diff options
author | Sorin Basca <sorinbasca@google.com> | 2023-04-27 19:25:18 +0000 |
---|---|---|
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | 2023-04-27 19:25:18 +0000 |
commit | 93f97578b11ca3bbf9a8ed11bd444c63cd9eee47 (patch) | |
tree | 238134d008177eed3ba497ad66ccc1c2feb5e58f | |
parent | 9c727483a6e538292e2eba7039a74c172bc61c63 (diff) | |
parent | c6b1ae499da7077f964cd5eb4470813f6e07f533 (diff) | |
download | snakeyaml-93f97578b11ca3bbf9a8ed11bd444c63cd9eee47.tar.gz |
Move snakeyaml to v1.32 am: 5352bb310d am: fafcd2ff88 am: c6b1ae499d
Original change: https://android-review.googlesource.com/c/platform/external/snakeyaml/+/2558671
Change-Id: If1f730e9583c505266008b8599a0e4d0e0add162
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
688 files changed, 49337 insertions, 36639 deletions
@@ -55,15 +55,12 @@ license { ], license_text: [ "LICENSE.txt", - "NOTICE", + "LICENSE", ], } snakeyaml_need_patch_src_files = [ - "src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java", - "src/main/java/org/yaml/snakeyaml/constructor/Constructor.java", "src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java", - "src/main/java/org/yaml/snakeyaml/representer/Representer.java", ] genrule { @@ -1,3 +1,19 @@ +name: "snakeyaml" +description: "a complete YAML 1.1 processor for JVM" third_party { + url { + type: HOMEPAGE + value: "https://bitbucket.org/snakeyaml/snakeyaml/" + } + url { + type: GIT + value: "https://bitbucket.org/snakeyaml/snakeyaml.git" + } + version: "snakeyaml-1.32" license_type: NOTICE + last_upgrade_date { + year: 2023 + month: 4 + day: 24 + } } @@ -3,22 +3,28 @@ ## Overview ## [YAML](http://yaml.org) is a data serialization format designed for human readability and interaction with scripting languages. -SnakeYAML is a YAML processor for the Java Virtual Machine. +SnakeYAML is a YAML 1.1 processor for the Java Virtual Machine version 7. +For YAML 1.2 (which is a superset of JSON) you may have a look at [SnakeYAML Engine](https://bitbucket.org/snakeyaml/snakeyaml-engine) ## SnakeYAML features ## -* a **complete** [YAML 1.1 processor](http://yaml.org/spec/1.1/current.html). In particular, SnakeYAML can parse all examples from the specification. +* a **complete** [YAML 1.1 processor](http://yaml.org/spec/1.1/current.html). (If you need YAML **1.2** support have a look [here](https://bitbucket.org/snakeyaml/snakeyaml-engine)). In particular, SnakeYAML can parse all examples from the specification. * Unicode support including UTF-8/UTF-16 input/output. * high-level API for serializing and deserializing native Java objects. * support for all types from the [YAML types repository](http://yaml.org/type/index.html). * relatively sensible error messages. +* when you plan to feed the parser with untrusted data please study the settings which allow to restrict incoming data. + ## Info ## - * [Changes](https://bitbucket.org/asomov/snakeyaml/wiki/Changes) - * [Documentation](https://bitbucket.org/asomov/snakeyaml/wiki/Documentation) + * [Changes](https://bitbucket.org/snakeyaml/snakeyaml/wiki/Changes) + * [Documentation](https://bitbucket.org/snakeyaml/snakeyaml/wiki/Documentation) + * [CVE and untrusted data](https://bitbucket.org/snakeyaml/snakeyaml/wiki/CVE%20&%20NIST.md) ## Contribute ## -* Mercurial DVCS is used to dance with the [source code](https://bitbucket.org/asomov/snakeyaml/src). -* If you find a bug in SnakeYAML, please [file a bug report](https://bitbucket.org/asomov/snakeyaml/issues?status=new&status=open). +* GIT [is now used](https://bitbucket.org/snakeyaml/snakeyaml/wiki/Migration%20to%20Git) to dance with the [source code](https://bitbucket.org/snakeyaml/snakeyaml/src). +* If you find a bug in SnakeYAML, please [file a bug report](https://bitbucket.org/snakeyaml/snakeyaml/issues?status=new&status=open). * You may discuss SnakeYAML at -[the mailing list](http://groups.google.com/group/snakeyaml-core).
\ No newline at end of file +[the mailing list](http://groups.google.com/group/snakeyaml-core). +* Telegram group is removed because of the spam +* [YAML community](https://matrix.to/#/%23chat:yaml.io) diff --git a/README.version b/README.version deleted file mode 100644 index 71ee1d22..00000000 --- a/README.version +++ /dev/null @@ -1,4 +0,0 @@ -URL: https://bitbucket.org/asomov/snakeyaml -Version: hg id 29a091e21588 -BugComponent: 99142 -Owners: iam diff --git a/docker-run-jdk11.sh b/docker-run-jdk11.sh new file mode 100755 index 00000000..37dd737e --- /dev/null +++ b/docker-run-jdk11.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +./run-in-docker.sh openjdk:11 -Pwith-java11-tests $@ diff --git a/docker-run-jdk17.sh b/docker-run-jdk17.sh new file mode 100755 index 00000000..0d9ee088 --- /dev/null +++ b/docker-run-jdk17.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +./run-in-docker.sh openjdk:17-alpine -Pwith-java11-tests $@ diff --git a/docker-run-jdk6.sh b/docker-run-jdk6.sh deleted file mode 100755 index 5904c908..00000000 --- a/docker-run-jdk6.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash -./docker-run.sh 6 - diff --git a/docker-run-jdk7.sh b/docker-run-jdk7.sh deleted file mode 100755 index b2c97828..00000000 --- a/docker-run-jdk7.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash -./docker-run.sh 7 - - diff --git a/docker-run-jdk8.sh b/docker-run-jdk8.sh index aaf10f07..ed893bfd 100755 --- a/docker-run-jdk8.sh +++ b/docker-run-jdk8.sh @@ -1,4 +1,2 @@ #!/usr/bin/env bash -./docker-run.sh 8 - - +./run-in-docker.sh openjdk:8-alpine -Pwith-java8-tests $@ @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script +# Maven Start Up Batch script # # Required ENV vars: # ------------------ @@ -36,6 +36,10 @@ if [ -z "$MAVEN_SKIP_RC" ] ; then + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi @@ -54,38 +58,16 @@ case "`uname`" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true;; Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; esac if [ -z "$JAVA_HOME" ] ; then @@ -130,13 +112,12 @@ if $cygwin ; then CLASSPATH=`cygpath --path --unix "$CLASSPATH"` fi -# For Migwn, ensure paths are in UNIX format before anything is touched +# For Mingw, ensure paths are in UNIX format before anything is touched if $mingw ; then [ -n "$M2_HOME" ] && M2_HOME="`(cd "$M2_HOME"; pwd)`" [ -n "$JAVA_HOME" ] && JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? fi if [ -z "$JAVA_HOME" ]; then @@ -168,7 +149,7 @@ if [ -z "$JAVACMD" ] ; then JAVACMD="$JAVA_HOME/bin/java" fi else - JAVACMD="`which java`" + JAVACMD="`\\unset -f command; \\command -v java`" fi fi @@ -184,27 +165,28 @@ fi CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - # traverses directory structure from process work directory to filesystem root # first directory with .mvn subdirectory is considered project base directory find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" while [ "$wdir" != '/' ] ; do - wdir=$(cd "$wdir/.."; pwd) if [ -d "$wdir"/.mvn ] ; then basedir=$wdir break fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround done echo "${basedir}" } @@ -216,10 +198,109 @@ concat_lines() { fi } -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" -# Provide a "standardized" way to retrieve the CLI args that will +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will # work with both Windows and non-Windows executions. MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" export MAVEN_CMD_LINE_ARGS @@ -228,7 +309,8 @@ WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain exec "$JAVACMD" \ $MAVEN_OPTS \ - -classpath "./.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" - + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.bat b/mvnw.bat deleted file mode 100644 index 7ca42b99..00000000 --- a/mvnw.bat +++ /dev/null @@ -1,177 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:chkMHome -if not "%M2_HOME%"=="" goto valMHome - -SET "M2_HOME=%~dp0.." -if not "%M2_HOME%"=="" goto valMHome - -echo. -echo Error: M2_HOME not found in your environment. >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation. >&2 -echo. -goto error - -:valMHome - -:stripMHome -if not "_%M2_HOME:~-1%"=="_\" goto checkMCmd -set "M2_HOME=%M2_HOME:~0,-1%" -goto stripMHome - -:checkMCmd -if exist "%M2_HOME%\bin\mvn.cmd" goto init - -echo. -echo Error: M2_HOME is set to an invalid directory. >&2 -echo M2_HOME = "%M2_HOME%" >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation >&2 -echo. -goto error -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -for %%i in ("%M2_HOME%"\boot\plexus-classworlds-*) do set CLASSWORLDS_JAR="%%i" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.home=%M2_HOME%" "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% @@ -1,30 +1,35 @@ +<?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> - <version>1.18-SNAPSHOT</version> + <version>1.32</version> <packaging>bundle</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.scm.id>bitbucket</project.scm.id> <release.repo.url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</release.repo.url> <snapshot.repo.url>https://oss.sonatype.org/content/repositories/snapshots/</snapshot.repo.url> - <maven.compiler.source>1.6</maven.compiler.source> - <maven.compiler.target>1.6</maven.compiler.target> + <maven.compiler.source>7</maven.compiler.source> + <maven.compiler.target>7</maven.compiler.target> + <maven.compiler.testSource>8</maven.compiler.testSource> + <maven.compiler.testTarget>8</maven.compiler.testTarget> <maven.javadoc.failOnError>false</maven.javadoc.failOnError> + <maven-bundle-plugin.version>5.1.8</maven-bundle-plugin.version> + <maven-resources-plugin.version>3.1.0</maven-resources-plugin.version><!-- for Github CI --> + <cobertura-maven-plugin.version>2.7</cobertura-maven-plugin.version> + <maven-site-plugin.version>3.12.1</maven-site-plugin.version> + <maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version> + <jdk9-illegal-access-level>deny</jdk9-illegal-access-level> </properties> <name>SnakeYAML</name> <description>YAML 1.1 parser and emitter for Java</description> <inceptionYear>2008</inceptionYear> - <url>http://www.snakeyaml.org</url> + <url>https://bitbucket.org/snakeyaml/snakeyaml</url> <issueManagement> <system>Bitbucket</system> - <url>https://bitbucket.org/asomov/snakeyaml/issues</url> + <url>https://bitbucket.org/snakeyaml/snakeyaml/issues</url> </issueManagement> - <!--ciManagement> - <system>jenkins</system> - <url>https://snakeyaml.ci.cloudbees.com/job/SnakeYAML/</url> - </ciManagement--> <mailingLists> <mailingList> <name>SnakeYAML developers and users List</name> @@ -32,11 +37,11 @@ </mailingList> </mailingLists> <scm> - <connection>scm:hg:http://bitbucket.org/asomov/snakeyaml</connection> - <developerConnection>scm:hg:ssh://hg@bitbucket.org/asomov/snakeyaml</developerConnection> - <url>https://bitbucket.org/asomov/snakeyaml/src</url> - <tag>HEAD</tag> - </scm> + <connection>scm:git:http://bitbucket.org/snakeyaml/snakeyaml</connection> + <developerConnection>scm:git:ssh://git@bitbucket.org/snakeyaml/snakeyaml</developerConnection> + <url>https://bitbucket.org/snakeyaml/snakeyaml/src</url> + <tag>snakeyaml-1.32</tag> + </scm> <licenses> <license> <name>Apache License, Version 2.0</name> @@ -55,38 +60,30 @@ <name>Alexander Maslov</name> <email>alexander.maslov@gmail.com</email> </developer> - <developer> - <id>Jordan</id> - <name>Jordan Angold</name> - <email>jordanangold@gmail.com</email> - </developer> </developers> - <prerequisites> - <maven>3.0.5</maven> - </prerequisites> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> - <version>4.12</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring</artifactId> - <version>2.5.6</version> + <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.velocity</groupId> - <artifactId>velocity</artifactId> - <version>1.6.2</version> + <artifactId>velocity-engine-core</artifactId> + <version>2.3</version> <scope>test</scope> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> - <version>1.6</version> + <version>2.11.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>1.18.24</version> <scope>test</scope> </dependency> </dependencies> @@ -97,7 +94,7 @@ <url>${release.repo.url}</url> </repository> <snapshotRepository> - <id>sonatype-nexus-snapshots</id> + <id>sonatype-nexus-staging</id> <name>Sonatype Nexus Snapshots</name> <url>${snapshot.repo.url}</url> <uniqueVersion>false</uniqueVersion> @@ -114,21 +111,79 @@ <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-resources-plugin</artifactId> + <version>${maven-resources-plugin.version}</version> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> - <version>2.10.3</version> + <version>3.4.1</version> + <configuration> + <excludePackageNames>org.yaml.snakeyaml.external.*</excludePackageNames> + </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> - <version>3.5</version> + <version>${maven-site-plugin.version}</version> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + <version>3.2.2</version> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>cobertura-maven-plugin</artifactId> + <version>${cobertura-maven-plugin.version}</version> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.10.1</version> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>3.3.0</version> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <version>${maven-surefire-plugin.version}</version> + <configuration> + <environmentVariables> + <EnvironmentKey1>EnvironmentValue1</EnvironmentKey1> + <EnvironmentEmpty /> + </environmentVariables> + </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-enforcer-plugin</artifactId> + <version>3.1.0</version> + <executions> + <execution> + <id>enforce-maven</id> + <goals> + <goal>enforce</goal> + </goals> + <configuration> + <rules> + <requireMavenVersion> + <version>3.3.0</version> + </requireMavenVersion> + </rules> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> - <version>3.5.1</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> @@ -138,7 +193,6 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> - <version>2.19.1</version> <configuration> <argLine>-Xmx512m</argLine> <includes> @@ -159,37 +213,9 @@ </configuration> </plugin> <plugin> - <groupId>org.codehaus.mojo</groupId> - <artifactId>cobertura-maven-plugin</artifactId> - <version>2.7</version> - <configuration> - <check> - <totalBranchRate>80</totalBranchRate> - <totalLineRate>95</totalLineRate> - </check> - <formats> - <format>html</format> - <format>xml</format> - </formats> - <instrumentation> - <excludes> - <exclude>org/yaml/snakeyaml/external/**</exclude> - </excludes> - </instrumentation> - </configuration> - <executions> - <execution> - <goals> - <goal>clean</goal> - <goal>check</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-changes-plugin</artifactId> - <version>2.11</version> + <version>2.12.1</version> <executions> <execution> <id>validate-changes</id> @@ -206,11 +232,11 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> - <version>3.0.0</version> + <version>3.2.1</version> <executions> <execution> <goals> - <goal>jar</goal> + <goal>jar-no-fork</goal> </goals> </execution> </executions> @@ -218,11 +244,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> - <configuration> - <links> - <link>http://java.sun.com/javase/6/docs/api/</link> - </links> - </configuration> + <version>3.4.1</version> <executions> <execution> <id>attach-javadocs</id> @@ -264,7 +286,7 @@ <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> - <version>3.0.1</version> + <version>${maven-bundle-plugin.version}</version> <extensions>true</extensions> <configuration> <instructions> @@ -273,13 +295,13 @@ !org.yaml.snakeyaml.external*, org.yaml.snakeyaml.*;version=${project.version} </Export-Package> - <Bundle-RequiredExecutionEnvironment>J2SE-1.5</Bundle-RequiredExecutionEnvironment> + <Automatic-Module-Name>org.yaml.snakeyaml</Automatic-Module-Name> </instructions> </configuration> </plugin> <plugin> <artifactId>maven-site-plugin</artifactId> - <version>3.4</version> + <version>${maven-site-plugin.version}</version> <executions> <execution> <id>attach-descriptor</id> @@ -289,6 +311,31 @@ </execution> </executions> </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-release-plugin</artifactId> + <version>2.5.3</version> + <configuration> + <autoVersionSubmodules>true</autoVersionSubmodules> + <useReleaseProfile>false</useReleaseProfile> + <releaseProfiles>android,release</releaseProfiles> + <goals>deploy nexus-staging:release</goals> + </configuration> + </plugin> + <plugin> + <groupId>org.sonatype.plugins</groupId> + <artifactId>nexus-staging-maven-plugin</artifactId> + <!-- the version is compatible with Nexus, do not change --> + <version>1.6.8</version> + <extensions>true</extensions> + <configuration> + <serverId>sonatype-nexus-staging</serverId> + <nexusUrl>https://oss.sonatype.org/</nexusUrl> + <autoReleaseAfterClose>false</autoReleaseAfterClose> + <keepStagingRepositoryOnFailure>true</keepStagingRepositoryOnFailure> + <keepStagingRepositoryOnCloseRuleFailure>true</keepStagingRepositoryOnCloseRuleFailure> + </configuration> + </plugin> </plugins> </build> <reporting> @@ -296,9 +343,9 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-changes-plugin</artifactId> - <version>2.11</version> + <version>2.12.1</version> <configuration> - <issueLinkTemplate>https://bitbucket.org/asomov/snakeyaml/issues/%ISSUE%</issueLinkTemplate> + <issueLinkTemplate>https://bitbucket.org/snakeyaml/snakeyaml/issues/%ISSUE%</issueLinkTemplate> </configuration> <reportSets> <reportSet> @@ -311,23 +358,12 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> - <version>2.19.1</version> + <version>${maven-surefire-plugin.version}</version> <configuration> <showSuccess>true</showSuccess> </configuration> </plugin> <plugin> - <groupId>org.codehaus.mojo</groupId> - <artifactId>cobertura-maven-plugin</artifactId> - <version>2.6</version> - <configuration> - <formats> - <format>html</format> - <format>xml</format> - </formats> - </configuration> - </plugin> - <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <reportSets> @@ -360,7 +396,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-toolchains-plugin</artifactId> - <version>1.1</version> + <version>3.1.0</version> <executions> <execution> <phase>validate</phase> @@ -370,45 +406,151 @@ </execution> </executions> <configuration> - <toolchains> - <jdk> - <version>${maven.compiler.target}</version> - </jdk> - </toolchains> + <toolchains> + <jdk> + <version>${maven.compiler.testTarget}</version> + </jdk> + </toolchains> </configuration> </plugin> </plugins> </build> </profile> <profile> - <id>with-java8-tests</id> - <properties> - <maven.compiler.source>1.8</maven.compiler.source> - <maven.compiler.target>1.8</maven.compiler.target> - </properties> - <build> - <plugins> - <plugin> - <groupId>org.codehaus.mojo</groupId> - <artifactId>build-helper-maven-plugin</artifactId> - <version>1.10</version> - <executions> - <execution> - <id>add-java8-test-source</id> - <phase>generate-test-sources</phase> - <goals> - <goal>add-test-source</goal> - </goals> - <configuration> - <sources> - <source>${basedir}/src/test/java8/</source> - </sources> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> + <id>with-coverage</id> + <build> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>cobertura-maven-plugin</artifactId> + <configuration> + <check> + <totalBranchRate>80</totalBranchRate> + <totalLineRate>95</totalLineRate> + </check> + <formats> + <format>html</format> + <format>xml</format> + </formats> + <instrumentation> + <excludes> + <exclude>org/yaml/snakeyaml/external/**</exclude> + </excludes> + </instrumentation> + </configuration> + <executions> + <execution> + <goals> + <goal>clean</goal> + <goal>check</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + <reporting> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>cobertura-maven-plugin</artifactId> + <configuration> + <check> + <branchRate>85</branchRate> + <lineRate>85</lineRate> + <haltOnFailure>true</haltOnFailure> + </check> + <formats> + <format>html</format> + <format>xml</format> + </formats> + </configuration> + <reportSets> + <reportSet> + <reports> + <report>cobertura</report> + </reports> + </reportSet> + </reportSets> + </plugin> + </plugins> + </reporting> + </profile> + <profile> + <id>with-java8-tests</id> + <properties> + <maven.compiler.testSource>1.8</maven.compiler.testSource> + <maven.compiler.testTarget>1.8</maven.compiler.testTarget> + </properties> + <build> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <executions> + <execution> + <id>add-java8-test-source</id> + <phase>generate-test-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source>${basedir}/src/test/java8/</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + <profile> + <id>with-java11-tests</id> + <properties> + <maven.compiler.testSource>11</maven.compiler.testSource> + <maven.compiler.testTarget>11</maven.compiler.testTarget> + </properties> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <configuration> + <argLine>--illegal-access=${jdk9-illegal-access-level} -Xmx512m</argLine> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <compilerArgs> + <!-- arg>-Xlint:unchecked</arg --> + <arg>-Xlint:deprecation</arg> + </compilerArgs> + </configuration> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <executions> + <execution> + <id>add-java11-test-source</id> + <phase>generate-test-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source>${basedir}/src/test/java8/</source> + <source>${basedir}/src/test/java11/</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> </profile> <profile> <id>release</id> @@ -423,7 +565,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> - <version>1.6</version> + <version>3.0.1</version> <executions> <execution> <id>sign-artifacts</id> @@ -444,12 +586,12 @@ <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> - <version>3.0.3</version> + <version>3.0.5</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> - <version>3.6</version> + <version>3.19.0</version> </plugin> </plugins> </build> @@ -458,22 +600,22 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> - <version>2.5</version> + <version>3.3.0</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> - <version>3.0.3</version> + <version>3.0.5</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> - <version>3.6</version> + <version>3.19.0</version> <configuration> <linkXref>true</linkXref> <sourceEncoding>utf-8</sourceEncoding> <minimumTokens>100</minimumTokens> - <targetJdk>1.5</targetJdk> + <targetJdk>1.8</targetJdk> <excludes> <exclude>**/external/*.java</exclude> </excludes> @@ -485,15 +627,18 @@ <profile> <id>android</id> <properties> - <android.src>${project.build.directory}/android/src/</android.src> + <android.src>${project.build.directory}/android/src</android.src> + <android.src.main>${android.src}/main/java</android.src.main> + <android.src.test>${android.src}/test/java</android.src.test> <android.classes>${project.build.directory}/android/classes/</android.classes> <android.test.classes>${project.build.directory}/android/test-classes/</android.test.classes> </properties> <build> <plugins> <plugin> + <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> - <version>2.7</version> + <version>${maven-resources-plugin.version}</version> <executions> <execution> <id>copy-src-for-android</id> @@ -502,7 +647,7 @@ <goal>copy-resources</goal> </goals> <configuration> - <outputDirectory>${android.src}</outputDirectory> + <outputDirectory>${android.src.main}</outputDirectory> <resources> <resource> <directory>${basedir}/src/main/java</directory> @@ -515,6 +660,25 @@ </configuration> </execution> <execution> + <id>copy-test-src-for-android</id> + <phase>generate-sources</phase> + <goals> + <goal>copy-resources</goal> + </goals> + <configuration> + <outputDirectory>${android.src.test}</outputDirectory> + <resources> + <resource> + <directory>${basedir}/src/test/java</directory> + <filtering>false</filtering> + <excludes> + <exclude>org/yaml/snakeyaml/introspector/MethodProperty.java</exclude> + </excludes> + </resource> + </resources> + </configuration> + </execution> + <execution> <id>copy-test-resources-for-android</id> <phase>process-test-resources</phase> <goals> @@ -525,6 +689,7 @@ <resources> <resource> <directory>${basedir}/src/test/resources</directory> + <filtering>true</filtering> </resource> </resources> </configuration> @@ -540,7 +705,7 @@ <patchDirectory>${basedir}/src/patches/android/</patchDirectory> <targetDirectory>${android.src}</targetDirectory> <skipApplication>false</skipApplication> - <strip>4</strip> + <strip>2</strip> </configuration> <executions> <execution> @@ -550,8 +715,7 @@ <goal>apply</goal> </goals> <configuration> - <patchTrackingFile>${project.build.directory}/android/patches-applied.txt - </patchTrackingFile> + <patchTrackingFile>${project.build.directory}/android/patches-applied.txt</patchTrackingFile> <naturalOrderProcessing>true</naturalOrderProcessing> </configuration> </execution> @@ -560,7 +724,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> - <version>1.8</version> + <version>3.1.0</version> <executions> <execution> <id>build-for-android</id> @@ -574,15 +738,18 @@ <mkdir dir="${android.test.classes}" /> <!-- compile patched sources --> - <javac srcdir="${android.src}" destdir="${android.classes}" classpath="${android.classes}" encoding="${project.build.sourceEncoding}" target="1.5" source="1.5" debug="true" includeantruntime="false" fork="true" /> + <javac srcdir="${android.src.main}" destdir="${android.classes}" classpath="${android.classes}" encoding="${project.build.sourceEncoding}" target="1.7" source="1.7" debug="true" includeantruntime="true" fork="true" /> <!-- compile test classes. Exclude some - not for BeanAccess.FIELD --> - <javac srcdir="${basedir}/src/test/java:${basedir}/src/test/resources" destdir="${android.test.classes}" classpath="${android.classes}:${android.test.classes}:${junit:junit:jar}:${org.springframework:spring:jar}:${org.apache.velocity:velocity:jar}:${joda-time:joda-time:jar}" encoding="${project.build.sourceEncoding}" target="1.5" source="1.5" debug="true" includeantruntime="false" fork="true"> + <javac srcdir="${android.src.test}:${basedir}/src/test/resources" destdir="${android.test.classes}" classpath="${android.classes}:${android.test.classes}:${junit:junit:jar}:${org.apache.velocity:velocity:jar}:${joda-time:joda-time:jar}:${commons-io:commons-io:jar}:${commons-lang:commons-lang:jar}:${org.hamcrest:hamcrest-core:jar}:${org.projectlombok:lombok:jar}" encoding="${project.build.sourceEncoding}" target="1.7" source="1.7" debug="true" includeantruntime="true" fork="true"> + <exclude name="org/yaml/snakeyaml/introspector/MethodPropertyTest.java" /> <exclude name="org/yaml/snakeyaml/representer/FilterPropertyToDumpTest.java" /> <exclude name="org/yaml/snakeyaml/issues/issue60/CustomOrderTest.java" /> <exclude name="org/yaml/snakeyaml/issues/issue29/FlexibleScalarStylesInJavaBeanTest.java" /> - + <!-- uses filtered resources. Additional tricks needed to be able to run under current build --> + <exclude name="org/yaml/snakeyaml/issues/issue318/ContextClassLoaderTest.java" /> + <exclude name="org/yaml/snakeyaml/emitter/template/VelocityTest.java" /> </javac> </target> @@ -601,8 +768,7 @@ </goals> <configuration> <classesDirectory>${android.classes}</classesDirectory> - <reportsDirectory>${project.build.directory}/android/surefire-reports - </reportsDirectory> + <reportsDirectory>${project.build.directory}/android/surefire-reports</reportsDirectory> <testClassesDirectory>${android.test.classes}</testClassesDirectory> <!-- We ignore test failures for android build at the moment. @@ -633,5 +799,27 @@ </plugins> </build> </profile> + <profile> + <id>reformat</id> + <build> + <plugins> + <plugin> + <groupId>net.revelc.code.formatter</groupId> + <artifactId>formatter-maven-plugin</artifactId> + <executions> + <execution> + <goals> + <goal>format</goal> + </goals> + <configuration> + <configFile>src/etc/eclipse-java-google-style.xml</configFile> + <encoding>UTF-8</encoding> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles> </project> diff --git a/pom.yaml b/pom.yaml deleted file mode 100644 index 2c2e39ee..00000000 --- a/pom.yaml +++ /dev/null @@ -1,360 +0,0 @@ -modelVersion: 4.0.0 -groupId: org.yaml -artifactId: snakeyaml -version: 1.17-SNAPSHOT -packaging: jar # TODO must be bundle -properties: {project.scm.id: bitbucket, project.build.sourceEncoding: UTF-8} -name: SnakeYAML -description: YAML 1.1 parser and emitter for Java -inceptionYear: '2008' -url: http://www.snakeyaml.org -issueManagement: {system: Bitbucket, url: 'https://bitbucket.org/asomov/snakeyaml/issues'} -mailingLists: -- {name: SnakeYAML developers and users List, post: snakeyaml-core@googlegroups.com} -scm: {connection: 'scm:hg:http://bitbucket.org/asomov/snakeyaml', developerConnection: 'scm:hg:https://bitbucket.org/asomov/snakeyaml', - tag: HEAD, url: 'https://bitbucket.org/asomov/snakeyaml/src'} -licenses: -- {distribution: repo, name: 'Apache License, Version 2.0', url: 'http://www.apache.org/licenses/LICENSE-2.0.txt'} -developers: -- {email: public.somov@gmail.com, id: asomov, name: Andrey Somov} -- {email: alexander.maslov@gmail.com, id: maslovalex, name: Alexander Maslov} -- {email: jordanangold@gmail.com, id: Jordan, name: Jordan Angold} -prerequisites: {maven: 3.3.1} -dependencies: -- {artifactId: junit, groupId: junit, optional: false, scope: test, type: jar, version: '4.12'} -- {artifactId: spring, groupId: org.springframework, optional: false, scope: test, - type: jar, version: 2.5.6} -- {artifactId: velocity, groupId: org.apache.velocity, optional: false, scope: test, - type: jar, version: 1.6.2} -- {artifactId: joda-time, groupId: joda-time, optional: false, scope: test, type: jar, - version: '1.6'} -distributionManagement: - repository: {id: sonatype-nexus-staging, layout: default, name: Nexus Release Repository, - uniqueVersion: true, url: 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'} - snapshotRepository: {id: sonatype-nexus-snapshots, layout: default, name: Sonatype Nexus Snapshots, - uniqueVersion: false, url: 'https://oss.sonatype.org/content/repositories/snapshots/'} -build: - pluginManagement: - plugins: - - {artifactId: maven-site-plugin, extensions: false, groupId: org.apache.maven.plugins, - inherited: true, version: '3.4'} - plugins: - - artifactId: maven-compiler-plugin - configuration: {source: '1.5', target: '1.5', encoding: '${project.build.sourceEncoding}'} - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '3.3' - - artifactId: maven-surefire-plugin - configuration: - argLine: -Xmx512m - includes: {include: '**/*Test.java'} - excludes: {exclude: '**/ParallelTest.java'} - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: 2.18.1 - - artifactId: maven-eclipse-plugin - configuration: {buildOutputDirectory: bin} - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '2.10' - - artifactId: cobertura-maven-plugin - configuration: - check: {totalBranchRate: '80', totalLineRate: '95'} - formats: {format: xml} - instrumentation: - excludes: {exclude: org/yaml/snakeyaml/external/**} - executions: - - goals: [clean, check] - id: default - inherited: true - priority: 0 - extensions: false - groupId: org.codehaus.mojo - inherited: true - version: '2.7' - - artifactId: maven-changes-plugin - executions: - - configuration: {failOnError: 'true'} - goals: [changes-validate] - id: validate-changes - inherited: true - phase: pre-site - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '2.11' - - artifactId: maven-source-plugin - executions: - - goals: [jar] - id: default - inherited: true - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '2.4' - - artifactId: maven-javadoc-plugin - configuration: - links: {link: 'http://java.sun.com/javase/6/docs/api/'} - executions: - - goals: [jar] - id: attach-javadocs - inherited: true - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: 2.10.3 - - artifactId: maven-license-plugin - configuration: - header: src/etc/header.txt - quiet: 'false' - failIfMissing: 'true' - aggregate: 'false' - includes: {include: src/**/*.java} - excludes: {exclude: src/main/java/org/yaml/snakeyaml/external/**} - useDefaultExcludes: 'true' - useDefaultMapping: 'true' - strictCheck: 'true' - encoding: UTF-8 - executions: - - goals: [format] - id: default - inherited: true - phase: site - priority: 0 - extensions: false - groupId: com.mycila.maven-license-plugin - inherited: true - version: 1.10.b1 - - artifactId: maven-bundle-plugin - configuration: - instructions: {_nouses: 'true', Export-Package: "!org.yaml.snakeyaml.external*,\n\ - \ org.yaml.snakeyaml.*;version=${project.version}", - Bundle-RequiredExecutionEnvironment: J2SE-1.5} - extensions: true - groupId: org.apache.felix - inherited: true - version: 2.5.4 - - artifactId: maven-site-plugin - executions: - - goals: [attach-descriptor] - id: attach-descriptor - inherited: true - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '3.4' -profiles: -- activation: {activeByDefault: false, jdk: '[1.8,)'} - build: - plugins: - - artifactId: maven-javadoc-plugin - configuration: {additionalparam: '-Xdoclint:none'} - extensions: false - groupId: org.apache.maven.plugins - inherited: true - - artifactId: maven-site-plugin - configuration: - reportPlugins: - plugin: - groupId: org.apache.maven.plugins - artifactId: maven-javadoc-plugin - configuration: {additionalparam: '-Xdoclint:none'} - extensions: false - groupId: org.apache.maven.plugins - inherited: true - id: jdk8 - source: pom -- build: - plugins: - - artifactId: maven-compiler-plugin - configuration: {source: '1.8', target: '1.8'} - extensions: false - groupId: org.apache.maven.plugins - inherited: true - - artifactId: build-helper-maven-plugin - executions: - - configuration: - sources: {source: '${basedir}/src/test/java8/'} - goals: [add-test-source] - id: add-java8-test-source - inherited: true - phase: generate-test-sources - priority: 0 - extensions: false - groupId: org.codehaus.mojo - inherited: true - version: '1.10' - id: with-java8-tests - source: pom -- activation: - activeByDefault: false - property: {name: performRelease, value: 'true'} - build: - plugins: - - artifactId: maven-gpg-plugin - executions: - - goals: [sign] - id: sign-artifacts - inherited: true - phase: verify - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '1.6' - id: release - source: pom -- build: - plugins: - - {artifactId: findbugs-maven-plugin, extensions: false, groupId: org.codehaus.mojo, - inherited: true, version: 3.0.2} - - {artifactId: maven-pmd-plugin, extensions: false, groupId: org.apache.maven.plugins, - inherited: true, version: '3.5'} - id: findbugs - reporting: - excludeDefaults: false - plugins: - - {artifactId: maven-jxr-plugin, groupId: org.apache.maven.plugins, inherited: true, - version: '2.5'} - - {artifactId: findbugs-maven-plugin, groupId: org.codehaus.mojo, inherited: true, - version: 3.0.0} - - artifactId: maven-pmd-plugin - configuration: - linkXref: 'true' - sourceEncoding: utf-8 - minimumTokens: '100' - targetJdk: '1.5' - excludes: {exclude: '**/external/*.java'} - groupId: org.apache.maven.plugins - inherited: true - version: '3.4' - source: pom -- build: - plugins: - - artifactId: maven-resources-plugin - executions: - - configuration: - outputDirectory: ${android.src} - resources: - resource: - directory: ${basedir}/src/main/java - filtering: 'false' - excludes: {exclude: org/yaml/snakeyaml/introspector/MethodProperty.java} - goals: [copy-resources] - id: copy-src-for-android - inherited: true - phase: generate-sources - priority: 0 - - configuration: - outputDirectory: ${android.test.classes} - resources: - resource: {directory: '${basedir}/src/test/resources'} - goals: [copy-resources] - id: copy-test-resources-for-android - inherited: true - phase: process-test-resources - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '2.7' - - artifactId: maven-patch-plugin - configuration: {patchDirectory: '${basedir}/src/patches/android/', targetDirectory: '${android.src}', - skipApplication: 'false', strip: '4'} - executions: - - configuration: {patchTrackingFile: '${project.build.directory}/android/patches-applied.txt', - naturalOrderProcessing: 'true'} - goals: [apply] - id: android-patches - inherited: true - phase: process-sources - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '1.2' - - artifactId: maven-antrun-plugin - executions: - - configuration: - target: - javac: {} - goals: [run] - id: build-for-android - inherited: true - phase: compile - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - version: '1.8' - - artifactId: maven-surefire-plugin - executions: - - configuration: {classesDirectory: '${android.classes}', reportsDirectory: '${project.build.directory}/android/surefire-reports', - testClassesDirectory: '${android.test.classes}', testFailureIgnore: 'true'} - goals: [test] - id: test-android - inherited: true - phase: test - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - - artifactId: maven-jar-plugin - executions: - - configuration: {classesDirectory: '${android.classes}', classifier: android} - goals: [jar] - id: package-android-jar - inherited: true - phase: package - priority: 0 - extensions: false - groupId: org.apache.maven.plugins - inherited: true - id: android - properties: {android.test.classes: '${project.build.directory}/android/test-classes/', - android.classes: '${project.build.directory}/android/classes/', android.src: '${project.build.directory}/android/src/'} - source: pom -reporting: - excludeDefaults: false - plugins: - - artifactId: maven-changes-plugin - configuration: {issueLinkTemplate: 'https://bitbucket.org/asomov/snakeyaml/issues/%ISSUE%'} - groupId: org.apache.maven.plugins - inherited: true - reportSets: - - id: default - inherited: true - reports: [changes-report] - version: '2.11' - - artifactId: maven-surefire-report-plugin - configuration: {showSuccess: 'true'} - groupId: org.apache.maven.plugins - inherited: true - version: 2.18.1 - - artifactId: cobertura-maven-plugin - configuration: - formats: {format: xml} - groupId: org.codehaus.mojo - inherited: true - version: '2.6' - - artifactId: maven-javadoc-plugin - groupId: org.apache.maven.plugins - inherited: true - reportSets: - - configuration: {doctitle: 'API for ${project.name} ${project.version}', windowtitle: 'API - for ${project.name} ${project.version}', testDoctitle: 'Test API for ${project.name} - ${project.version}', testWindowtitle: 'Test API for ${project.name} ${project.version}'} - id: html - inherited: true - reports: [javadoc] - version: 2.10.1 - - - diff --git a/docker-run.sh b/run-in-docker.sh index 3abaa887..4a4def2a 100755 --- a/docker-run.sh +++ b/run-in-docker.sh @@ -1,16 +1,10 @@ #!/usr/bin/env bash -if [ "$#" -ne 1 ] -then - echo "Usage: docker-run.sh <JDK number> (number can be 6, 7, 8)" - exit 1 -fi - docker run --rm -it \ -u `id -u`:`id -g` \ -v `pwd`:/work \ -v ~:/my-home \ -e "HOME=/my-home" \ -w /work \ - maven:3-jdk-$1 \ - mvn -Dmaven.repo.local=/my-home/.m2/repository clean test + $1 \ + ./mvnw -Dmaven.repo.local=/my-home/.m2/repository clean test ${@:2} diff --git a/src/changes/changes.xml b/src/changes/changes.xml index a9274306..00cb523e 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -3,10 +3,386 @@ xsi:schemaLocation="http://maven.apache.org/changes/1.0.0 http://maven.apache.org/plugins/maven-changes-plugin/xsd/changes-1.0.0.xsd"> <properties> <title>YAML 1.1 parser and emitter</title> - <author email="public.somov@gmail.com">Andrey Somov</author> </properties> <body> - <release version="1.18-SNAPSHOT" date="in Mercurial" description="Maintenance"> + <release version="1.32" date="2022-09-12" description="Maintenance"> + <action dev="asomov" type="fix" issue="543"> + Add a test for issue 543 (thanks to Henry Lin) + </action> + <action dev="asomov" type="fix" issue="547"> + Set the limit for incoming data to prevent a CVE report in NIST + By default it is 3 MB + </action> + <action dev="asomov" type="update"> + Format the source with Google style. + Info: https://stackoverflow.com/questions/49712148/maven-plugin-for-auto-formatting-code-to-match-google-checkstyle + Format: https://raw.githubusercontent.com/google/styleguide/gh-pages/eclipse-java-google-style.xml + Activation: ./mvnw clean install site -Preformat + </action> + <action dev="maslovalex" type="fix" issue="544"> + Support unescaped unicode characters for double-quoted scalars (thanks to Florian Waltenberger) + </action> + </release> + <release version="1.31" date="2022-08-27" description="Maintenance"> + <action dev="maslovalex" type="update"> + JDK 8 is required for tests + </action> + <action dev="asomov" type="update" issue="539"> + Fix false positive CVE-2020-13936 (thanks to Gaรฉtan Collaud) + </action> + <action dev="asomov" type="fix" issue="537"> + Improved RE for integers (thanks to Petr Pucil) + </action> + <action dev="asomov" type="fix" issue="530"> + Add an opportunity to restrict data matched with Regular Expressions + to avoid possible attack when RE takes too many resources (detected by OSS-Fuzz) + </action> + <action dev="asomov" type="fix" issue="529"> + Show proper error message for invalid !!float and !!int scalar (detected by OSS-Fuzz) + </action> + <action dev="asomov" type="fix" issue="525"> + Restrict nested depth for collections to avoid DoS attacks (detected by OSS-Fuzz) + </action> + <action dev="asomov" type="add" issue="525"> + Add test for stackoverflow + </action> + <action dev="maslovalex" type="fix" issue="522"> + Deserializing key "on" fails with Exception + </action> + <action dev="asomov" type="update"> + Merged PR #7: https://bitbucket.org/snakeyaml/snakeyaml/pull-requests/7 (2022-04-04) + </action> + <action dev="asomov" type="update"> + Do not emit global TAGs by not keeping them in Parser + (breaks https://code.google.com/archive/p/snakeyaml/issues/149) + </action> + <action dev="asomov" type="add"> + Add an example with Lombok and ENV variable substitution (2021-12-29) + </action> + <action dev="asomov" type="update"> + Fix issues with comments + </action> + <action dev="asomov" type="update" issue="517"> + Recognise issue with trailing TAB + </action> + </release> + <release version="1.30" date="2021-12-14" description="Maintenance"> + <action dev="asomov" type="fix" issue="516"> + Remove snakeyaml.org + </action> + <action dev="asomov" type="update"> + Migrate to https://bitbucket.org/snakeyaml/snakeyaml (2021-10-23) + </action> + <action dev="asomov" type="update"> + Fix issues with comments + </action> + <action dev="asomov" type="fix" issue="506"> + Improve parsing a number starting with 0x (2021-06-28) + Take the Float pattern from ruamel: https://pypi.org/project/ruamel.yaml + </action> + </release> + <release version="1.29" date="2021-06-08" description="Maintenance"> + <action dev="Wolf2323" type="fix"> + Fix Events ordering and improve Node-Comment association (2021-05-13) + </action> + <action dev="asomov" type="fix"> + Fix corner case for comments where blank lines after plain token (2021-03-02) + </action> + <action dev="asomov" type="add"> + Add a test for issue 500 (2021-03-14) + </action> + <action dev="asomov" type="remove"> + Remove unused variable (2021-02-28) + </action> + </release> + <release version="1.28" date="2021-02-22" description="Maintenance"> + <action dev="maslovalex" type="fix"> + Fix tests to work on Windows (2021-02-19) + </action> + <action dev="asomov" type="add"> + Add enumCaseSensitive property to LoaderOptions to control constructing enum with case sensitivity (2021-01-05) + </action> + <action dev="asomov" type="fix" issue="493"> + ENV substitution default can contain special characters (2021-01-03) + </action> + <action dev="asomov" type="add"> + Allow for read and write YAML with Comments (2020-11-01) + </action> + <action dev="asomov" type="fix" issue="485"> + Alias names are too permissive compared to libyaml and future spec. + Follow https://github.com/yaml/yaml-spec/blob/master/rfc/RFC-0003.md (2020-10-06) + </action> + </release> + <release version="1.27" date="2020-08-31" description="Maintenance"> + <action dev="asomov" type="fix" issue="481"> + Serialize anchors that are not used by any alias (2020-08-14) + </action> + <action dev="asomov" type="fix" issue="416"> + Add indentWithIndicator option to improve dumping sequences (2020-07-14) + </action> + <action dev="asomov" type="fix" issue="480"> + Anchor should allow non ascii characters while dumping (2020-06-29) + </action> + <action dev="asomov" type="update" issue="remove"> + Remove Spring related tests because they are outdated and upgrading to Spring 5 + makes the tests fail under JDK 7 (2020-05-02) + </action> + <action dev="asomov" type="update" issue="476"> + Make constructor of EnvScalarConstructor public (2020-04-24) + </action> + <action dev="asomov" type="fix" issue="474"> + Parse the value of byte and short after a narrowing primitive conversion (2020-04-16) + </action> + <action dev="asomov" type="add"> + Add test for different Line Break Characters in the error message (2020-03-09) + </action> + <action dev="asomov" type="update"> + Fix yet another OWASP false positive. It complains that the Spring controller makes SnakeYAML insecure + even though SnakeYAML does not use Spring controller and does not depend on Spring (but the tests do). + Bump spring.version from 3.2.17.RELEASE to 5.2.4.RELEASE (2020-03-08) + </action> + <action dev="asomov" type="update"> + Migrated to GIT (2020-02-29) + </action> + </release> + <release version="1.26" date="2020-02-28" description="Maintenance"> + <action dev="asomov" type="fix" issue="377"> + Allow configuration for preventing billion laughs attack (2020-02-24) + </action> + <action dev="asomov" type="update"> + Update Maven wrapper (2020-01-18) + </action> + <action dev="asomov" type="fix" issue="468"> + Parse ENV variables similar to how it works in docker-compose (2019-12-25) + </action> + <action dev="asomov" type="fix" issue="468"> + Allow non ASCII characters in the anchor names (2019-12-23) + </action> + <action dev="asomov" type="update" issue="462"> + Clean up composer internal maps after construction. Should not have any impact but + it does not harm (2019-10-25) + </action> + <action dev="asomov" type="update" issue="459"> + The '!' tag now works the same way as for PyYAML. (12 is parsed as int instead of string) + The spec files are modified (spec-08-07.canonical spec-08-07.data) + </action> + <action dev="asomov" type="add"> + Add test for not implemented "!" tag (2019-10-11) + </action> + <action dev="asomov" type="update"> + Refactor Events: expose Event.ID via a getter (2019-10-05) + </action> + <action dev="asomov" type="update"> + Refactor ScalarAnalysis: make it immutable (2019-09-28) + </action> + <action dev="asomov" type="add" issue="454"> + Add example for integer without time pattern (2019-08-22) + </action> + </release> + <release version="1.25" date="2019-08-13" description="Maintenance"> + <action dev="asomov" type="update"> + Deprecate setting tags in TypeDescription (2019-06-23) + </action> + <action dev="asomov" type="fix" issue="449"> + Add test for issue 449 (2019-06-19) + </action> + <action dev="asomov" type="add" issue="441"> + Restore the way to get anchor for a Node (2019-04-13) + </action> + <action dev="asomov" type="fix" issue="437"> + Introduce setting to keep !!str tag for String even when it contains non-printable chars (2019-03-24) + </action> + <action dev="asomov" type="update"> + Update plugin versions (2019-03-04) + </action> + </release> + <release version="1.24" date="2019-02-28" description="Maintenance"> + <action dev="asomov" type="update"> + Refactor BaseConstructor: Factored out postponed mapping logic so subclasses can effectively + override constructMapping2ndStep() and delegate to the postponed mapping logic. + This is backported from SnakeYAML engine (2019-01-26) + </action> + <action dev="asomov" type="fix" issue="431"> + Customize simple key length when dumping (2019-01-17) + </action> + <action dev="asomov" type="fix" issue="430"> + Wrap runtime exceptions into YAMLException (2019-01-14) + </action> + <action dev="asomov" type="fix"> + Fix: Null tag constructor not called when parsing top-level null value (2019-01-13) + (issue reported for snakeyaml-engine) + </action> + <action dev="asomov" type="fix" issue="429"> + Provide "Automatic-Module-Name" entry in MANIFEST (2018-12-16) + </action> + <action dev="asomov" type="fix" issue="426"> + Fix NPE when duplicate keys are not allowed and the key is null (2018-12-02) + </action> + <action dev="asomov" type="update"> + Support java.sql classes without the need to depend on java.sql module in java9+ (2018-11-06) + </action> + <action dev="asomov" type="update"> + Require Java 7 (2018-11-06) + </action> + <action dev="asomov" type="fix" issue="423"> + Date Serialization Fails for TimeZones on Daylight Savings Time (2018-11-06) + </action> + </release> + <release version="1.23" date="2018-08-27" description="Maintenance"> + <action dev="asomov" type="fix" issue="412"> + Add another getter for ScalarStyle to support backwards compatibility (2018-08-27) + </action> + </release> + <release version="1.22" date="2018-08-25" description="Maintenance"> + <action dev="asomov" type="update"> + Run tests under Java 11 (2018-08-19) + </action> + <action dev="asomov" type="update"> + Use Maven 3.5.4 (2018-08-19) + </action> + <action dev="asomov" type="fix" issue="412"> + Restore the Boolean constructors for Events and Nodes for binary compatibility + of dependent projects (2018-08-17) + </action> + <action dev="asomov" type="fix" issue="411"> + System Property "java.runtime.name" is not required to be defined (2018-08-12) + Ensure Compatibility with Graal + </action> + <action dev="asomov" type="fix" issue="409"> + Dumping Enum breaks when Enum value is Anonymous inner class (2018-08-07) + Solution: refactor the way to detect if the full tag can be omitted (and !!str is used instead). + Instead of checking whether the class for property and the class for the actual value is the same + we can just check that the property class is not java.lang.Enum + </action> + </release> + <release version="1.21" date="2018-04-13" description="Maintenance"> + <action dev="asomov" type="update"> + Scanner throws IndexOutOfBoundsException if no more token left but getToken() + or peekToken() called (2018-04-10) + </action> + <action dev="asomov" type="update"> + Enhance output of token IDs (2018-04-06) + </action> + <action dev="asomov" type="add"> + Mark: expose buffer and pointer (2018-04-06) + </action> + <action dev="asomov" type="fix" issue="401"> + Restore index in Mark - it is used in JRuby (2018-03-26) + </action> + <action dev="asomov" type="fix" issue="397"> + Plain scalars with colons in flow sequences/mappings are valid YAML (2018-03-03) + </action> + </release> + <release version="1.20" date="2018-02-28" description="Maintenance"> + <action dev="maslovalex" type="fix" issue="393"> + Improve reflective access operation to avoid warning under Java 9 (2018-02-24) + </action> + <action dev="asomov" type="update"> + Refactor collection node - flow style must not be null (2018-02-16) + </action> + <action dev="asomov" type="remove"> + Refactor: remove unused method isResolved in Node (2018-02-15) + </action> + <action dev="asomov" type="remove"> + Refactor: remove unused code in Tag (2018-02-15) + </action> + <action dev="asomov" type="update"> + Refactor nodes and events - use enum FlowStyle instead of Boolean (2018-02-10) + </action> + <action dev="asomov" type="update"> + Refactor ScalarToken, ScalarNode and ScalarEvent - use enum ScalarStyle instead of Character (2018-02-10) + </action> + <action dev="asomov" type="update"> + Refactor Token - remove unused code (2018-02-08) + </action> + <action dev="asomov" type="update"> + Refactor Mark - remove unused code (2018-02-06) + </action> + <action dev="asomov" type="fix" issue="395"> + Introduce DuplicateKeyException and report line number for duplicate keys + when creating non-Javabeans (2017-12-15) + </action> + </release> + <release version="1.19" date="2017-10-14" description="Maintenance"> + <action dev="maslovalex" type="update"> + Only use FIELD access for Android in PropertyUtils (2017-08-20) + </action> + <action dev="maslovalex" type="update"> + Add getAnnotations() and getAnnotation() methods to Property (2017-08-20) + </action> + <action dev="maslovalex" type="fix" issue="383"> + Some configuration properties of Representer are ignored. + </action> + <action dev="maslovalex" type="fix" issue="386"> + Fix order of duplicate keys indices to prevent wrong removals. + </action> + <action dev="maslovalex" type="fix" issue="382"> + Fix 382: same as 322 + </action> + <action dev="maslovalex" type="fix" issue="322"> + Fix 322: if there is no getter try to get type information from a setter + </action> + <action dev="asomov" type="fix" issue="377"> + Add test for 'billion laughs attack' + </action> + <action dev="asomov" type="fix" issue="368"> + Relax final restriction on TypeDescription (2017-05-05) + </action> + <action dev="asomov" type="fix" issue="375"> + Empty yaml file must return null instead of throwing an exception when loading a JavaBean (2017-05-03) + </action> + <action dev="asomov" type="fix" issue="374"> + Fix Number when it is used as a JavaBean property with a custom Locale (2017-04-30) + </action> + <action dev="asomov" type="add" issue="373"> + Add redundant test (2017-04-06) + </action> + <action dev="asomov" type="update"> + Provide access to node's anchor, pull request#20 (2017-03-30) + </action> + <action dev="asomov" type="fix" issue="370"> + Remove redundant "Bundle-RequiredExecutionEnvironment: J2SE-1.5" (2017-03-16) + </action> + <action dev="asomov" type="fix" issue="364"> + Serializing Calendar objects with certain timezone offsets renders invalid YAML (2017-02-28) + </action> + </release> + <release version="1.18" date="2017-02-22" description="Maintenance"> + <action dev="asomov" type="fix" issue="358"> + Validate DumperOptions to prevent invalid YAML to be dumped (2017-01-12) + </action> + <action dev="asomov" type="fix" issue="355"> + Fix for emitter to split long plain string scalars over multiple lines (2017-01-10) + </action> + <action dev="asomov" type="update"> + Let Mark implement Serializable so that ParserException can be serialized (2016-12-15) + </action> + <action dev="asomov" type="update" issue="354"> + Add tests for issue 354 (2016-12-12) + </action> + <action dev="maslovalex" type="fix" issue="337"> + Throw exception in case of duplicate keys in MappingNode and + LoaderOptions.allowDuplicateKeys is false. (2016-11-25) + </action> + <action dev="maslovalex" type="fix" issue="351"> + Keep same nodes order on merge (preprocess keys for MappingNode + and remove duplicates keeping the last one). (2016-11-22) + </action> + <action dev="asomov" type="fix" issue="349"> + Ignore white spaces for base64 encoded scalar (2016-11-17) + </action> + <action dev="maslovalex" type="fix" issue="348"> + Not removing parent object when composed object is an anchor. (2016-10-13) + </action> + <action dev="asomov" type="fix" issue="323"> + Support "Miscellaneous Symbols and Pictographs" (2016-09-05) + </action> + <action dev="asomov" type="fix" issue="341"> + Fix NPE in BaseRepresenter.multiRepresenters if it contains 'null' as value (2016-05-03) + </action> + <action dev="asomov" type="update" issue="335"> + Add example for issue 335 - the same tag for different node kinds (2016-03-19) + </action> <action dev="asomov" type="update" issue="332"> Add example for issue 332 (2016-02-24) </action> diff --git a/src/etc/announcement.msg b/src/etc/announcement.msg index a1cd13f5..c8bc294e 100644 --- a/src/etc/announcement.msg +++ b/src/etc/announcement.msg @@ -1,39 +1,40 @@ -From: Andrey Somov <public.somov@gmail.com>
-To: yaml-core@lists.sourceforge.net
-Subject: [ANN] SnakeYAML-1.17 final is available
-
-==========================
- Announcing SnakeYAML-1.17
-==========================
-
-A new release of SnakeYAML is now available:
-
- http://www.snakeyaml.org
-
-This release delivers minor changes and bug fixes.
-
-The complete list of changes is here: https://bitbucket.org/asomov/snakeyaml/wiki/Changes
-
-Resources
-==========
-
-SnakeYAML homepage: http://www.snakeyaml.org
-SnakeYAML documentation: https://bitbucket.org/asomov/snakeyaml/wiki/Home
-
-JAR package: http://repo2.maven.org/maven2/org/yaml/snakeyaml/1.17/snakeyaml-1.17.jar
-
-YAML homepage: http://yaml.org/
-YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core
-
-About SnakeYAML
-================
-
-SnakeYAML is a YAML parser and emitter for Java 6.
-
-SnakeYAML features a complete YAML 1.1 parser.
-SnakeYAML is applicable for a broad range of tasks from complex
-configuration files to object serialization and persistence.
-
-Copyright
-==========
-SnakeYAML is released under the Apache License Version 2.0
+From: Andrey Somov <public.somov@gmail.com> +To: yaml-core@lists.sourceforge.net +Subject: [ANN] SnakeYAML-1.32 final is available + +========================== + Announcing SnakeYAML-1.32 +========================== + +A new release of SnakeYAML is now available: + + https://bitbucket.org/snakeyaml/snakeyaml + +This release delivers minor changes and bug fixes + +The complete list of changes is here: https://bitbucket.org/snakeyaml/snakeyaml/wiki/Changes + +Resources +========== + +SnakeYAML homepage: https://bitbucket.org/snakeyaml/snakeyaml +SnakeYAML documentation: https://bitbucket.org/snakeyaml/snakeyaml/wiki/Home + +JAR package: http://repo2.maven.org/maven2/org/yaml/snakeyaml/1.32/snakeyaml-1.32.jar +Android: http://repo2.maven.org/maven2/org/yaml/snakeyaml/1.32/snakeyaml-1.32-android.jar + +YAML homepage: http://yaml.org/ +YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core + +About SnakeYAML +================ + +SnakeYAML is a YAML parser and emitter for Java 7. + +SnakeYAML features a complete YAML 1.1 parser. +SnakeYAML is applicable for a broad range of tasks from complex +configuration files to object serialization and persistence. + +Copyright +========== +SnakeYAML is released under the Apache License Version 2.0 diff --git a/src/etc/eclipse-java-google-style.xml b/src/etc/eclipse-java-google-style.xml new file mode 100644 index 00000000..096e983b --- /dev/null +++ b/src/etc/eclipse-java-google-style.xml @@ -0,0 +1,337 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<profiles version="13"> + <profile kind="CodeFormatterProfile" name="GoogleStyle" version="13"> + <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments.count_dependent" value="16|-1|16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_prefer_two_fragments" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_comment_inline_tags" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_local_variable_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter" value="1040"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type.count_dependent" value="1585|-1|1585"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields.count_dependent" value="16|-1|16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression.count_dependent" value="16|4|80"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration.count_dependent" value="16|4|48"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration.count_dependent" value="16|4|49"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments" value="16"/> + <setting id="org.eclipse.jdt.core.compiler.source" value="1.7"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration.count_dependent" value="16|4|48"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_local_variable_annotation" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants.count_dependent" value="16|5|48"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.lineSplit" value="100"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation.count_dependent" value="16|4|48"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package" value="1585"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="16"/> + <setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/> + <setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_type_annotation" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_field_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.comment_new_line_at_start_of_html_paragraph" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comment_prefix" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_parameter_annotation" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method" value="1585"/> + <setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="2"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation.count_dependent" value="16|5|80"/> + <setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter.count_dependent" value="1040|-1|1040"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package.count_dependent" value="1585|-1|1585"/> + <setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.force_if_else_statement_brace" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="3"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_package_annotation" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation.count_dependent" value="16|-1|16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type" value="1585"/> + <setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7"/> + <setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_new_anonymous_class" value="20"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable.count_dependent" value="1585|-1|1585"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field.count_dependent" value="1585|-1|1585"/> + <setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration.count_dependent" value="16|5|80"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/> + <setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant.count_dependent" value="16|-1|16"/> + <setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="100"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="2"/> + <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field" value="1585"/> + <setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer.count_dependent" value="16|5|80"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/> + <setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.7"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/> + <setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration.count_dependent" value="16|4|48"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method.count_dependent" value="1585|-1|1585"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression.count_dependent" value="16|-1|16"/> + <setting id="org.eclipse.jdt.core.formatter.wrap_non_simple_member_annotation" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable" value="1585"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call.count_dependent" value="16|5|80"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments.count_dependent" value="16|-1|16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression.count_dependent" value="16|5|80"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration.count_dependent" value="16|5|80"/> + <setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/> + <setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.alignment_for_for_statement" value="16"/> + <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/> + <setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/> + <setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/> + </profile> +</profiles>
\ No newline at end of file diff --git a/src/etc/header.txt b/src/etc/header.txt index 8db00b5c..742a717e 100644 --- a/src/etc/header.txt +++ b/src/etc/header.txt @@ -1,13 +1,11 @@ -Copyright (c) 2008, http://www.snakeyaml.org +Copyright (c) 2008, SnakeYAML -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 +http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. +Unless required by applicable law or agreed to in writing, software distributed under the License +is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +or implied. See the License for the specific language governing permissions and limitations under +the License. diff --git a/src/main/java/org/yaml/snakeyaml/DumperOptions.java b/src/main/java/org/yaml/snakeyaml/DumperOptions.java index 07621981..48b5e096 100644 --- a/src/main/java/org/yaml/snakeyaml/DumperOptions.java +++ b/src/main/java/org/yaml/snakeyaml/DumperOptions.java @@ -1,405 +1,487 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.Map; import java.util.TimeZone; - import org.yaml.snakeyaml.emitter.Emitter; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.serializer.AnchorGenerator; import org.yaml.snakeyaml.serializer.NumberAnchorGenerator; public class DumperOptions { - /** - * YAML provides a rich set of scalar styles. Block scalar styles include - * the literal style and the folded style; flow scalar styles include the - * plain style and two quoted styles, the single-quoted style and the - * double-quoted style. These styles offer a range of trade-offs between - * expressive power and readability. - * - * @see <a href="http://yaml.org/spec/1.1/#id903915">Chapter 9. Scalar - * Styles</a> - * @see <a href="http://yaml.org/spec/1.1/#id858081">2.3. Scalars</a> - */ - public enum ScalarStyle { - DOUBLE_QUOTED(Character.valueOf('"')), SINGLE_QUOTED(Character.valueOf('\'')), LITERAL( - Character.valueOf('|')), FOLDED(Character.valueOf('>')), PLAIN(null); - private Character styleChar; - - private ScalarStyle(Character style) { - this.styleChar = style; - } - - public Character getChar() { - return styleChar; - } - - @Override - public String toString() { - return "Scalar style: '" + styleChar + "'"; - } - - public static ScalarStyle createStyle(Character style) { - if (style == null) { - return PLAIN; - } else { - switch (style) { - case '"': - return DOUBLE_QUOTED; - case '\'': - return SINGLE_QUOTED; - case '|': - return LITERAL; - case '>': - return FOLDED; - default: - throw new YAMLException("Unknown scalar style character: " + style); - } - } - } - } - - /** - * Block styles use indentation to denote nesting and scope within the - * document. In contrast, flow styles rely on explicit indicators to denote - * nesting and scope. - * - * @see <a href="http://www.yaml.org/spec/current.html#id2509255">3.2.3.1. - * Node Styles (http://yaml.org/spec/1.1)</a> - */ - public enum FlowStyle { - FLOW(Boolean.TRUE), BLOCK(Boolean.FALSE), AUTO(null); - - private Boolean styleBoolean; - - private FlowStyle(Boolean flowStyle) { - styleBoolean = flowStyle; - } - - public Boolean getStyleBoolean() { - return styleBoolean; - } - - @Override - public String toString() { - return "Flow style: '" + styleBoolean + "'"; - } - } - - /** - * Platform dependent line break. - */ - public enum LineBreak { - WIN("\r\n"), MAC("\r"), UNIX("\n"); - private String lineBreak; - - private LineBreak(String lineBreak) { - this.lineBreak = lineBreak; - } - - public String getString() { - return lineBreak; - } - - @Override - public String toString() { - return "Line break: " + name(); - } - - public static LineBreak getPlatformLineBreak() { - String platformLineBreak = System.getProperty("line.separator"); - for (LineBreak lb : values()) { - if (lb.lineBreak.equals(platformLineBreak)) { - return lb; - } - } - return LineBreak.UNIX; + /** + * YAML provides a rich set of scalar styles. Block scalar styles include the literal style and + * the folded style; flow scalar styles include the plain style and two quoted styles, the + * single-quoted style and the double-quoted style. These styles offer a range of trade-offs + * between expressive power and readability. + * + * @see <a href="http://yaml.org/spec/1.1/#id903915">Chapter 9. Scalar Styles</a> + * @see <a href="http://yaml.org/spec/1.1/#id858081">2.3. Scalars</a> + */ + public enum ScalarStyle { + DOUBLE_QUOTED('"'), SINGLE_QUOTED('\''), LITERAL('|'), FOLDED('>'), PLAIN(null); + + private final Character styleChar; + + ScalarStyle(Character style) { + this.styleChar = style; + } + + public Character getChar() { + return styleChar; + } + + @Override + public String toString() { + return "Scalar style: '" + styleChar + "'"; + } + + public static ScalarStyle createStyle(Character style) { + if (style == null) { + return PLAIN; + } else { + switch (style) { + case '"': + return DOUBLE_QUOTED; + case '\'': + return SINGLE_QUOTED; + case '|': + return LITERAL; + case '>': + return FOLDED; + default: + throw new YAMLException("Unknown scalar style character: " + style); } + } } + } - /** - * Specification version. Currently supported 1.0 and 1.1 - */ - public enum Version { - V1_0(new Integer[] { 1, 0 }), V1_1(new Integer[] { 1, 1 }); - - private Integer[] version; - - private Version(Integer[] version) { - this.version = version; - } - - public int major() { return version[0]; } - public int minor() { return version[1]; } - - public String getRepresentation() { - return version[0] + "." + version[1]; - } + /** + * Block styles use indentation to denote nesting and scope within the document. In contrast, flow + * styles rely on explicit indicators to denote nesting and scope. + * + * @see <a href="http://www.yaml.org/spec/current.html#id2509255">3.2.3.1. Node Styles + * (http://yaml.org/spec/1.1)</a> + */ + public enum FlowStyle { + FLOW(Boolean.TRUE), BLOCK(Boolean.FALSE), AUTO(null); - @Override - public String toString() { - return "Version: " + getRepresentation(); - } - } + private final Boolean styleBoolean; - private ScalarStyle defaultStyle = ScalarStyle.PLAIN; - private FlowStyle defaultFlowStyle = FlowStyle.AUTO; - private boolean canonical = false; - private boolean allowUnicode = true; - private boolean allowReadOnlyProperties = false; - private int indent = 2; - private int indicatorIndent = 0; - private int bestWidth = 80; - private boolean splitLines = true; - private LineBreak lineBreak = LineBreak.UNIX; - private boolean explicitStart = false; - private boolean explicitEnd = false; - private TimeZone timeZone = null; - - private Version version = null; - private Map<String, String> tags = null; - private Boolean prettyFlow = false; - private AnchorGenerator anchorGenerator = new NumberAnchorGenerator(0); - - public boolean isAllowUnicode() { - return allowUnicode; + FlowStyle(Boolean flowStyle) { + styleBoolean = flowStyle; } - /** - * Specify whether to emit non-ASCII printable Unicode characters. - * The default value is true. - * When set to false then printable non-ASCII characters (Cyrillic, Chinese etc) - * will be not printed but escaped (to support ASCII terminals) + /* + * Convenience for legacy constructors that took {@link Boolean} arguments since replaced by + * {@link FlowStyle}. Introduced in v1.22 but only to support that for backwards compatibility. * - * @param allowUnicode - * if allowUnicode is false then all non-ASCII characters are - * escaped + * @deprecated Since restored in v1.22. Use the {@link FlowStyle} constants in your code + * instead. */ - public void setAllowUnicode(boolean allowUnicode) { - this.allowUnicode = allowUnicode; + @Deprecated + public static FlowStyle fromBoolean(Boolean flowStyle) { + return flowStyle == null ? AUTO : flowStyle ? FLOW : BLOCK; } - public ScalarStyle getDefaultScalarStyle() { - return defaultStyle; + public Boolean getStyleBoolean() { + return styleBoolean; } - /** - * Set default style for scalars. See YAML 1.1 specification, 2.3 Scalars - * (http://yaml.org/spec/1.1/#id858081) - * - * @param defaultStyle - * set the style for all scalars - */ - public void setDefaultScalarStyle(ScalarStyle defaultStyle) { - if (defaultStyle == null) { - throw new NullPointerException("Use ScalarStyle enum."); - } - this.defaultStyle = defaultStyle; + @Override + public String toString() { + return "Flow style: '" + styleBoolean + "'"; } + } - public void setIndent(int indent) { - if (indent < Emitter.MIN_INDENT) { - throw new YAMLException("Indent must be at least " + Emitter.MIN_INDENT); - } - if (indent > Emitter.MAX_INDENT) { - throw new YAMLException("Indent must be at most " + Emitter.MAX_INDENT); - } - this.indent = indent; - } + /** + * Platform dependent line break. + */ + public enum LineBreak { + WIN("\r\n"), MAC("\r"), UNIX("\n"); - public int getIndent() { - return this.indent; - } + private final String lineBreak; - public void setIndicatorIndent(int indicatorIndent) { - if (indicatorIndent < 0) { - throw new YAMLException("Indicator indent must be non-negative."); - } - if (indicatorIndent > Emitter.MAX_INDENT - 1) { - throw new YAMLException("Indicator indent must be at most Emitter.MAX_INDENT-1: " + (Emitter.MAX_INDENT - 1)); - } - this.indicatorIndent = indicatorIndent; + LineBreak(String lineBreak) { + this.lineBreak = lineBreak; } - public int getIndicatorIndent() { - return this.indicatorIndent; + public String getString() { + return lineBreak; } - public void setVersion(Version version) { - this.version = version; + @Override + public String toString() { + return "Line break: " + name(); } - public Version getVersion() { - return this.version; - } - - /** - * Force the emitter to produce a canonical YAML document. - * - * @param canonical - * true produce canonical YAML document - */ - public void setCanonical(boolean canonical) { - this.canonical = canonical; - } - - public boolean isCanonical() { - return this.canonical; - } - - /** - * Force the emitter to produce a pretty YAML document when using the flow - * style. - * - * @param prettyFlow - * true produce pretty flow YAML document - */ - public void setPrettyFlow(boolean prettyFlow) { - this.prettyFlow = prettyFlow; - } - - public boolean isPrettyFlow() { - return this.prettyFlow; - } - - /** - * Specify the preferred width to emit scalars. When the scalar - * representation takes more then the preferred with the scalar will be - * split into a few lines. The default is 80. - * - * @param bestWidth - * the preferred width for scalars. - */ - public void setWidth(int bestWidth) { - this.bestWidth = bestWidth; - } - - public int getWidth() { - return this.bestWidth; - } - - /** - * Specify whether to split lines exceeding preferred width for - * scalars. The default is true. - * - * @param splitLines - * whether to split lines exceeding preferred width for scalars. - */ - public void setSplitLines(boolean splitLines) { - this.splitLines = splitLines; - } - - public boolean getSplitLines() { - return this.splitLines; - } - - public LineBreak getLineBreak() { - return lineBreak; - } - - public void setDefaultFlowStyle(FlowStyle defaultFlowStyle) { - if (defaultFlowStyle == null) { - throw new NullPointerException("Use FlowStyle enum."); + public static LineBreak getPlatformLineBreak() { + String platformLineBreak = System.getProperty("line.separator"); + for (LineBreak lb : values()) { + if (lb.lineBreak.equals(platformLineBreak)) { + return lb; } - this.defaultFlowStyle = defaultFlowStyle; + } + return LineBreak.UNIX; } + } - public FlowStyle getDefaultFlowStyle() { - return defaultFlowStyle; - } - - /** - * Specify the line break to separate the lines. It is platform specific: - * Windows - "\r\n", old MacOS - "\r", Unix - "\n". The default value is the - * one for Unix. - */ - public void setLineBreak(LineBreak lineBreak) { - if (lineBreak == null) { - throw new NullPointerException("Specify line break."); - } - this.lineBreak = lineBreak; - } + /** + * Specification version. Currently supported 1.0 and 1.1 + */ + public enum Version { + V1_0(new Integer[] {1, 0}), V1_1(new Integer[] {1, 1}); - public boolean isExplicitStart() { - return explicitStart; - } + private final Integer[] version; - public void setExplicitStart(boolean explicitStart) { - this.explicitStart = explicitStart; + Version(Integer[] version) { + this.version = version; } - public boolean isExplicitEnd() { - return explicitEnd; + public int major() { + return version[0]; } - public void setExplicitEnd(boolean explicitEnd) { - this.explicitEnd = explicitEnd; + public int minor() { + return version[1]; } - public Map<String, String> getTags() { - return tags; + public String getRepresentation() { + return version[0] + "." + version[1]; } - // TODO should use Tag ??? - public void setTags(Map<String, String> tags) { - this.tags = tags; + @Override + public String toString() { + return "Version: " + getRepresentation(); } + } + public enum NonPrintableStyle { /** - * Report whether read-only JavaBean properties (the ones without setters) - * should be included in the YAML document - * - * @return false when read-only JavaBean properties are not emitted + * Transform String to binary if it contains non-printable characters */ - public boolean isAllowReadOnlyProperties() { - return allowReadOnlyProperties; - } - + BINARY, /** - * Set to true to include read-only JavaBean properties (the ones without - * setters) in the YAML document. By default these properties are not - * included to be able to parse later the same JavaBean. - * - * @param allowReadOnlyProperties - * - true to dump read-only JavaBean properties - */ - public void setAllowReadOnlyProperties(boolean allowReadOnlyProperties) { - this.allowReadOnlyProperties = allowReadOnlyProperties; - } - - public TimeZone getTimeZone() { - return timeZone; - } - - /** - * Set the timezone to be used for Date. If set to <code>null</code> UTC is - * used. + * Escape non-printable characters */ - public void setTimeZone(TimeZone timeZone) { - this.timeZone = timeZone; - } - - - public AnchorGenerator getAnchorGenerator() { - return anchorGenerator; - } - - public void setAnchorGenerator(AnchorGenerator anchorGenerator) { - this.anchorGenerator = anchorGenerator; - } + ESCAPE + } + + private ScalarStyle defaultStyle = ScalarStyle.PLAIN; + private FlowStyle defaultFlowStyle = FlowStyle.AUTO; + private boolean canonical = false; + private boolean allowUnicode = true; + private boolean allowReadOnlyProperties = false; + private int indent = 2; + private int indicatorIndent = 0; + private boolean indentWithIndicator = false; + private int bestWidth = 80; + private boolean splitLines = true; + private LineBreak lineBreak = LineBreak.UNIX; + private boolean explicitStart = false; + private boolean explicitEnd = false; + private TimeZone timeZone = null; + private int maxSimpleKeyLength = 128; + private boolean processComments = false; + private NonPrintableStyle nonPrintableStyle = NonPrintableStyle.BINARY; + + private Version version = null; + private Map<String, String> tags = null; + private Boolean prettyFlow = false; + private AnchorGenerator anchorGenerator = new NumberAnchorGenerator(0); + + public boolean isAllowUnicode() { + return allowUnicode; + } + + /** + * Specify whether to emit non-ASCII printable Unicode characters. The default value is true. When + * set to false then printable non-ASCII characters (Cyrillic, Chinese etc) will be not printed + * but escaped (to support ASCII terminals) + * + * @param allowUnicode if allowUnicode is false then all non-ASCII characters are escaped + */ + public void setAllowUnicode(boolean allowUnicode) { + this.allowUnicode = allowUnicode; + } + + public ScalarStyle getDefaultScalarStyle() { + return defaultStyle; + } + + /** + * Set default style for scalars. See YAML 1.1 specification, 2.3 Scalars + * (http://yaml.org/spec/1.1/#id858081) + * + * @param defaultStyle set the style for all scalars + */ + public void setDefaultScalarStyle(ScalarStyle defaultStyle) { + if (defaultStyle == null) { + throw new NullPointerException("Use ScalarStyle enum."); + } + this.defaultStyle = defaultStyle; + } + + public void setIndent(int indent) { + if (indent < Emitter.MIN_INDENT) { + throw new YAMLException("Indent must be at least " + Emitter.MIN_INDENT); + } + if (indent > Emitter.MAX_INDENT) { + throw new YAMLException("Indent must be at most " + Emitter.MAX_INDENT); + } + this.indent = indent; + } + + public int getIndent() { + return this.indent; + } + + /** + * Set number of white spaces to use for the sequence indicator '-' + * + * @param indicatorIndent value to be used as indent + */ + public void setIndicatorIndent(int indicatorIndent) { + if (indicatorIndent < 0) { + throw new YAMLException("Indicator indent must be non-negative."); + } + if (indicatorIndent > Emitter.MAX_INDENT - 1) { + throw new YAMLException( + "Indicator indent must be at most Emitter.MAX_INDENT-1: " + (Emitter.MAX_INDENT - 1)); + } + this.indicatorIndent = indicatorIndent; + } + + public int getIndicatorIndent() { + return this.indicatorIndent; + } + + public boolean getIndentWithIndicator() { + return indentWithIndicator; + } + + /** + * Set to true to add the indent for sequences to the general indent + * + * @param indentWithIndicator - true when indent for sequences is added to general + */ + public void setIndentWithIndicator(boolean indentWithIndicator) { + this.indentWithIndicator = indentWithIndicator; + } + + public void setVersion(Version version) { + this.version = version; + } + + public Version getVersion() { + return this.version; + } + + /** + * Force the emitter to produce a canonical YAML document. + * + * @param canonical true produce canonical YAML document + */ + public void setCanonical(boolean canonical) { + this.canonical = canonical; + } + + public boolean isCanonical() { + return this.canonical; + } + + /** + * Force the emitter to produce a pretty YAML document when using the flow style. + * + * @param prettyFlow true produce pretty flow YAML document + */ + public void setPrettyFlow(boolean prettyFlow) { + this.prettyFlow = prettyFlow; + } + + public boolean isPrettyFlow() { + return this.prettyFlow; + } + + /** + * Specify the preferred width to emit scalars. When the scalar representation takes more then the + * preferred with the scalar will be split into a few lines. The default is 80. + * + * @param bestWidth the preferred width for scalars. + */ + public void setWidth(int bestWidth) { + this.bestWidth = bestWidth; + } + + public int getWidth() { + return this.bestWidth; + } + + /** + * Specify whether to split lines exceeding preferred width for scalars. The default is true. + * + * @param splitLines whether to split lines exceeding preferred width for scalars. + */ + public void setSplitLines(boolean splitLines) { + this.splitLines = splitLines; + } + + public boolean getSplitLines() { + return this.splitLines; + } + + public LineBreak getLineBreak() { + return lineBreak; + } + + public void setDefaultFlowStyle(FlowStyle defaultFlowStyle) { + if (defaultFlowStyle == null) { + throw new NullPointerException("Use FlowStyle enum."); + } + this.defaultFlowStyle = defaultFlowStyle; + } + + public FlowStyle getDefaultFlowStyle() { + return defaultFlowStyle; + } + + /** + * Specify the line break to separate the lines. It is platform specific: Windows - "\r\n", old + * MacOS - "\r", Unix - "\n". The default value is the one for Unix. + * + * @param lineBreak to be used for the input + */ + public void setLineBreak(LineBreak lineBreak) { + if (lineBreak == null) { + throw new NullPointerException("Specify line break."); + } + this.lineBreak = lineBreak; + } + + public boolean isExplicitStart() { + return explicitStart; + } + + public void setExplicitStart(boolean explicitStart) { + this.explicitStart = explicitStart; + } + + public boolean isExplicitEnd() { + return explicitEnd; + } + + public void setExplicitEnd(boolean explicitEnd) { + this.explicitEnd = explicitEnd; + } + + public Map<String, String> getTags() { + return tags; + } + + public void setTags(Map<String, String> tags) { + this.tags = tags; + } + + /** + * Report whether read-only JavaBean properties (the ones without setters) should be included in + * the YAML document + * + * @return false when read-only JavaBean properties are not emitted + */ + public boolean isAllowReadOnlyProperties() { + return allowReadOnlyProperties; + } + + /** + * Set to true to include read-only JavaBean properties (the ones without setters) in the YAML + * document. By default these properties are not included to be able to parse later the same + * JavaBean. + * + * @param allowReadOnlyProperties - true to dump read-only JavaBean properties + */ + public void setAllowReadOnlyProperties(boolean allowReadOnlyProperties) { + this.allowReadOnlyProperties = allowReadOnlyProperties; + } + + public TimeZone getTimeZone() { + return timeZone; + } + + /** + * Set the timezone to be used for Date. If set to <code>null</code> UTC is used. + * + * @param timeZone for created Dates or null to use UTC + */ + public void setTimeZone(TimeZone timeZone) { + this.timeZone = timeZone; + } + + + public AnchorGenerator getAnchorGenerator() { + return anchorGenerator; + } + + public void setAnchorGenerator(AnchorGenerator anchorGenerator) { + this.anchorGenerator = anchorGenerator; + } + + public int getMaxSimpleKeyLength() { + return maxSimpleKeyLength; + } + + /** + * Define max key length to use simple key (without '?') More info + * https://yaml.org/spec/1.1/#id934537 + * + * @param maxSimpleKeyLength - the limit after which the key gets explicit key indicator '?' + */ + public void setMaxSimpleKeyLength(int maxSimpleKeyLength) { + if (maxSimpleKeyLength > 1024) { + throw new YAMLException( + "The simple key must not span more than 1024 stream characters. See https://yaml.org/spec/1.1/#id934537"); + } + this.maxSimpleKeyLength = maxSimpleKeyLength; + } + + /** + * Set the comment processing. By default comments are ignored. + * + * @param processComments <code>true</code> to process; <code>false</code> to ignore + */ + + public void setProcessComments(boolean processComments) { + this.processComments = processComments; + } + + public boolean isProcessComments() { + return processComments; + } + + public NonPrintableStyle getNonPrintableStyle() { + return this.nonPrintableStyle; + } + + /** + * When String contains non-printable characters SnakeYAML convert it to binary data with the + * !!binary tag. Set this to ESCAPE to keep the !!str tag and escape the non-printable chars with + * \\x or \\u + * + * @param style ESCAPE to force SnakeYAML to keep !!str tag for non-printable data + */ + public void setNonPrintableStyle(NonPrintableStyle style) { + this.nonPrintableStyle = style; + } } diff --git a/src/main/java/org/yaml/snakeyaml/LoaderOptions.java b/src/main/java/org/yaml/snakeyaml/LoaderOptions.java new file mode 100644 index 00000000..78583587 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/LoaderOptions.java @@ -0,0 +1,149 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml; + +public class LoaderOptions { + + private boolean allowDuplicateKeys = true; + private boolean wrappedToRootException = false; + private int maxAliasesForCollections = 50; // to prevent YAML at + // https://en.wikipedia.org/wiki/Billion_laughs_attack + private boolean allowRecursiveKeys = false; + private boolean processComments = false; + private boolean enumCaseSensitive = true; + private int nestingDepthLimit = 50; + private int codePointLimit = 3 * 1024 * 1024; // 3 MB + + public final boolean isAllowDuplicateKeys() { + return allowDuplicateKeys; + } + + /** + * Allow/Reject duplicate map keys in the YAML file. + * + * Default is to allow. + * + * YAML 1.1 is slightly vague around duplicate entries in the YAML file. The best reference is + * <a href="http://www.yaml.org/spec/1.1/#id862121"> 3.2.1.3. Nodes Comparison</a> where it hints + * that a duplicate map key is an error. + * + * For future reference, YAML spec 1.2 is clear. The keys MUST be unique. + * <a href="http://www.yaml.org/spec/1.2/spec.html#id2759572">1.3. Relation to JSON</a> + * + * @param allowDuplicateKeys false to reject duplicate mapping keys + */ + public void setAllowDuplicateKeys(boolean allowDuplicateKeys) { + this.allowDuplicateKeys = allowDuplicateKeys; + } + + public final boolean isWrappedToRootException() { + return wrappedToRootException; + } + + /** + * Wrap runtime exception to YAMLException during parsing or leave them as they are + * + * Default is to leave original exceptions + * + * @param wrappedToRootException - true to convert runtime exception to YAMLException + */ + public void setWrappedToRootException(boolean wrappedToRootException) { + this.wrappedToRootException = wrappedToRootException; + } + + public final int getMaxAliasesForCollections() { + return maxAliasesForCollections; + } + + /** + * Restrict the amount of aliases for collections (sequences and mappings) to avoid + * https://en.wikipedia.org/wiki/Billion_laughs_attack + * + * @param maxAliasesForCollections set max allowed value (50 by default) + */ + public void setMaxAliasesForCollections(int maxAliasesForCollections) { + this.maxAliasesForCollections = maxAliasesForCollections; + } + + /** + * Allow recursive keys for mappings. By default, it is not allowed. This setting only prevents + * the case when the key is the value. If the key is only a part of the value (the value is a + * sequence or a mapping) then this case is not recognized and always allowed. + * + * @param allowRecursiveKeys - false to disable recursive keys + */ + public void setAllowRecursiveKeys(boolean allowRecursiveKeys) { + this.allowRecursiveKeys = allowRecursiveKeys; + } + + public final boolean getAllowRecursiveKeys() { + return allowRecursiveKeys; + } + + /** + * Set the comment processing. By default, comments are ignored. + * + * @param processComments <code>true</code> to process; <code>false</code> to ignore + */ + public LoaderOptions setProcessComments(boolean processComments) { + this.processComments = processComments; + return this; + } + + public final boolean isProcessComments() { + return processComments; + } + + public final boolean isEnumCaseSensitive() { + return enumCaseSensitive; + } + + /** + * Disables or enables case sensitivity during construct enum constant from string value Default + * is false. + * + * @param enumCaseSensitive - true to set enum case sensitive, false the reverse + */ + public void setEnumCaseSensitive(boolean enumCaseSensitive) { + this.enumCaseSensitive = enumCaseSensitive; + } + + public final int getNestingDepthLimit() { + return nestingDepthLimit; + } + + /** + * Set max depth of nested collections. When the limit is exceeded an exception is thrown. + * Aliases/Anchors are not counted. This is to prevent a DoS attack + * + * @param nestingDepthLimit - depth to be accepted (50 by default) + */ + public void setNestingDepthLimit(int nestingDepthLimit) { + this.nestingDepthLimit = nestingDepthLimit; + } + + public final int getCodePointLimit() { + return codePointLimit; + } + + /** + * The max amount of code points in the input YAML document. Please be aware that byte limit + * depends on the encoding. + * + * @param codePointLimit - the max allowed size of the YAML data + */ + public void setCodePointLimit(int codePointLimit) { + this.codePointLimit = codePointLimit; + } +} diff --git a/src/main/java/org/yaml/snakeyaml/TypeDescription.java b/src/main/java/org/yaml/snakeyaml/TypeDescription.java index 4c383076..e65308b1 100644 --- a/src/main/java/org/yaml/snakeyaml/TypeDescription.java +++ b/src/main/java/org/yaml/snakeyaml/TypeDescription.java @@ -1,148 +1,398 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; -import java.util.HashMap; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; - +import java.util.Set; +import java.util.logging.Logger; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.introspector.BeanAccess; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertySubstitute; +import org.yaml.snakeyaml.introspector.PropertyUtils; +import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; /** - * Provides additional runtime information necessary to create a custom Java - * instance. + * Provides additional runtime information necessary to create a custom Java instance. + * + * In general this class is thread-safe and can be used as a singleton, the only exception being the + * PropertyUtils field. A singleton PropertyUtils should be constructed and shared between all YAML + * Constructors used if a singleton TypeDescription is used, since Constructor sets its + * propertyUtils to the TypeDescription that is passed to it, hence you may end up in a situation + * when propertyUtils in TypeDescription is from different Constructor. */ -public final class TypeDescription { - private final Class<? extends Object> type; - private Tag tag; - private Map<String, Class<? extends Object>> listProperties; - private Map<String, Class<? extends Object>> keyProperties; - private Map<String, Class<? extends Object>> valueProperties; - - public TypeDescription(Class<? extends Object> clazz, Tag tag) { - this.type = clazz; - this.tag = tag; - listProperties = new HashMap<String, Class<? extends Object>>(); - keyProperties = new HashMap<String, Class<? extends Object>>(); - valueProperties = new HashMap<String, Class<? extends Object>>(); - } +public class TypeDescription { + + final static private Logger log = Logger.getLogger(TypeDescription.class.getPackage().getName()); + + private final Class<? extends Object> type; + + // class that implements the described type; if set, will be used as a source for constructor. + // If not set - TypeDescription will leave instantiation of an entity to the YAML Constructor + private Class<?> impl; + + private Tag tag; + + private transient Set<Property> dumpProperties; + private transient PropertyUtils propertyUtils; + private transient boolean delegatesChecked; + + private Map<String, PropertySubstitute> properties = Collections.emptyMap(); + + protected Set<String> excludes = Collections.emptySet(); + protected String[] includes = null; + protected BeanAccess beanAccess; + + public TypeDescription(Class<? extends Object> clazz, Tag tag) { + this(clazz, tag, null); + } + + public TypeDescription(Class<? extends Object> clazz, Tag tag, Class<?> impl) { + this.type = clazz; + this.tag = tag; + this.impl = impl; + beanAccess = null; + } + + public TypeDescription(Class<? extends Object> clazz, String tag) { + this(clazz, new Tag(tag), null); + } + + public TypeDescription(Class<? extends Object> clazz) { + this(clazz, new Tag(clazz), null); + } + + public TypeDescription(Class<? extends Object> clazz, Class<?> impl) { + this(clazz, new Tag(clazz), impl); + } + + /** + * Get tag which shall be used to load or dump the type (class). + * + * @return tag to be used. It may be a tag for Language-Independent Types + * (http://www.yaml.org/type/) + */ + public Tag getTag() { + return tag; + } + + /** + * Set tag to be used dump the type (class). + * + * @param tag - local or global tag + * @deprecated it will be removed because it is not used + */ + @Deprecated + public void setTag(Tag tag) { + this.tag = tag; + } + + /** + * Set tag to be used to dump the type (class). + * + * @param tag - local or global tag + * @deprecated it will be removed because it is not used + */ + @Deprecated + public void setTag(String tag) { + setTag(new Tag(tag)); + } + + /** + * Get represented type (class) + * + * @return type (class) to be described. + */ + public Class<? extends Object> getType() { + return type; + } + + /** + * Specify that the property is a type-safe <code>List</code>. + * + * @param property name of the JavaBean property + * @param type class of List values + */ + @Deprecated + public void putListPropertyType(String property, Class<? extends Object> type) { + addPropertyParameters(property, type); + } - public TypeDescription(Class<? extends Object> clazz, String tag) { - this(clazz, new Tag(tag)); + /** + * Get class of List values for provided JavaBean property. + * + * @param property property name + * @return class of List values + */ + @Deprecated + public Class<? extends Object> getListPropertyType(String property) { + if (properties.containsKey(property)) { + Class<?>[] typeArguments = properties.get(property).getActualTypeArguments(); + if (typeArguments != null && typeArguments.length > 0) { + return typeArguments[0]; + } } + return null; + } - public TypeDescription(Class<? extends Object> clazz) { - this(clazz, (Tag) null); + /** + * Specify that the property is a type-safe <code>Map</code>. + * + * @param property property name of this JavaBean + * @param key class of keys in Map + * @param value class of values in Map + */ + @Deprecated + public void putMapPropertyType(String property, Class<? extends Object> key, + Class<? extends Object> value) { + addPropertyParameters(property, key, value); + } + + /** + * Get keys type info for this JavaBean + * + * @param property property name of this JavaBean + * @return class of keys in the Map + */ + @Deprecated + public Class<? extends Object> getMapKeyType(String property) { + if (properties.containsKey(property)) { + Class<?>[] typeArguments = properties.get(property).getActualTypeArguments(); + if (typeArguments != null && typeArguments.length > 0) { + return typeArguments[0]; + } } + return null; + } - /** - * Get tag which shall be used to load or dump the type (class). - * - * @return tag to be used. It may be a tag for Language-Independent Types - * (http://www.yaml.org/type/) - */ - public Tag getTag() { - return tag; + /** + * Get values type info for this JavaBean + * + * @param property property name of this JavaBean + * @return class of values in the Map + */ + @Deprecated + public Class<? extends Object> getMapValueType(String property) { + if (properties.containsKey(property)) { + Class<?>[] typeArguments = properties.get(property).getActualTypeArguments(); + if (typeArguments != null && typeArguments.length > 1) { + return typeArguments[1]; + } } + return null; + } - /** - * Set tag to be used to load or dump the type (class). - * - * @param tag - * local or global tag - */ - public void setTag(Tag tag) { - this.tag = tag; + /** + * Adds new substitute for property <code>pName</code> parameterized by <code>classes</code> to + * this <code>TypeDescription</code>. If <code>pName</code> has been added before - updates + * parameters with <code>classes</code>. + * + * @param pName - parameter name + * @param classes - parameterized by + */ + public void addPropertyParameters(String pName, Class<?>... classes) { + if (!properties.containsKey(pName)) { + substituteProperty(pName, null, null, null, classes); + } else { + PropertySubstitute pr = properties.get(pName); + pr.setActualTypeArguments(classes); } - public void setTag(String tag) { - setTag(new Tag(tag)); + } + + @Override + public String toString() { + return "TypeDescription for " + getType() + " (tag='" + getTag() + "')"; + } + + private void checkDelegates() { + Collection<PropertySubstitute> values = properties.values(); + for (PropertySubstitute p : values) { + try { + p.setDelegate(discoverProperty(p.getName())); + } catch (YAMLException e) { + } } + delegatesChecked = true; + } - /** - * Get represented type (class) - * - * @return type (class) to be described. - */ - public Class<? extends Object> getType() { - return type; + private Property discoverProperty(String name) { + if (propertyUtils != null) { + if (beanAccess == null) { + return propertyUtils.getProperty(type, name); + } + return propertyUtils.getProperty(type, name, beanAccess); } + return null; + } - /** - * Specify that the property is a type-safe <code>List</code>. - * - * @param property - * name of the JavaBean property - * @param type - * class of List values - */ - public void putListPropertyType(String property, Class<? extends Object> type) { - listProperties.put(property, type); + public Property getProperty(String name) { + if (!delegatesChecked) { + checkDelegates(); } + return properties.containsKey(name) ? properties.get(name) : discoverProperty(name); + } - /** - * Get class of List values for provided JavaBean property. - * - * @param property - * property name - * @return class of List values - */ - public Class<? extends Object> getListPropertyType(String property) { - return listProperties.get(property); + /** + * Adds property substitute for <code>pName</code> + * + * @param pName property name + * @param pType property type + * @param getter method name for getter + * @param setter method name for setter + * @param argParams actual types for parameterized type (List<?>, Map<?>) + */ + public void substituteProperty(String pName, Class<?> pType, String getter, String setter, + Class<?>... argParams) { + substituteProperty(new PropertySubstitute(pName, pType, getter, setter, argParams)); + } + + public void substituteProperty(PropertySubstitute substitute) { + if (Collections.EMPTY_MAP == properties) { + properties = new LinkedHashMap<String, PropertySubstitute>(); } + substitute.setTargetType(type); + properties.put(substitute.getName(), substitute); + } + + public void setPropertyUtils(PropertyUtils propertyUtils) { + this.propertyUtils = propertyUtils; + } - /** - * Specify that the property is a type-safe <code>Map</code>. - * - * @param property - * property name of this JavaBean - * @param key - * class of keys in Map - * @param value - * class of values in Map - */ - public void putMapPropertyType(String property, Class<? extends Object> key, - Class<? extends Object> value) { - keyProperties.put(property, key); - valueProperties.put(property, value); + /* begin: Representer */ + public void setIncludes(String... propNames) { + this.includes = (propNames != null && propNames.length > 0) ? propNames : null; + } + + public void setExcludes(String... propNames) { + if (propNames != null && propNames.length > 0) { + excludes = new HashSet<String>(); + Collections.addAll(excludes, propNames); + } else { + excludes = Collections.emptySet(); } + } - /** - * Get keys type info for this JavaBean - * - * @param property - * property name of this JavaBean - * @return class of keys in the Map - */ - public Class<? extends Object> getMapKeyType(String property) { - return keyProperties.get(property); + public Set<Property> getProperties() { + if (dumpProperties != null) { + return dumpProperties; } - /** - * Get values type info for this JavaBean - * - * @param property - * property name of this JavaBean - * @return class of values in the Map - */ - public Class<? extends Object> getMapValueType(String property) { - return valueProperties.get(property); + if (propertyUtils != null) { + if (includes != null) { + dumpProperties = new LinkedHashSet<Property>(); + for (String propertyName : includes) { + if (!excludes.contains(propertyName)) { + dumpProperties.add(getProperty(propertyName)); + } + } + return dumpProperties; + } + + final Set<Property> readableProps = (beanAccess == null) ? propertyUtils.getProperties(type) + : propertyUtils.getProperties(type, beanAccess); + + if (properties.isEmpty()) { + if (excludes.isEmpty()) { + return dumpProperties = readableProps; + } + dumpProperties = new LinkedHashSet<Property>(); + for (Property property : readableProps) { + if (!excludes.contains(property.getName())) { + dumpProperties.add(property); + } + } + return dumpProperties; + } + + if (!delegatesChecked) { + checkDelegates(); + } + + dumpProperties = new LinkedHashSet<Property>(); + + for (Property property : properties.values()) { + if (!excludes.contains(property.getName()) && property.isReadable()) { + dumpProperties.add(property); + } + } + + for (Property property : readableProps) { + if (!excludes.contains(property.getName())) { + dumpProperties.add(property); + } + } + + return dumpProperties; } + return null; + } + + /* end: Representer */ + + /*------------ Maybe something useful to override :) ---------*/ - @Override - public String toString() { - return "TypeDescription for " + getType() + " (tag='" + getTag() + "')"; + public boolean setupPropertyType(String key, Node valueNode) { + return false; + } + + public boolean setProperty(Object targetBean, String propertyName, Object value) + throws Exception { + return false; + } + + /** + * This method should be overridden for TypeDescription implementations that are supposed to + * implement instantiation logic that is different from default one as implemented in YAML + * constructors. Note that even if you override this method, default filling of fields with + * variables from parsed YAML will still occur later. + * + * @param node - node to construct the instance from + * @return new instance + */ + public Object newInstance(Node node) { + if (impl != null) { + try { + java.lang.reflect.Constructor<?> c = impl.getDeclaredConstructor(); + c.setAccessible(true); + return c.newInstance(); + } catch (Exception e) { + log.fine(e.getLocalizedMessage()); + impl = null; + } } + return null; + } + + public Object newInstance(String propertyName, Node node) { + return null; + } + + /** + * Is invoked after entity is filled with values from deserialized YAML + * + * @param obj - deserialized entity + * @return postprocessed deserialized entity + */ + public Object finalizeConstruction(Object obj) { + return obj; + } + } diff --git a/src/main/java/org/yaml/snakeyaml/Yaml.java b/src/main/java/org/yaml/snakeyaml/Yaml.java index 5c4559cb..16114cd9 100644 --- a/src/main/java/org/yaml/snakeyaml/Yaml.java +++ b/src/main/java/org/yaml/snakeyaml/Yaml.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -24,8 +22,8 @@ import java.io.Writer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; import java.util.regex.Pattern; - import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.constructor.BaseConstructor; @@ -46,616 +44,675 @@ import org.yaml.snakeyaml.resolver.Resolver; import org.yaml.snakeyaml.serializer.Serializer; /** - * Public YAML interface. Each Thread must have its own instance. + * Public YAML interface. This class is not thread-safe. Which means that all the methods of the + * same instance can be called only by one thread. It is better to create an instance for every YAML + * stream. */ public class Yaml { - protected final Resolver resolver; - private String name; - protected BaseConstructor constructor; - protected Representer representer; - protected DumperOptions dumperOptions; - - /** - * Create Yaml instance. It is safe to create a few instances and use them - * in different Threads. - */ - public Yaml() { - this(new Constructor(), new Representer(), new DumperOptions(), new Resolver()); - } - - /** - * Create Yaml instance. - * - * @param dumperOptions - * DumperOptions to configure outgoing objects - */ - public Yaml(DumperOptions dumperOptions) { - this(new Constructor(), new Representer(), dumperOptions); - } - - /** - * Create Yaml instance. It is safe to create a few instances and use them - * in different Threads. - * - * @param representer - * Representer to emit outgoing objects - */ - public Yaml(Representer representer) { - this(new Constructor(), representer); - } - - /** - * Create Yaml instance. It is safe to create a few instances and use them - * in different Threads. - * - * @param constructor - * BaseConstructor to construct incoming documents - */ - public Yaml(BaseConstructor constructor) { - this(constructor, new Representer()); - } - - /** - * Create Yaml instance. It is safe to create a few instances and use them - * in different Threads. - * - * @param constructor - * BaseConstructor to construct incoming documents - * @param representer - * Representer to emit outgoing objects - */ - public Yaml(BaseConstructor constructor, Representer representer) { - this(constructor, representer, new DumperOptions()); - } - - /** - * Create Yaml instance. It is safe to create a few instances and use them - * in different Threads. - * - * @param representer - * Representer to emit outgoing objects - * @param dumperOptions - * DumperOptions to configure outgoing objects - */ - public Yaml(Representer representer, DumperOptions dumperOptions) { - this(new Constructor(), representer, dumperOptions, new Resolver()); - } - - /** - * Create Yaml instance. It is safe to create a few instances and use them - * in different Threads. - * - * @param constructor - * BaseConstructor to construct incoming documents - * @param representer - * Representer to emit outgoing objects - * @param dumperOptions - * DumperOptions to configure outgoing objects - */ - public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions) { - this(constructor, representer, dumperOptions, new Resolver()); - } - - /** - * Create Yaml instance. It is safe to create a few instances and use them - * in different Threads. - * - * @param constructor - * BaseConstructor to construct incoming documents - * @param representer - * Representer to emit outgoing objects - * @param dumperOptions - * DumperOptions to configure outgoing objects - * @param resolver - * Resolver to detect implicit type - */ - public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions, - Resolver resolver) { - if (!constructor.isExplicitPropertyUtils()) { - constructor.setPropertyUtils(representer.getPropertyUtils()); - } else if (!representer.isExplicitPropertyUtils()) { - representer.setPropertyUtils(constructor.getPropertyUtils()); - } - this.constructor = constructor; - representer.setDefaultFlowStyle(dumperOptions.getDefaultFlowStyle()); - representer.setDefaultScalarStyle(dumperOptions.getDefaultScalarStyle()); - representer.getPropertyUtils().setAllowReadOnlyProperties( - dumperOptions.isAllowReadOnlyProperties()); - representer.setTimeZone(dumperOptions.getTimeZone()); - this.representer = representer; - this.dumperOptions = dumperOptions; - this.resolver = resolver; - this.name = "Yaml:" + System.identityHashCode(this); - } - - /** - * Serialize a Java object into a YAML String. - * - * @param data - * Java object to be Serialized to YAML - * @return YAML String - */ - public String dump(Object data) { - List<Object> list = new ArrayList<Object>(1); - list.add(data); - return dumpAll(list.iterator()); - } - - /** - * Produce the corresponding representation tree for a given Object. - * - * @see <a href="http://yaml.org/spec/1.1/#id859333">Figure 3.1. Processing - * Overview</a> - * @param data - * instance to build the representation tree for - * @return representation tree - */ - public Node represent(Object data) { - return representer.represent(data); - } - - /** - * Serialize a sequence of Java objects into a YAML String. - * - * @param data - * Iterator with Objects - * @return YAML String with all the objects in proper sequence - */ - public String dumpAll(Iterator<? extends Object> data) { - StringWriter buffer = new StringWriter(); - dumpAll(data, buffer, null); - return buffer.toString(); - } - - /** - * Serialize a Java object into a YAML stream. - * - * @param data - * Java object to be serialized to YAML - * @param output - * stream to write to - */ - public void dump(Object data, Writer output) { - List<Object> list = new ArrayList<Object>(1); - list.add(data); - dumpAll(list.iterator(), output, null); - } - - /** - * Serialize a sequence of Java objects into a YAML stream. - * - * @param data - * Iterator with Objects - * @param output - * stream to write to - */ - public void dumpAll(Iterator<? extends Object> data, Writer output) { - dumpAll(data, output, null); - } - - private void dumpAll(Iterator<? extends Object> data, Writer output, Tag rootTag) { - Serializer serializer = new Serializer(new Emitter(output, dumperOptions), resolver, - dumperOptions, rootTag); - try { - serializer.open(); - while (data.hasNext()) { - Node node = representer.represent(data.next()); - serializer.serialize(node); - } - serializer.close(); - } catch (IOException e) { - throw new YAMLException(e); - } - } - /** - * <p> - * Serialize a Java object into a YAML string. Override the default root tag - * with <code>rootTag</code>. - * </p> - * - * <p> - * This method is similar to <code>Yaml.dump(data)</code> except that the - * root tag for the whole document is replaced with the given tag. This has - * two main uses. - * </p> - * - * <p> - * First, if the root tag is replaced with a standard YAML tag, such as - * <code>Tag.MAP</code>, then the object will be dumped as a map. The root - * tag will appear as <code>!!map</code>, or blank (implicit !!map). - * </p> - * - * <p> - * Second, if the root tag is replaced by a different custom tag, then the - * document appears to be a different type when loaded. For example, if an - * instance of MyClass is dumped with the tag !!YourClass, then it will be - * handled as an instance of YourClass when loaded. - * </p> - * - * @param data - * Java object to be serialized to YAML - * @param rootTag - * the tag for the whole YAML document. The tag should be Tag.MAP - * for a JavaBean to make the tag disappear (to use implicit tag - * !!map). If <code>null</code> is provided then the standard tag - * with the full class name is used. - * @param flowStyle - * flow style for the whole document. See Chapter 10. Collection - * Styles http://yaml.org/spec/1.1/#id930798. If - * <code>null</code> is provided then the flow style from - * DumperOptions is used. - * - * @return YAML String - */ - public String dumpAs(Object data, Tag rootTag, FlowStyle flowStyle) { - FlowStyle oldStyle = representer.getDefaultFlowStyle(); - if (flowStyle != null) { - representer.setDefaultFlowStyle(flowStyle); - } - List<Object> list = new ArrayList<Object>(1); - list.add(data); - StringWriter buffer = new StringWriter(); - dumpAll(list.iterator(), buffer, rootTag); - representer.setDefaultFlowStyle(oldStyle); - return buffer.toString(); - } - - /** - * <p> - * Serialize a Java object into a YAML string. Override the default root tag - * with <code>Tag.MAP</code>. - * </p> - * <p> - * This method is similar to <code>Yaml.dump(data)</code> except that the - * root tag for the whole document is replaced with <code>Tag.MAP</code> tag - * (implicit !!map). - * </p> - * <p> - * Block Mapping is used as the collection style. See 10.2.2. Block Mappings - * (http://yaml.org/spec/1.1/#id934537) - * </p> - * - * @param data - * Java object to be serialized to YAML - * @return YAML String - */ - public String dumpAsMap(Object data) { - return dumpAs(data, Tag.MAP, FlowStyle.BLOCK); + protected final Resolver resolver; + private String name; + protected BaseConstructor constructor; + protected Representer representer; + protected DumperOptions dumperOptions; + protected LoaderOptions loadingConfig; + + /** + * Create Yaml instance. + */ + public Yaml() { + this(new Constructor(), new Representer(), new DumperOptions(), new LoaderOptions(), + new Resolver()); + } + + /** + * Create Yaml instance. + * + * @param dumperOptions DumperOptions to configure outgoing objects + */ + public Yaml(DumperOptions dumperOptions) { + this(new Constructor(), new Representer(dumperOptions), dumperOptions); + } + + /** + * Create Yaml instance. + * + * @param loadingConfig LoadingConfig to control load behavior + */ + public Yaml(LoaderOptions loadingConfig) { + this(new Constructor(loadingConfig), new Representer(), new DumperOptions(), loadingConfig); + } + + /** + * Create Yaml instance. + * + * @param representer Representer to emit outgoing objects + */ + public Yaml(Representer representer) { + this(new Constructor(), representer); + } + + /** + * Create Yaml instance. + * + * @param constructor BaseConstructor to construct incoming documents + */ + public Yaml(BaseConstructor constructor) { + this(constructor, new Representer()); + } + + /** + * Create Yaml instance. + * + * @param constructor BaseConstructor to construct incoming documents + * @param representer Representer to emit outgoing objects + */ + public Yaml(BaseConstructor constructor, Representer representer) { + this(constructor, representer, initDumperOptions(representer)); + } + + private static DumperOptions initDumperOptions(Representer representer) { + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setDefaultFlowStyle(representer.getDefaultFlowStyle()); + dumperOptions.setDefaultScalarStyle(representer.getDefaultScalarStyle()); + dumperOptions + .setAllowReadOnlyProperties(representer.getPropertyUtils().isAllowReadOnlyProperties()); + dumperOptions.setTimeZone(representer.getTimeZone()); + return dumperOptions; + } + + /** + * Create Yaml instance. It is safe to create a few instances and use them in different Threads. + * + * @param representer Representer to emit outgoing objects + * @param dumperOptions DumperOptions to configure outgoing objects + */ + public Yaml(Representer representer, DumperOptions dumperOptions) { + this(new Constructor(), representer, dumperOptions, new LoaderOptions(), new Resolver()); + } + + /** + * Create Yaml instance. It is safe to create a few instances and use them in different Threads. + * + * @param constructor BaseConstructor to construct incoming documents + * @param representer Representer to emit outgoing objects + * @param dumperOptions DumperOptions to configure outgoing objects + */ + public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions) { + this(constructor, representer, dumperOptions, new LoaderOptions(), new Resolver()); + } + + /** + * Create Yaml instance. It is safe to create a few instances and use them in different Threads. + * + * @param constructor BaseConstructor to construct incoming documents + * @param representer Representer to emit outgoing objects + * @param dumperOptions DumperOptions to configure outgoing objects + * @param loadingConfig LoadingConfig to control load behavior + */ + public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions, + LoaderOptions loadingConfig) { + this(constructor, representer, dumperOptions, loadingConfig, new Resolver()); + } + + /** + * Create Yaml instance. It is safe to create a few instances and use them in different Threads. + * + * @param constructor BaseConstructor to construct incoming documents + * @param representer Representer to emit outgoing objects + * @param dumperOptions DumperOptions to configure outgoing objects + * @param resolver Resolver to detect implicit type + */ + public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions, + Resolver resolver) { + this(constructor, representer, dumperOptions, new LoaderOptions(), resolver); + } + + /** + * Create Yaml instance. It is safe to create a few instances and use them in different Threads. + * + * @param constructor BaseConstructor to construct incoming documents + * @param representer Representer to emit outgoing objects + * @param dumperOptions DumperOptions to configure outgoing objects + * @param loadingConfig LoadingConfig to control load behavior + * @param resolver Resolver to detect implicit type + */ + public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions, + LoaderOptions loadingConfig, Resolver resolver) { + if (!constructor.isExplicitPropertyUtils()) { + constructor.setPropertyUtils(representer.getPropertyUtils()); + } else if (!representer.isExplicitPropertyUtils()) { + representer.setPropertyUtils(constructor.getPropertyUtils()); + } + this.constructor = constructor; + this.constructor.setAllowDuplicateKeys(loadingConfig.isAllowDuplicateKeys()); + this.constructor.setWrappedToRootException(loadingConfig.isWrappedToRootException()); + if (!dumperOptions.getIndentWithIndicator() + && dumperOptions.getIndent() <= dumperOptions.getIndicatorIndent()) { + throw new YAMLException("Indicator indent must be smaller then indent."); + } + representer.setDefaultFlowStyle(dumperOptions.getDefaultFlowStyle()); + representer.setDefaultScalarStyle(dumperOptions.getDefaultScalarStyle()); + representer.getPropertyUtils() + .setAllowReadOnlyProperties(dumperOptions.isAllowReadOnlyProperties()); + representer.setTimeZone(dumperOptions.getTimeZone()); + this.representer = representer; + this.dumperOptions = dumperOptions; + this.loadingConfig = loadingConfig; + this.resolver = resolver; + this.name = "Yaml:" + System.identityHashCode(this); + } + + /** + * Serialize a Java object into a YAML String. + * + * @param data Java object to be Serialized to YAML + * @return YAML String + */ + public String dump(Object data) { + List<Object> list = new ArrayList<Object>(1); + list.add(data); + return dumpAll(list.iterator()); + } + + /** + * Produce the corresponding representation tree for a given Object. + * + * @param data instance to build the representation tree for + * @return representation tree + * @see <a href="http://yaml.org/spec/1.1/#id859333">Figure 3.1. Processing Overview</a> + */ + public Node represent(Object data) { + return representer.represent(data); + } + + /** + * Serialize a sequence of Java objects into a YAML String. + * + * @param data Iterator with Objects + * @return YAML String with all the objects in proper sequence + */ + public String dumpAll(Iterator<? extends Object> data) { + StringWriter buffer = new StringWriter(); + dumpAll(data, buffer, null); + return buffer.toString(); + } + + /** + * Serialize a Java object into a YAML stream. + * + * @param data Java object to be serialized to YAML + * @param output stream to write to + */ + public void dump(Object data, Writer output) { + List<Object> list = new ArrayList<Object>(1); + list.add(data); + dumpAll(list.iterator(), output, null); + } + + /** + * Serialize a sequence of Java objects into a YAML stream. + * + * @param data Iterator with Objects + * @param output stream to write to + */ + public void dumpAll(Iterator<? extends Object> data, Writer output) { + dumpAll(data, output, null); + } + + private void dumpAll(Iterator<? extends Object> data, Writer output, Tag rootTag) { + Serializer serializer = + new Serializer(new Emitter(output, dumperOptions), resolver, dumperOptions, rootTag); + try { + serializer.open(); + while (data.hasNext()) { + Node node = representer.represent(data.next()); + serializer.serialize(node); + } + serializer.close(); + } catch (IOException e) { + throw new YAMLException(e); + } + } + + /** + * <p> + * Serialize a Java object into a YAML string. Override the default root tag with + * <code>rootTag</code>. + * </p> + * + * <p> + * This method is similar to <code>Yaml.dump(data)</code> except that the root tag for the whole + * document is replaced with the given tag. This has two main uses. + * </p> + * + * <p> + * First, if the root tag is replaced with a standard YAML tag, such as <code>Tag.MAP</code>, then + * the object will be dumped as a map. The root tag will appear as <code>!!map</code>, or blank + * (implicit !!map). + * </p> + * + * <p> + * Second, if the root tag is replaced by a different custom tag, then the document appears to be + * a different type when loaded. For example, if an instance of MyClass is dumped with the tag + * !!YourClass, then it will be handled as an instance of YourClass when loaded. + * </p> + * + * @param data Java object to be serialized to YAML + * @param rootTag the tag for the whole YAML document. The tag should be Tag.MAP for a JavaBean to + * make the tag disappear (to use implicit tag !!map). If <code>null</code> is provided + * then the standard tag with the full class name is used. + * @param flowStyle flow style for the whole document. See Chapter 10. Collection Styles + * http://yaml.org/spec/1.1/#id930798. If <code>null</code> is provided then the flow style + * from DumperOptions is used. + * @return YAML String + */ + public String dumpAs(Object data, Tag rootTag, FlowStyle flowStyle) { + FlowStyle oldStyle = representer.getDefaultFlowStyle(); + if (flowStyle != null) { + representer.setDefaultFlowStyle(flowStyle); + } + List<Object> list = new ArrayList<Object>(1); + list.add(data); + StringWriter buffer = new StringWriter(); + dumpAll(list.iterator(), buffer, rootTag); + representer.setDefaultFlowStyle(oldStyle); + return buffer.toString(); + } + + /** + * <p> + * Serialize a Java object into a YAML string. Override the default root tag with + * <code>Tag.MAP</code>. + * </p> + * <p> + * This method is similar to <code>Yaml.dump(data)</code> except that the root tag for the whole + * document is replaced with <code>Tag.MAP</code> tag (implicit !!map). + * </p> + * <p> + * Block Mapping is used as the collection style. See 10.2.2. Block Mappings + * (http://yaml.org/spec/1.1/#id934537) + * </p> + * + * @param data Java object to be serialized to YAML + * @return YAML String + */ + public String dumpAsMap(Object data) { + return dumpAs(data, Tag.MAP, FlowStyle.BLOCK); + } + + /** + * Serialize (dump) a YAML node into a YAML stream. + * + * @param node YAML node to be serialized to YAML + * @param output stream to write to + */ + public void serialize(Node node, Writer output) { + Serializer serializer = + new Serializer(new Emitter(output, dumperOptions), resolver, dumperOptions, null); + try { + serializer.open(); + serializer.serialize(node); + serializer.close(); + } catch (IOException e) { + throw new YAMLException(e); + } + } + + /** + * Serialize the representation tree into Events. + * + * @param data representation tree + * @return Event list + * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a> + */ + public List<Event> serialize(Node data) { + SilentEmitter emitter = new SilentEmitter(); + Serializer serializer = new Serializer(emitter, resolver, dumperOptions, null); + try { + serializer.open(); + serializer.serialize(data); + serializer.close(); + } catch (IOException e) { + throw new YAMLException(e); + } + return emitter.getEvents(); + } + + private static class SilentEmitter implements Emitable { + + private final List<Event> events = new ArrayList<Event>(100); + + public List<Event> getEvents() { + return events; } - /** - * Serialize the representation tree into Events. - * - * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a> - * @param data - * representation tree - * @return Event list - */ - public List<Event> serialize(Node data) { - SilentEmitter emitter = new SilentEmitter(); - Serializer serializer = new Serializer(emitter, resolver, dumperOptions, null); - try { - serializer.open(); - serializer.serialize(data); - serializer.close(); - } catch (IOException e) { - throw new YAMLException(e); - } - return emitter.getEvents(); + @Override + public void emit(Event event) throws IOException { + events.add(event); + } + } + + /** + * Parse the only YAML document in a String and produce the corresponding Java object. (Because + * the encoding in known BOM is not respected.) + * + * @param yaml YAML data to load from (BOM must not be present) + * @param <T> the class of the instance to be created + * @return parsed object + */ + @SuppressWarnings("unchecked") + public <T> T load(String yaml) { + return (T) loadFromReader(new StreamReader(yaml), Object.class); + } + + /** + * Parse the only YAML document in a stream and produce the corresponding Java object. + * + * @param io data to load from (BOM is respected to detect encoding and removed from the data) + * @param <T> the class of the instance to be created + * @return parsed object + */ + @SuppressWarnings("unchecked") + public <T> T load(InputStream io) { + return (T) loadFromReader(new StreamReader(new UnicodeReader(io)), Object.class); + } + + /** + * Parse the only YAML document in a stream and produce the corresponding Java object. + * + * @param io data to load from (BOM must not be present) + * @param <T> the class of the instance to be created + * @return parsed object + */ + @SuppressWarnings("unchecked") + public <T> T load(Reader io) { + return (T) loadFromReader(new StreamReader(io), Object.class); + } + + /** + * Parse the only YAML document in a stream and produce the corresponding Java object. + * + * @param <T> Class is defined by the second argument + * @param io data to load from (BOM must not be present) + * @param type Class of the object to be created + * @return parsed object + */ + @SuppressWarnings("unchecked") + public <T> T loadAs(Reader io, Class<T> type) { + return (T) loadFromReader(new StreamReader(io), type); + } + + /** + * Parse the only YAML document in a String and produce the corresponding Java object. (Because + * the encoding in known BOM is not respected.) + * + * @param <T> Class is defined by the second argument + * @param yaml YAML data to load from (BOM must not be present) + * @param type Class of the object to be created + * @return parsed object + */ + @SuppressWarnings("unchecked") + public <T> T loadAs(String yaml, Class<T> type) { + return (T) loadFromReader(new StreamReader(yaml), type); + } + + /** + * Parse the only YAML document in a stream and produce the corresponding Java object. + * + * @param <T> Class is defined by the second argument + * @param input data to load from (BOM is respected to detect encoding and removed from the data) + * @param type Class of the object to be created + * @return parsed object + */ + @SuppressWarnings("unchecked") + public <T> T loadAs(InputStream input, Class<T> type) { + return (T) loadFromReader(new StreamReader(new UnicodeReader(input)), type); + } + + private Object loadFromReader(StreamReader sreader, Class<?> type) { + Composer composer = + new Composer(new ParserImpl(sreader, loadingConfig), resolver, loadingConfig); + constructor.setComposer(composer); + return constructor.getSingleData(type); + } + + /** + * Parse all YAML documents in the Reader and produce corresponding Java objects. The documents + * are parsed only when the iterator is invoked. + * + * @param yaml YAML data to load from (BOM must not be present) + * @return an Iterable over the parsed Java objects in this String in proper sequence + */ + public Iterable<Object> loadAll(Reader yaml) { + Composer composer = + new Composer(new ParserImpl(new StreamReader(yaml), loadingConfig.isProcessComments()), + resolver, loadingConfig); + constructor.setComposer(composer); + Iterator<Object> result = new Iterator<Object>() { + @Override + public boolean hasNext() { + return constructor.checkData(); + } + + @Override + public Object next() { + return constructor.getData(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + return new YamlIterable(result); + } + + private static class YamlIterable implements Iterable<Object> { + + private final Iterator<Object> iterator; + + public YamlIterable(Iterator<Object> iterator) { + this.iterator = iterator; } - private static class SilentEmitter implements Emitable { - private List<Event> events = new ArrayList<Event>(100); - - public List<Event> getEvents() { - return events; - } - - public void emit(Event event) throws IOException { - events.add(event); + @Override + public Iterator<Object> iterator() { + return iterator; + } + } + + /** + * Parse all YAML documents in a String and produce corresponding Java objects. (Because the + * encoding in known BOM is not respected.) The documents are parsed only when the iterator is + * invoked. + * + * @param yaml YAML data to load from (BOM must not be present) + * @return an Iterable over the parsed Java objects in this String in proper sequence + */ + public Iterable<Object> loadAll(String yaml) { + return loadAll(new StringReader(yaml)); + } + + /** + * Parse all YAML documents in a stream and produce corresponding Java objects. The documents are + * parsed only when the iterator is invoked. + * + * @param yaml YAML data to load from (BOM is respected to detect encoding and removed from the + * data) + * @return an Iterable over the parsed Java objects in this stream in proper sequence + */ + public Iterable<Object> loadAll(InputStream yaml) { + return loadAll(new UnicodeReader(yaml)); + } + + /** + * Parse the first YAML document in a stream and produce the corresponding representation tree. + * (This is the opposite of the represent() method) + * + * @param yaml YAML document + * @return parsed root Node for the specified YAML document + * @see <a href="http://yaml.org/spec/1.1/#id859333">Figure 3.1. Processing Overview</a> + */ + public Node compose(Reader yaml) { + Composer composer = + new Composer(new ParserImpl(new StreamReader(yaml), loadingConfig.isProcessComments()), + resolver, loadingConfig); + return composer.getSingleNode(); + } + + /** + * Parse all YAML documents in a stream and produce corresponding representation trees. + * + * @param yaml stream of YAML documents + * @return parsed root Nodes for all the specified YAML documents + * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a> + */ + public Iterable<Node> composeAll(Reader yaml) { + final Composer composer = + new Composer(new ParserImpl(new StreamReader(yaml), loadingConfig.isProcessComments()), + resolver, loadingConfig); + Iterator<Node> result = new Iterator<Node>() { + @Override + public boolean hasNext() { + return composer.checkNode(); + } + + @Override + public Node next() { + Node node = composer.getNode(); + if (node != null) { + return node; + } else { + throw new NoSuchElementException("No Node is available."); } - } + } - /** - * Parse the only YAML document in a String and produce the corresponding - * Java object. (Because the encoding in known BOM is not respected.) - * - * @param yaml - * YAML data to load from (BOM must not be present) - * @return parsed object - */ - public Object load(String yaml) { - return loadFromReader(new StreamReader(yaml), Object.class); - } - - /** - * Parse the only YAML document in a stream and produce the corresponding - * Java object. - * - * @param io - * data to load from (BOM is respected and removed) - * @return parsed object - */ - public Object load(InputStream io) { - return loadFromReader(new StreamReader(new UnicodeReader(io)), Object.class); - } - - /** - * Parse the only YAML document in a stream and produce the corresponding - * Java object. - * - * @param io - * data to load from (BOM must not be present) - * @return parsed object - */ - public Object load(Reader io) { - return loadFromReader(new StreamReader(io), Object.class); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + return new NodeIterable(result); + } - /** - * Parse the only YAML document in a stream and produce the corresponding - * Java object. - * - * @param <T> - * Class is defined by the second argument - * @param io - * data to load from (BOM must not be present) - * @param type - * Class of the object to be created - * @return parsed object - */ - @SuppressWarnings("unchecked") - public <T> T loadAs(Reader io, Class<T> type) { - return (T) loadFromReader(new StreamReader(io), type); - } - - /** - * Parse the only YAML document in a String and produce the corresponding - * Java object. (Because the encoding in known BOM is not respected.) - * - * @param <T> - * Class is defined by the second argument - * @param yaml - * YAML data to load from (BOM must not be present) - * @param type - * Class of the object to be created - * @return parsed object - */ - @SuppressWarnings("unchecked") - public <T> T loadAs(String yaml, Class<T> type) { - return (T) loadFromReader(new StreamReader(yaml), type); - } - - /** - * Parse the only YAML document in a stream and produce the corresponding - * Java object. - * - * @param <T> - * Class is defined by the second argument - * @param input - * data to load from (BOM is respected and removed) - * @param type - * Class of the object to be created - * @return parsed object - */ - @SuppressWarnings("unchecked") - public <T> T loadAs(InputStream input, Class<T> type) { - return (T) loadFromReader(new StreamReader(new UnicodeReader(input)), type); - } + private static class NodeIterable implements Iterable<Node> { - private Object loadFromReader(StreamReader sreader, Class<?> type) { - Composer composer = new Composer(new ParserImpl(sreader), resolver); - constructor.setComposer(composer); - return constructor.getSingleData(type); - } + private final Iterator<Node> iterator; - /** - * Parse all YAML documents in a String and produce corresponding Java - * objects. The documents are parsed only when the iterator is invoked. - * - * @param yaml - * YAML data to load from (BOM must not be present) - * @return an iterator over the parsed Java objects in this String in proper - * sequence - */ - public Iterable<Object> loadAll(Reader yaml) { - Composer composer = new Composer(new ParserImpl(new StreamReader(yaml)), resolver); - constructor.setComposer(composer); - Iterator<Object> result = new Iterator<Object>() { - public boolean hasNext() { - return constructor.checkData(); - } - - public Object next() { - return constructor.getData(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - return new YamlIterable(result); + public NodeIterable(Iterator<Node> iterator) { + this.iterator = iterator; } - private static class YamlIterable implements Iterable<Object> { - private Iterator<Object> iterator; - - public YamlIterable(Iterator<Object> iterator) { - this.iterator = iterator; - } - - public Iterator<Object> iterator() { - return iterator; + @Override + public Iterator<Node> iterator() { + return iterator; + } + } + + /** + * Add an implicit scalar detector. If an implicit scalar value matches the given regexp, the + * corresponding tag is assigned to the scalar. + * + * @param tag tag to assign to the node + * @param regexp regular expression to match against + * @param first a sequence of possible initial characters or null (which means any). + */ + public void addImplicitResolver(Tag tag, Pattern regexp, String first) { + resolver.addImplicitResolver(tag, regexp, first); + } + + /** + * Add an implicit scalar detector. If an implicit scalar value matches the given regexp, the + * corresponding tag is assigned to the scalar. + * + * @param tag tag to assign to the node + * @param regexp regular expression to match against + * @param first a sequence of possible initial characters or null (which means any). + * @param limit the max length of the value which may match the regular expression + */ + public void addImplicitResolver(Tag tag, Pattern regexp, String first, int limit) { + resolver.addImplicitResolver(tag, regexp, first, limit); + } + + @Override + public String toString() { + return name; + } + + /** + * Get a meaningful name. It simplifies debugging in a multi-threaded environment. If nothing is + * set explicitly the address of the instance is returned. + * + * @return human readable name + */ + public String getName() { + return name; + } + + /** + * Set a meaningful name to be shown in toString() + * + * @param name human readable name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Parse a YAML stream and produce parsing events. + * + * @param yaml YAML document(s) + * @return parsed events + * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a> + */ + public Iterable<Event> parse(Reader yaml) { + final Parser parser = new ParserImpl(new StreamReader(yaml), loadingConfig.isProcessComments()); + Iterator<Event> result = new Iterator<Event>() { + @Override + public boolean hasNext() { + return parser.peekEvent() != null; + } + + @Override + public Event next() { + Event event = parser.getEvent(); + if (event != null) { + return event; + } else { + throw new NoSuchElementException("No Event is available."); } - } - - /** - * Parse all YAML documents in a String and produce corresponding Java - * objects. (Because the encoding in known BOM is not respected.) The - * documents are parsed only when the iterator is invoked. - * - * @param yaml - * YAML data to load from (BOM must not be present) - * @return an iterator over the parsed Java objects in this String in proper - * sequence - */ - public Iterable<Object> loadAll(String yaml) { - return loadAll(new StringReader(yaml)); - } - - /** - * Parse all YAML documents in a stream and produce corresponding Java - * objects. The documents are parsed only when the iterator is invoked. - * - * @param yaml - * YAML data to load from (BOM is respected and ignored) - * @return an iterator over the parsed Java objects in this stream in proper - * sequence - */ - public Iterable<Object> loadAll(InputStream yaml) { - return loadAll(new UnicodeReader(yaml)); - } + } - /** - * Parse the first YAML document in a stream and produce the corresponding - * representation tree. (This is the opposite of the represent() method) - * - * @see <a href="http://yaml.org/spec/1.1/#id859333">Figure 3.1. Processing - * Overview</a> - * @param yaml - * YAML document - * @return parsed root Node for the specified YAML document - */ - public Node compose(Reader yaml) { - Composer composer = new Composer(new ParserImpl(new StreamReader(yaml)), resolver); - constructor.setComposer(composer); - return composer.getSingleNode(); - } - - /** - * Parse all YAML documents in a stream and produce corresponding - * representation trees. - * - * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a> - * @param yaml - * stream of YAML documents - * @return parsed root Nodes for all the specified YAML documents - */ - public Iterable<Node> composeAll(Reader yaml) { - final Composer composer = new Composer(new ParserImpl(new StreamReader(yaml)), resolver); - constructor.setComposer(composer); - Iterator<Node> result = new Iterator<Node>() { - public boolean hasNext() { - return composer.checkNode(); - } - - public Node next() { - return composer.getNode(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - return new NodeIterable(result); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + return new EventIterable(result); + } - private static class NodeIterable implements Iterable<Node> { - private Iterator<Node> iterator; - - public NodeIterable(Iterator<Node> iterator) { - this.iterator = iterator; - } + private static class EventIterable implements Iterable<Event> { - public Iterator<Node> iterator() { - return iterator; - } - } + private final Iterator<Event> iterator; - /** - * Add an implicit scalar detector. If an implicit scalar value matches the - * given regexp, the corresponding tag is assigned to the scalar. - * - * @param tag - * tag to assign to the node - * @param regexp - * regular expression to match against - * @param first - * a sequence of possible initial characters or null (which means - * any). - */ - public void addImplicitResolver(Tag tag, Pattern regexp, String first) { - resolver.addImplicitResolver(tag, regexp, first); + public EventIterable(Iterator<Event> iterator) { + this.iterator = iterator; } @Override - public String toString() { - return name; - } - - /** - * Get a meaningful name. It simplifies debugging in a multi-threaded - * environment. If nothing is set explicitly the address of the instance is - * returned. - * - * @return human readable name - */ - public String getName() { - return name; - } - - /** - * Set a meaningful name to be shown in toString() - * - * @param name - * human readable name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Parse a YAML stream and produce parsing events. - * - * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a> - * @param yaml - * YAML document(s) - * @return parsed events - */ - public Iterable<Event> parse(Reader yaml) { - final Parser parser = new ParserImpl(new StreamReader(yaml)); - Iterator<Event> result = new Iterator<Event>() { - public boolean hasNext() { - return parser.peekEvent() != null; - } - - public Event next() { - return parser.getEvent(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - return new EventIterable(result); - } - - private static class EventIterable implements Iterable<Event> { - private Iterator<Event> iterator; - - public EventIterable(Iterator<Event> iterator) { - this.iterator = iterator; - } - - public Iterator<Event> iterator() { - return iterator; - } + public Iterator<Event> iterator() { + return iterator; } + } - public void setBeanAccess(BeanAccess beanAccess) { - constructor.getPropertyUtils().setBeanAccess(beanAccess); - representer.getPropertyUtils().setBeanAccess(beanAccess); - } + public void setBeanAccess(BeanAccess beanAccess) { + constructor.getPropertyUtils().setBeanAccess(beanAccess); + representer.getPropertyUtils().setBeanAccess(beanAccess); + } + public void addTypeDescription(TypeDescription td) { + constructor.addTypeDescription(td); + representer.addTypeDescription(td); + } } diff --git a/src/main/java/org/yaml/snakeyaml/comments/CommentEventsCollector.java b/src/main/java/org/yaml/snakeyaml/comments/CommentEventsCollector.java new file mode 100644 index 00000000..f1994217 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/comments/CommentEventsCollector.java @@ -0,0 +1,177 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comments; + +import java.util.AbstractQueue; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Queue; +import org.yaml.snakeyaml.events.CommentEvent; +import org.yaml.snakeyaml.events.Event; +import org.yaml.snakeyaml.parser.Parser; + +/** + * Used by the Composer and Emitter to collect comment events so that they can be used at a later + * point in the process. + */ +public class CommentEventsCollector { + + private List<CommentLine> commentLineList; + private final Queue<Event> eventSource; + private final CommentType[] expectedCommentTypes; + + /** + * Constructor used to collect comment events emitted by a Parser. + * + * @param parser the event source. + * @param expectedCommentTypes the comment types expected. Any comment types not included are not + * collected. + */ + public CommentEventsCollector(final Parser parser, CommentType... expectedCommentTypes) { + this.eventSource = new AbstractQueue<Event>() { + + @Override + public boolean offer(Event e) { + throw new UnsupportedOperationException(); + } + + @Override + public Event poll() { + return parser.getEvent(); + } + + @Override + public Event peek() { + return parser.peekEvent(); + } + + @Override + public Iterator<Event> iterator() { + throw new UnsupportedOperationException(); + } + + @Override + public int size() { + throw new UnsupportedOperationException(); + } + + }; + this.expectedCommentTypes = expectedCommentTypes; + commentLineList = new ArrayList<>(); + } + + /** + * Constructor used to collect events emitted by the Serializer. + * + * @param eventSource the event source. + * + * @param expectedCommentTypes the comment types expected. Any comment types not included are not + * collected. + */ + public CommentEventsCollector(Queue<Event> eventSource, CommentType... expectedCommentTypes) { + this.eventSource = eventSource; + this.expectedCommentTypes = expectedCommentTypes; + commentLineList = new ArrayList<>(); + } + + /** + * Determine if the event is a comment of one of the expected types set during construction. + * + * @param event the event to test. + * @return <code>true</code> if the events is a comment of the expected type; Otherwise, false. + */ + private boolean isEventExpected(Event event) { + if (event == null || !event.is(Event.ID.Comment)) { + return false; + } + CommentEvent commentEvent = (CommentEvent) event; + for (CommentType type : expectedCommentTypes) { + if (commentEvent.getCommentType() == type) { + return true; + } + } + return false; + } + + /** + * Collect all events of the expected type (set during construction) starting with the top event + * on the event source. Collection stops as soon as a non comment or comment of the unexpected + * type is encountered. + * + * @return this object. + */ + public CommentEventsCollector collectEvents() { + collectEvents(null); + return this; + } + + /** + * Collect all events of the expected type (set during construction) starting with event provided + * as an argument and continuing with the top event on the event source. Collection stops as soon + * as a non comment or comment of the unexpected type is encountered. + * + * @param event the first event to attempt to collect. + * @return the event provided as an argument, if it is not collected; Otherwise, <code>null</code> + */ + public Event collectEvents(Event event) { + if (event != null) { + if (isEventExpected(event)) { + commentLineList.add(new CommentLine((CommentEvent) event)); + } else { + return event; + } + } + while (isEventExpected(eventSource.peek())) { + commentLineList.add(new CommentLine((CommentEvent) eventSource.poll())); + } + return null; + } + + /** + * Collect all events of the expected type (set during construction) starting with event provided + * as an argument and continuing with the top event on the event source. Collection stops as soon + * as a non comment or comment of the unexpected type is encountered. + * + * @param event the first event to attempt to collect. + * @return the event provided as an argument, if it is not collected; Otherwise, the first event + * that is not collected. + */ + public Event collectEventsAndPoll(Event event) { + Event nextEvent = collectEvents(event); + return nextEvent != null ? nextEvent : eventSource.poll(); + } + + /** + * Return the events collected and reset the colletor. + * + * @return the events collected. + */ + public List<CommentLine> consume() { + try { + return commentLineList; + } finally { + commentLineList = new ArrayList<>(); + } + } + + /** + * Test if the collector contains any collected events. + * + * @return <code>true</code> if it does; Otherwise, <code>false</code> + */ + public boolean isEmpty() { + return commentLineList.isEmpty(); + } +} diff --git a/src/main/java/org/yaml/snakeyaml/comments/CommentLine.java b/src/main/java/org/yaml/snakeyaml/comments/CommentLine.java new file mode 100644 index 00000000..76ecd1b4 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/comments/CommentLine.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comments; + +import org.yaml.snakeyaml.error.Mark; +import org.yaml.snakeyaml.events.CommentEvent; + +/** + * A comment line. May be a block comment, blank line, or inline comment. + */ +public class CommentLine { + + private final Mark startMark; + private final Mark endMark; + private final String value; + private final CommentType commentType; + + public CommentLine(CommentEvent event) { + this(event.getStartMark(), event.getEndMark(), event.getValue(), event.getCommentType()); + } + + public CommentLine(Mark startMark, Mark endMark, String value, CommentType commentType) { + this.startMark = startMark; + this.endMark = endMark; + this.value = value; + this.commentType = commentType; + } + + public Mark getEndMark() { + return endMark; + } + + public Mark getStartMark() { + return startMark; + } + + public CommentType getCommentType() { + return commentType; + } + + /** + * Value of this comment. + * + * @return comment's value. + */ + public String getValue() { + return value; + } + + public String toString() { + return "<" + this.getClass().getName() + " (type=" + getCommentType() + ", value=" + getValue() + + ")>"; + } +} diff --git a/src/main/java/org/yaml/snakeyaml/comments/CommentType.java b/src/main/java/org/yaml/snakeyaml/comments/CommentType.java new file mode 100644 index 00000000..5ee7cf47 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/comments/CommentType.java @@ -0,0 +1,23 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comments; + +/** + * The type of a comment line. + */ +public enum CommentType { + BLANK_LINE, // + BLOCK, // + IN_LINE // +} diff --git a/src/main/java/org/yaml/snakeyaml/composer/Composer.java b/src/main/java/org/yaml/snakeyaml/composer/Composer.java index f8223c29..d89aa234 100644 --- a/src/main/java/org/yaml/snakeyaml/composer/Composer.java +++ b/src/main/java/org/yaml/snakeyaml/composer/Composer.java @@ -1,27 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.composer; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.comments.CommentEventsCollector; +import org.yaml.snakeyaml.comments.CommentLine; +import org.yaml.snakeyaml.comments.CommentType; +import org.yaml.snakeyaml.error.Mark; +import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.events.AliasEvent; import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.events.MappingStartEvent; @@ -41,208 +46,299 @@ import org.yaml.snakeyaml.resolver.Resolver; /** * Creates a node graph from parser events. * <p> - * Corresponds to the 'Compose' step as described in chapter 3.1 of the <a - * href="http://yaml.org/spec/1.1/">YAML Specification</a>. + * Corresponds to the 'Compose' step as described in chapter 3.1 of the + * <a href="http://yaml.org/spec/1.1/">YAML Specification</a>. * </p> */ public class Composer { - protected final Parser parser; - private final Resolver resolver; - private final Map<String, Node> anchors; - private final Set<Node> recursiveNodes; - - public Composer(Parser parser, Resolver resolver) { - this.parser = parser; - this.resolver = resolver; - this.anchors = new HashMap<String, Node>(); - this.recursiveNodes = new HashSet<Node>(); - } - - /** - * Checks if further documents are available. - * - * @return <code>true</code> if there is at least one more document. - */ - public boolean checkNode() { - // Drop the STREAM-START event. - if (parser.checkEvent(Event.ID.StreamStart)) { - parser.getEvent(); - } - // If there are more documents available? - return !parser.checkEvent(Event.ID.StreamEnd); - } - - /** - * Reads and composes the next document. - * - * @return The root node of the document or <code>null</code> if no more - * documents are available. - */ - public Node getNode() { - // Get the root node of the next document. - if (!parser.checkEvent(Event.ID.StreamEnd)) { - return composeDocument(); - } else { - return null; - } + + protected final Parser parser; + private final Resolver resolver; + private final Map<String, Node> anchors; + private final Set<Node> recursiveNodes; + private int nonScalarAliasesCount = 0; + private final LoaderOptions loadingConfig; + private final CommentEventsCollector blockCommentsCollector; + private final CommentEventsCollector inlineCommentsCollector; + // keep the nesting of collections inside other collections + private int nestingDepth = 0; + private final int nestingDepthLimit; + + public Composer(Parser parser, Resolver resolver) { + this(parser, resolver, new LoaderOptions()); + } + + public Composer(Parser parser, Resolver resolver, LoaderOptions loadingConfig) { + this.parser = parser; + this.resolver = resolver; + this.anchors = new HashMap<String, Node>(); + this.recursiveNodes = new HashSet<Node>(); + this.loadingConfig = loadingConfig; + this.blockCommentsCollector = + new CommentEventsCollector(parser, CommentType.BLANK_LINE, CommentType.BLOCK); + this.inlineCommentsCollector = new CommentEventsCollector(parser, CommentType.IN_LINE); + nestingDepthLimit = loadingConfig.getNestingDepthLimit(); + } + + /** + * Checks if further documents are available. + * + * @return <code>true</code> if there is at least one more document. + */ + public boolean checkNode() { + // Drop the STREAM-START event. + if (parser.checkEvent(Event.ID.StreamStart)) { + parser.getEvent(); } + // If there are more documents available? + return !parser.checkEvent(Event.ID.StreamEnd); + } - /** - * Reads a document from a source that contains only one document. - * <p> - * If the stream contains more than one document an exception is thrown. - * </p> - * - * @return The root node of the document or <code>null</code> if no document - * is available. - */ - public Node getSingleNode() { - // Drop the STREAM-START event. - parser.getEvent(); - // Compose a document if the stream is not empty. - Node document = null; - if (!parser.checkEvent(Event.ID.StreamEnd)) { - document = composeDocument(); - } - // Ensure that the stream contains no more documents. - if (!parser.checkEvent(Event.ID.StreamEnd)) { - Event event = parser.getEvent(); - throw new ComposerException("expected a single document in the stream", - document.getStartMark(), "but found another document", event.getStartMark()); - } - // Drop the STREAM-END event. - parser.getEvent(); - return document; - } - - private Node composeDocument() { - // Drop the DOCUMENT-START event. - parser.getEvent(); - // Compose the root node. - Node node = composeNode(null); - // Drop the DOCUMENT-END event. - parser.getEvent(); - this.anchors.clear(); - recursiveNodes.clear(); - return node; - } - - private Node composeNode(Node parent) { - recursiveNodes.add(parent); - if (parser.checkEvent(Event.ID.Alias)) { - AliasEvent event = (AliasEvent) parser.getEvent(); - String anchor = event.getAnchor(); - if (!anchors.containsKey(anchor)) { - throw new ComposerException(null, null, "found undefined alias " + anchor, - event.getStartMark()); - } - Node result = anchors.get(anchor); - if (recursiveNodes.remove(result)) { - result.setTwoStepsConstruction(true); - } - return result; - } - NodeEvent event = (NodeEvent) parser.peekEvent(); - String anchor = null; - anchor = event.getAnchor(); - // the check for duplicate anchors has been removed (issue 174) - Node node = null; - if (parser.checkEvent(Event.ID.Scalar)) { - node = composeScalarNode(anchor); - } else if (parser.checkEvent(Event.ID.SequenceStart)) { - node = composeSequenceNode(anchor); - } else { - node = composeMappingNode(anchor); - } - recursiveNodes.remove(parent); - return node; - } - - protected Node composeScalarNode(String anchor) { - ScalarEvent ev = (ScalarEvent) parser.getEvent(); - String tag = ev.getTag(); - boolean resolved = false; - Tag nodeTag; - if (tag == null || tag.equals("!")) { - nodeTag = resolver.resolve(NodeId.scalar, ev.getValue(), ev.getImplicit() - .canOmitTagInPlainScalar()); - resolved = true; - } else { - nodeTag = new Tag(tag); - } - Node node = new ScalarNode(nodeTag, resolved, ev.getValue(), ev.getStartMark(), - ev.getEndMark(), ev.getStyle()); - if (anchor != null) { - anchors.put(anchor, node); - } - return node; - } - - protected Node composeSequenceNode(String anchor) { - SequenceStartEvent startEvent = (SequenceStartEvent) parser.getEvent(); - String tag = startEvent.getTag(); - Tag nodeTag; - boolean resolved = false; - if (tag == null || tag.equals("!")) { - nodeTag = resolver.resolve(NodeId.sequence, null, startEvent.getImplicit()); - resolved = true; - } else { - nodeTag = new Tag(tag); - } - final ArrayList<Node> children = new ArrayList<Node>(); - SequenceNode node = new SequenceNode(nodeTag, resolved, children, - startEvent.getStartMark(), null, startEvent.getFlowStyle()); - if (anchor != null) { - anchors.put(anchor, node); - } - while (!parser.checkEvent(Event.ID.SequenceEnd)) { - children.add(composeNode(node)); - } - Event endEvent = parser.getEvent(); - node.setEndMark(endEvent.getEndMark()); - return node; - } - - protected Node composeMappingNode(String anchor) { - MappingStartEvent startEvent = (MappingStartEvent) parser.getEvent(); - String tag = startEvent.getTag(); - Tag nodeTag; - boolean resolved = false; - if (tag == null || tag.equals("!")) { - nodeTag = resolver.resolve(NodeId.mapping, null, startEvent.getImplicit()); - resolved = true; - } else { - nodeTag = new Tag(tag); - } + /** + * Reads and composes the next document. + * + * @return The root node of the document or <code>null</code> if no more documents are available. + */ + public Node getNode() { + // Collect inter-document start comments + blockCommentsCollector.collectEvents(); + if (parser.checkEvent(Event.ID.StreamEnd)) { + List<CommentLine> commentLines = blockCommentsCollector.consume(); + Mark startMark = commentLines.get(0).getStartMark(); + List<NodeTuple> children = Collections.emptyList(); + Node node = new MappingNode(Tag.COMMENT, false, children, startMark, null, FlowStyle.BLOCK); + node.setBlockComments(commentLines); + return node; + } + // Drop the DOCUMENT-START event. + parser.getEvent(); + // Compose the root node. + Node node = composeNode(null); + // Drop the DOCUMENT-END event. + blockCommentsCollector.collectEvents(); + if (!blockCommentsCollector.isEmpty()) { + node.setEndComments(blockCommentsCollector.consume()); + } + parser.getEvent(); + this.anchors.clear(); + this.recursiveNodes.clear(); + return node; + } - final List<NodeTuple> children = new ArrayList<NodeTuple>(); - MappingNode node = new MappingNode(nodeTag, resolved, children, startEvent.getStartMark(), - null, startEvent.getFlowStyle()); - if (anchor != null) { - anchors.put(anchor, node); - } - while (!parser.checkEvent(Event.ID.MappingEnd)) { - composeMappingChildren(children, node); - } - Event endEvent = parser.getEvent(); - node.setEndMark(endEvent.getEndMark()); - return node; + /** + * Reads a document from a source that contains only one document. + * <p> + * If the stream contains more than one document an exception is thrown. + * </p> + * + * @return The root node of the document or <code>null</code> if no document is available. + */ + public Node getSingleNode() { + // Drop the STREAM-START event. + parser.getEvent(); + // Compose a document if the stream is not empty. + Node document = null; + if (!parser.checkEvent(Event.ID.StreamEnd)) { + document = getNode(); } + // Ensure that the stream contains no more documents. + if (!parser.checkEvent(Event.ID.StreamEnd)) { + Event event = parser.getEvent(); + Mark contextMark = document != null ? document.getStartMark() : null; + throw new ComposerException("expected a single document in the stream", contextMark, + "but found another document", event.getStartMark()); + } + // Drop the STREAM-END event. + parser.getEvent(); + return document; + } - protected void composeMappingChildren(List<NodeTuple> children, MappingNode node) { - Node itemKey = composeKeyNode(node); - if (itemKey.getTag().equals(Tag.MERGE)) { - node.setMerged(true); + private Node composeNode(Node parent) { + blockCommentsCollector.collectEvents(); + if (parent != null) { + recursiveNodes.add(parent); + } + final Node node; + if (parser.checkEvent(Event.ID.Alias)) { + AliasEvent event = (AliasEvent) parser.getEvent(); + String anchor = event.getAnchor(); + if (!anchors.containsKey(anchor)) { + throw new ComposerException(null, null, "found undefined alias " + anchor, + event.getStartMark()); + } + node = anchors.get(anchor); + if (!(node instanceof ScalarNode)) { + this.nonScalarAliasesCount++; + if (this.nonScalarAliasesCount > loadingConfig.getMaxAliasesForCollections()) { + throw new YAMLException( + "Number of aliases for non-scalar nodes exceeds the specified max=" + + loadingConfig.getMaxAliasesForCollections()); } - Node itemValue = composeValueNode(node); - children.add(new NodeTuple(itemKey, itemValue)); + } + if (recursiveNodes.remove(node)) { + node.setTwoStepsConstruction(true); + } + // drop comments, they can not be supported here + blockCommentsCollector.consume(); + inlineCommentsCollector.collectEvents().consume(); + } else { + NodeEvent event = (NodeEvent) parser.peekEvent(); + String anchor = event.getAnchor(); + increaseNestingDepth(); + // the check for duplicate anchors has been removed (issue 174) + if (parser.checkEvent(Event.ID.Scalar)) { + node = composeScalarNode(anchor, blockCommentsCollector.consume()); + } else if (parser.checkEvent(Event.ID.SequenceStart)) { + node = composeSequenceNode(anchor); + } else { + node = composeMappingNode(anchor); + } + decreaseNestingDepth(); } + recursiveNodes.remove(parent); + return node; + } + + protected Node composeScalarNode(String anchor, List<CommentLine> blockComments) { + ScalarEvent ev = (ScalarEvent) parser.getEvent(); + String tag = ev.getTag(); + boolean resolved = false; + Tag nodeTag; + if (tag == null || tag.equals("!")) { + nodeTag = resolver.resolve(NodeId.scalar, ev.getValue(), + ev.getImplicit().canOmitTagInPlainScalar()); + resolved = true; + } else { + nodeTag = new Tag(tag); + } + Node node = new ScalarNode(nodeTag, resolved, ev.getValue(), ev.getStartMark(), ev.getEndMark(), + ev.getScalarStyle()); + if (anchor != null) { + node.setAnchor(anchor); + anchors.put(anchor, node); + } + node.setBlockComments(blockComments); + node.setInLineComments(inlineCommentsCollector.collectEvents().consume()); + return node; + } + + protected Node composeSequenceNode(String anchor) { + SequenceStartEvent startEvent = (SequenceStartEvent) parser.getEvent(); + String tag = startEvent.getTag(); + Tag nodeTag; + + boolean resolved = false; + if (tag == null || tag.equals("!")) { + nodeTag = resolver.resolve(NodeId.sequence, null, startEvent.getImplicit()); + resolved = true; + } else { + nodeTag = new Tag(tag); + } + final ArrayList<Node> children = new ArrayList<Node>(); + SequenceNode node = new SequenceNode(nodeTag, resolved, children, startEvent.getStartMark(), + null, startEvent.getFlowStyle()); + if (startEvent.isFlow()) { + node.setBlockComments(blockCommentsCollector.consume()); + } + if (anchor != null) { + node.setAnchor(anchor); + anchors.put(anchor, node); + } + while (!parser.checkEvent(Event.ID.SequenceEnd)) { + blockCommentsCollector.collectEvents(); + if (parser.checkEvent(Event.ID.SequenceEnd)) { + break; + } + children.add(composeNode(node)); + } + if (startEvent.isFlow()) { + node.setInLineComments(inlineCommentsCollector.collectEvents().consume()); + } + Event endEvent = parser.getEvent(); + node.setEndMark(endEvent.getEndMark()); + inlineCommentsCollector.collectEvents(); + if (!inlineCommentsCollector.isEmpty()) { + node.setInLineComments(inlineCommentsCollector.consume()); + } + return node; + } + + protected Node composeMappingNode(String anchor) { + MappingStartEvent startEvent = (MappingStartEvent) parser.getEvent(); + String tag = startEvent.getTag(); + Tag nodeTag; + boolean resolved = false; + if (tag == null || tag.equals("!")) { + nodeTag = resolver.resolve(NodeId.mapping, null, startEvent.getImplicit()); + resolved = true; + } else { + nodeTag = new Tag(tag); + } + + final List<NodeTuple> children = new ArrayList<NodeTuple>(); + MappingNode node = new MappingNode(nodeTag, resolved, children, startEvent.getStartMark(), null, + startEvent.getFlowStyle()); + if (startEvent.isFlow()) { + node.setBlockComments(blockCommentsCollector.consume()); + } + if (anchor != null) { + node.setAnchor(anchor); + anchors.put(anchor, node); + } + while (!parser.checkEvent(Event.ID.MappingEnd)) { + blockCommentsCollector.collectEvents(); + if (parser.checkEvent(Event.ID.MappingEnd)) { + break; + } + composeMappingChildren(children, node); + } + if (startEvent.isFlow()) { + node.setInLineComments(inlineCommentsCollector.collectEvents().consume()); + } + Event endEvent = parser.getEvent(); + node.setEndMark(endEvent.getEndMark()); + inlineCommentsCollector.collectEvents(); + if (!inlineCommentsCollector.isEmpty()) { + node.setInLineComments(inlineCommentsCollector.consume()); + } + return node; + } + + protected void composeMappingChildren(List<NodeTuple> children, MappingNode node) { + Node itemKey = composeKeyNode(node); + if (itemKey.getTag().equals(Tag.MERGE)) { + node.setMerged(true); + } + Node itemValue = composeValueNode(node); + children.add(new NodeTuple(itemKey, itemValue)); + } + + protected Node composeKeyNode(MappingNode node) { + return composeNode(node); + } + + protected Node composeValueNode(MappingNode node) { + return composeNode(node); + } - protected Node composeKeyNode(MappingNode node) { - return composeNode(node); + /** + * Increase nesting depth and fail when it exceeds the denied limit + */ + private void increaseNestingDepth() { + if (nestingDepth > nestingDepthLimit) { + throw new YAMLException("Nesting Depth exceeded max " + nestingDepthLimit); } + nestingDepth++; + } - protected Node composeValueNode(MappingNode node) { - return composeNode(node); + /** + * Indicate that the collection is finished and the nesting is decreased + */ + private void decreaseNestingDepth() { + if (nestingDepth > 0) { + nestingDepth--; + } else { + throw new YAMLException("Nesting Depth cannot be negative"); } + } } diff --git a/src/main/java/org/yaml/snakeyaml/composer/ComposerException.java b/src/main/java/org/yaml/snakeyaml/composer/ComposerException.java index 5d20c1d4..8e6cbd7f 100644 --- a/src/main/java/org/yaml/snakeyaml/composer/ComposerException.java +++ b/src/main/java/org/yaml/snakeyaml/composer/ComposerException.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.composer; @@ -19,9 +17,10 @@ import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.MarkedYAMLException; public class ComposerException extends MarkedYAMLException { - private static final long serialVersionUID = 2146314636913113935L; - protected ComposerException(String context, Mark contextMark, String problem, Mark problemMark) { - super(context, contextMark, problem, problemMark); - } + private static final long serialVersionUID = 2146314636913113935L; + + protected ComposerException(String context, Mark contextMark, String problem, Mark problemMark) { + super(context, contextMark, problem, problemMark); + } } diff --git a/src/main/java/org/yaml/snakeyaml/constructor/AbstractConstruct.java b/src/main/java/org/yaml/snakeyaml/constructor/AbstractConstruct.java index 61d14f60..ff0e3bbd 100644 --- a/src/main/java/org/yaml/snakeyaml/constructor/AbstractConstruct.java +++ b/src/main/java/org/yaml/snakeyaml/constructor/AbstractConstruct.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,23 +17,22 @@ import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.nodes.Node; /** - * Because recursive structures are not very common we provide a way to save - * some typing when extending a constructor + * Because recursive structures are not very common we provide a way to save some typing when + * extending a constructor */ public abstract class AbstractConstruct implements Construct { - /** - * Fail with a reminder to provide the seconds step for a recursive - * structure - * - * @see org.yaml.snakeyaml.constructor.Construct#construct2ndStep(org.yaml.snakeyaml.nodes.Node, - * java.lang.Object) - */ - public void construct2ndStep(Node node, Object data) { - if (node.isTwoStepsConstruction()) { - throw new IllegalStateException("Not Implemented in " + getClass().getName()); - } else { - throw new YAMLException("Unexpected recursive structure for Node: " + node); - } + /** + * Fail with a reminder to provide the seconds step for a recursive structure + * + * @see org.yaml.snakeyaml.constructor.Construct#construct2ndStep(org.yaml.snakeyaml.nodes.Node, + * java.lang.Object) + */ + public void construct2ndStep(Node node, Object data) { + if (node.isTwoStepsConstruction()) { + throw new IllegalStateException("Not Implemented in " + getClass().getName()); + } else { + throw new YAMLException("Unexpected recursive structure for Node: " + node); } + } } diff --git a/src/main/java/org/yaml/snakeyaml/constructor/BaseConstructor.java b/src/main/java/org/yaml/snakeyaml/constructor/BaseConstructor.java index 3a504cbb..a4ed1f50 100644 --- a/src/main/java/org/yaml/snakeyaml/constructor/BaseConstructor.java +++ b/src/main/java/org/yaml/snakeyaml/constructor/BaseConstructor.java @@ -1,21 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.lang.reflect.Array; +import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; @@ -25,12 +24,19 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Set; - +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.composer.ComposerException; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.introspector.PropertyUtils; +import org.yaml.snakeyaml.nodes.CollectionNode; import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeId; @@ -40,411 +46,578 @@ import org.yaml.snakeyaml.nodes.SequenceNode; import org.yaml.snakeyaml.nodes.Tag; public abstract class BaseConstructor { - /** - * It maps the node kind to the the Construct implementation. When the - * runtime class is known then the implicit tag is ignored. - */ - protected final Map<NodeId, Construct> yamlClassConstructors = new EnumMap<NodeId, Construct>( - NodeId.class); - /** - * It maps the (explicit or implicit) tag to the Construct implementation. - * It is used: <br/> - * 1) explicit tag - if present. <br/> - * 2) implicit tag - when the runtime class of the instance is unknown (the - * node has the Object.class) - */ - protected final Map<Tag, Construct> yamlConstructors = new HashMap<Tag, Construct>(); - /** - * It maps the (explicit or implicit) tag to the Construct implementation. - * It is used when no exact match found. - */ - protected final Map<String, Construct> yamlMultiConstructors = new HashMap<String, Construct>(); - - protected Composer composer; - private final Map<Node, Object> constructedObjects; - private final Set<Node> recursiveObjects; - private final ArrayList<RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>> maps2fill; - private final ArrayList<RecursiveTuple<Set<Object>, Object>> sets2fill; - - protected Tag rootTag; - private PropertyUtils propertyUtils; - private boolean explicitPropertyUtils; - - public BaseConstructor() { - constructedObjects = new HashMap<Node, Object>(); - recursiveObjects = new HashSet<Node>(); - maps2fill = new ArrayList<RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>>(); - sets2fill = new ArrayList<RecursiveTuple<Set<Object>, Object>>(); - rootTag = null; - explicitPropertyUtils = false; - } - public void setComposer(Composer composer) { - this.composer = composer; + /** + * An instance returned by newInstance methods when instantiation has not been performed. + */ + protected static final Object NOT_INSTANTIATED_OBJECT = new Object(); + + /** + * It maps the node kind to the the Construct implementation. When the runtime class is known then + * the implicit tag is ignored. + */ + protected final Map<NodeId, Construct> yamlClassConstructors = + new EnumMap<NodeId, Construct>(NodeId.class); + /** + * It maps the (explicit or implicit) tag to the Construct implementation. It is used: 1) explicit + * tag - if present. 2) implicit tag - when the runtime class of the instance is unknown (the node + * has the Object.class) + */ + protected final Map<Tag, Construct> yamlConstructors = new HashMap<Tag, Construct>(); + /** + * It maps the (explicit or implicit) tag to the Construct implementation. It is used when no + * exact match found. + */ + protected final Map<String, Construct> yamlMultiConstructors = new HashMap<String, Construct>(); + + protected Composer composer; + final Map<Node, Object> constructedObjects; + private final Set<Node> recursiveObjects; + private final ArrayList<RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>> maps2fill; + private final ArrayList<RecursiveTuple<Set<Object>, Object>> sets2fill; + + protected Tag rootTag; + private PropertyUtils propertyUtils; + private boolean explicitPropertyUtils; + private boolean allowDuplicateKeys = true; + private boolean wrappedToRootException = false; + + private boolean enumCaseSensitive = false; + + protected final Map<Class<? extends Object>, TypeDescription> typeDefinitions; + protected final Map<Tag, Class<? extends Object>> typeTags; + + protected LoaderOptions loadingConfig; + + public BaseConstructor() { + this(new LoaderOptions()); + } + + public BaseConstructor(LoaderOptions loadingConfig) { + constructedObjects = new HashMap<Node, Object>(); + recursiveObjects = new HashSet<Node>(); + maps2fill = + new ArrayList<RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>>(); + sets2fill = new ArrayList<RecursiveTuple<Set<Object>, Object>>(); + typeDefinitions = new HashMap<Class<? extends Object>, TypeDescription>(); + typeTags = new HashMap<Tag, Class<? extends Object>>(); + + rootTag = null; + explicitPropertyUtils = false; + + typeDefinitions.put(SortedMap.class, + new TypeDescription(SortedMap.class, Tag.OMAP, TreeMap.class)); + typeDefinitions.put(SortedSet.class, + new TypeDescription(SortedSet.class, Tag.SET, TreeSet.class)); + this.loadingConfig = loadingConfig; + } + + public void setComposer(Composer composer) { + this.composer = composer; + } + + /** + * Check if more documents available + * + * @return true when there are more YAML documents in the stream + */ + public boolean checkData() { + // If there are more documents available? + return composer.checkNode(); + } + + /** + * Construct and return the next document + * + * @return constructed instance + */ + public Object getData() throws NoSuchElementException { + // Construct and return the next document. + if (!composer.checkNode()) { + throw new NoSuchElementException("No document is available."); } - - /** - * Check if more documents available - * - * @return true when there are more YAML documents in the stream - */ - public boolean checkData() { - // If there are more documents available? - return composer.checkNode(); + Node node = composer.getNode(); + if (rootTag != null) { + node.setTag(rootTag); } - - /** - * Construct and return the next document - * - * @return constructed instance - */ - public Object getData() { - // Construct and return the next document. - composer.checkNode(); - Node node = composer.getNode(); - if (rootTag != null) { - node.setTag(rootTag); - } - return constructDocument(node); + return constructDocument(node); + } + + /** + * Ensure that the stream contains a single document and construct it + * + * @param type the class of the instance being created + * @return constructed instance + * @throws ComposerException in case there are more documents in the stream + */ + public Object getSingleData(Class<?> type) { + // Ensure that the stream contains a single document and construct it + final Node node = composer.getSingleNode(); + if (node != null && !Tag.NULL.equals(node.getTag())) { + if (Object.class != type) { + node.setTag(new Tag(type)); + } else if (rootTag != null) { + node.setTag(rootTag); + } + return constructDocument(node); + } else { + Construct construct = yamlConstructors.get(Tag.NULL); + return construct.construct(node); } - - /** - * Ensure that the stream contains a single document and construct it - * - * @return constructed instance - * @throws ComposerException - * in case there are more documents in the stream - */ - public Object getSingleData(Class<?> type) { - // Ensure that the stream contains a single document and construct it - Node node = composer.getSingleNode(); - if (node != null) { - if (Object.class != type) { - node.setTag(new Tag(type)); - } else if (rootTag != null) { - node.setTag(rootTag); - } - return constructDocument(node); - } - return null; + } + + /** + * Construct complete YAML document. Call the second step in case of recursive structures. At the + * end cleans all the state. + * + * @param node root Node + * @return Java instance + */ + protected final Object constructDocument(Node node) { + try { + Object data = constructObject(node); + fillRecursive(); + return data; + } catch (RuntimeException e) { + if (wrappedToRootException && !(e instanceof YAMLException)) { + throw new YAMLException(e); + } else { + throw e; + } + } finally { + // clean up resources + constructedObjects.clear(); + recursiveObjects.clear(); } - - /** - * Construct complete YAML document. Call the second step in case of - * recursive structures. At the end cleans all the state. - * - * @param node - * root Node - * @return Java instance - */ - protected final Object constructDocument(Node node) { - Object data = constructObject(node); - fillRecursive(); - constructedObjects.clear(); - recursiveObjects.clear(); - return data; + } + + /** + * Fill the recursive structures and clean the internal collections + */ + private void fillRecursive() { + if (!maps2fill.isEmpty()) { + for (RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>> entry : maps2fill) { + RecursiveTuple<Object, Object> key_value = entry._2(); + entry._1().put(key_value._1(), key_value._2()); + } + maps2fill.clear(); } - - private void fillRecursive() { - if (!maps2fill.isEmpty()) { - for (RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>> entry : maps2fill) { - RecursiveTuple<Object, Object> key_value = entry._2(); - entry._1().put(key_value._1(), key_value._2()); - } - maps2fill.clear(); - } - if (!sets2fill.isEmpty()) { - for (RecursiveTuple<Set<Object>, Object> value : sets2fill) { - value._1().add(value._2()); - } - sets2fill.clear(); - } + if (!sets2fill.isEmpty()) { + for (RecursiveTuple<Set<Object>, Object> value : sets2fill) { + value._1().add(value._2()); + } + sets2fill.clear(); } - - /** - * Construct object from the specified Node. Return existing instance if the - * node is already constructed. - * - * @param node - * Node to be constructed - * @return Java instance - */ - protected Object constructObject(Node node) { - if (constructedObjects.containsKey(node)) { - return constructedObjects.get(node); - } - if (recursiveObjects.contains(node)) { - throw new ConstructorException(null, null, "found unconstructable recursive node", - node.getStartMark()); - } - recursiveObjects.add(node); - Construct constructor = getConstructor(node); - Object data = constructor.construct(node); - constructedObjects.put(node, data); - recursiveObjects.remove(node); - if (node.isTwoStepsConstruction()) { - constructor.construct2ndStep(node, data); - } - return data; + } + + /** + * Construct object from the specified Node. Return existing instance if the node is already + * constructed. + * + * @param node Node to be constructed + * @return Java instance + */ + protected Object constructObject(Node node) { + if (constructedObjects.containsKey(node)) { + return constructedObjects.get(node); } + return constructObjectNoCheck(node); + } - /** - * Get the constructor to construct the Node. For implicit tags if the - * runtime class is known a dedicated Construct implementation is used. - * Otherwise the constructor is chosen by the tag. - * - * @param node - * Node to be constructed - * @return Construct implementation for the specified node - */ - protected Construct getConstructor(Node node) { - if (node.useClassConstructor()) { - return yamlClassConstructors.get(node.getNodeId()); - } else { - Construct constructor = yamlConstructors.get(node.getTag()); - if (constructor == null) { - for (String prefix : yamlMultiConstructors.keySet()) { - if (node.getTag().startsWith(prefix)) { - return yamlMultiConstructors.get(prefix); - } - } - return yamlConstructors.get(null); - } - return constructor; + protected Object constructObjectNoCheck(Node node) { + if (recursiveObjects.contains(node)) { + throw new ConstructorException(null, null, "found unconstructable recursive node", + node.getStartMark()); + } + recursiveObjects.add(node); + Construct constructor = getConstructor(node); + Object data = (constructedObjects.containsKey(node)) ? constructedObjects.get(node) + : constructor.construct(node); + + finalizeConstruction(node, data); + constructedObjects.put(node, data); + recursiveObjects.remove(node); + if (node.isTwoStepsConstruction()) { + constructor.construct2ndStep(node, data); + } + return data; + } + + /** + * Get the constructor to construct the Node. For implicit tags if the runtime class is known a + * dedicated Construct implementation is used. Otherwise the constructor is chosen by the tag. + * + * @param node {@link Node} to construct an instance from + * @return {@link Construct} implementation for the specified node + */ + protected Construct getConstructor(Node node) { + if (node.useClassConstructor()) { + return yamlClassConstructors.get(node.getNodeId()); + } else { + Construct constructor = yamlConstructors.get(node.getTag()); + if (constructor == null) { + for (String prefix : yamlMultiConstructors.keySet()) { + if (node.getTag().startsWith(prefix)) { + return yamlMultiConstructors.get(prefix); + } } + return yamlConstructors.get(null); + } + return constructor; } + } - protected Object constructScalar(ScalarNode node) { - return node.getValue(); - } + protected String constructScalar(ScalarNode node) { + return node.getValue(); + } - protected List<Object> createDefaultList(int initSize) { - return new ArrayList<Object>(initSize); - } + // >>>> DEFAULTS >>>> + protected List<Object> createDefaultList(int initSize) { + return new ArrayList<Object>(initSize); + } - protected Set<Object> createDefaultSet(int initSize) { - return new LinkedHashSet<Object>(initSize); - } + protected Set<Object> createDefaultSet(int initSize) { + return new LinkedHashSet<Object>(initSize); + } - protected Object createArray(Class<?> type, int size) { - return Array.newInstance(type.getComponentType(), size); - } + protected Map<Object, Object> createDefaultMap(int initSize) { + // respect order from YAML document + return new LinkedHashMap<Object, Object>(initSize); + } - @SuppressWarnings("unchecked") - protected List<? extends Object> constructSequence(SequenceNode node) { - List<Object> result; - if (List.class.isAssignableFrom(node.getType()) && !node.getType().isInterface()) { - // the root class may be defined (Vector for instance) - try { - result = (List<Object>) node.getType().newInstance(); - } catch (Exception e) { - throw new YAMLException(e); - } - } else { - result = createDefaultList(node.getValue().size()); - } - constructSequenceStep2(node, result); - return result; + protected Object createArray(Class<?> type, int size) { + return Array.newInstance(type.getComponentType(), size); + } - } + // <<<< DEFAULTS <<<< - @SuppressWarnings("unchecked") - protected Set<? extends Object> constructSet(SequenceNode node) { - Set<Object> result; - if (!node.getType().isInterface()) { - // the root class may be defined - try { - result = (Set<Object>) node.getType().newInstance(); - } catch (Exception e) { - throw new YAMLException(e); - } - } else { - result = createDefaultSet(node.getValue().size()); + protected Object finalizeConstruction(Node node, Object data) { + final Class<? extends Object> type = node.getType(); + if (typeDefinitions.containsKey(type)) { + return typeDefinitions.get(type).finalizeConstruction(data); + } + return data; + } + + // >>>> NEW instance + protected Object newInstance(Node node) { + return newInstance(Object.class, node); + } + + protected final Object newInstance(Class<?> ancestor, Node node) { + return newInstance(ancestor, node, true); + } + + /** + * Tries to create a new object for the node. + * + * @param ancestor expected ancestor of the {@code node.getType()} + * @param node for which to create a corresponding java object + * @param tryDefault should default constructor to be tried when there is no corresponding + * {@code TypeDescription} or {@code TypeDescription.newInstance(node)} returns + * {@code null}. + * + * @return - a new object created for {@code node.getType()} by using corresponding + * TypeDescription.newInstance or default constructor. - {@code NOT_INSTANTIATED_OBJECT} + * in case no object has been created + */ + protected Object newInstance(Class<?> ancestor, Node node, boolean tryDefault) { + try { + final Class<? extends Object> type = node.getType(); + if (typeDefinitions.containsKey(type)) { + TypeDescription td = typeDefinitions.get(type); + final Object instance = td.newInstance(node); + if (instance != null) { + return instance; } - constructSequenceStep2(node, result); - return result; - + } + + if (tryDefault) { + /* + * Removed <code> have InstantiationException in case of abstract type + */ + if (ancestor.isAssignableFrom(type) && !Modifier.isAbstract(type.getModifiers())) { + java.lang.reflect.Constructor<?> c = type.getDeclaredConstructor(); + c.setAccessible(true); + return c.newInstance(); + } + } + } catch (Exception e) { + throw new YAMLException(e); } - protected Object constructArray(SequenceNode node) { - return constructArrayStep2(node, createArray(node.getType(), node.getValue().size())); - } + return NOT_INSTANTIATED_OBJECT; + } - protected void constructSequenceStep2(SequenceNode node, Collection<Object> collection) { - for (Node child : node.getValue()) { - collection.add(constructObject(child)); - } + @SuppressWarnings("unchecked") + protected Set<Object> newSet(CollectionNode<?> node) { + Object instance = newInstance(Set.class, node); + if (instance != NOT_INSTANTIATED_OBJECT) { + return (Set<Object>) instance; + } else { + return createDefaultSet(node.getValue().size()); + } + } + + @SuppressWarnings("unchecked") + protected List<Object> newList(SequenceNode node) { + Object instance = newInstance(List.class, node); + if (instance != NOT_INSTANTIATED_OBJECT) { + return (List<Object>) instance; + } else { + return createDefaultList(node.getValue().size()); } + } + + @SuppressWarnings("unchecked") + protected Map<Object, Object> newMap(MappingNode node) { + Object instance = newInstance(Map.class, node); + if (instance != NOT_INSTANTIATED_OBJECT) { + return (Map<Object, Object>) instance; + } else { + return createDefaultMap(node.getValue().size()); + } + } + + // <<<< NEW instance + + // >>>> Construct => NEW, 2ndStep(filling) + protected List<? extends Object> constructSequence(SequenceNode node) { + List<Object> result = newList(node); + constructSequenceStep2(node, result); + return result; + } + + protected Set<? extends Object> constructSet(SequenceNode node) { + Set<Object> result = newSet(node); + constructSequenceStep2(node, result); + return result; + } + + protected Object constructArray(SequenceNode node) { + return constructArrayStep2(node, createArray(node.getType(), node.getValue().size())); + } + + protected void constructSequenceStep2(SequenceNode node, Collection<Object> collection) { + for (Node child : node.getValue()) { + collection.add(constructObject(child)); + } + } - protected Object constructArrayStep2(SequenceNode node, Object array) { - final Class<?> componentType = node.getType().getComponentType(); + protected Object constructArrayStep2(SequenceNode node, Object array) { + final Class<?> componentType = node.getType().getComponentType(); - int index = 0; - for (Node child : node.getValue()) { - // Handle multi-dimensional arrays... - if (child.getType() == Object.class) { - child.setType(componentType); - } + int index = 0; + for (Node child : node.getValue()) { + // Handle multi-dimensional arrays... + if (child.getType() == Object.class) { + child.setType(componentType); + } - final Object value = constructObject(child); + final Object value = constructObject(child); - if (componentType.isPrimitive()) { - // Null values are disallowed for primitives - if (value == null) { - throw new NullPointerException("Unable to construct element value for " + child); - } + if (componentType.isPrimitive()) { + // Null values are disallowed for primitives + if (value == null) { + throw new NullPointerException("Unable to construct element value for " + child); + } - // Primitive arrays require quite a lot of work. - if (byte.class.equals(componentType)) { - Array.setByte(array, index, ((Number) value).byteValue()); + // Primitive arrays require quite a lot of work. + if (byte.class.equals(componentType)) { + Array.setByte(array, index, ((Number) value).byteValue()); - } else if (short.class.equals(componentType)) { - Array.setShort(array, index, ((Number) value).shortValue()); + } else if (short.class.equals(componentType)) { + Array.setShort(array, index, ((Number) value).shortValue()); - } else if (int.class.equals(componentType)) { - Array.setInt(array, index, ((Number) value).intValue()); + } else if (int.class.equals(componentType)) { + Array.setInt(array, index, ((Number) value).intValue()); - } else if (long.class.equals(componentType)) { - Array.setLong(array, index, ((Number) value).longValue()); + } else if (long.class.equals(componentType)) { + Array.setLong(array, index, ((Number) value).longValue()); - } else if (float.class.equals(componentType)) { - Array.setFloat(array, index, ((Number) value).floatValue()); + } else if (float.class.equals(componentType)) { + Array.setFloat(array, index, ((Number) value).floatValue()); - } else if (double.class.equals(componentType)) { - Array.setDouble(array, index, ((Number) value).doubleValue()); + } else if (double.class.equals(componentType)) { + Array.setDouble(array, index, ((Number) value).doubleValue()); - } else if (char.class.equals(componentType)) { - Array.setChar(array, index, ((Character) value).charValue()); + } else if (char.class.equals(componentType)) { + Array.setChar(array, index, ((Character) value).charValue()); - } else if (boolean.class.equals(componentType)) { - Array.setBoolean(array, index, ((Boolean) value).booleanValue()); + } else if (boolean.class.equals(componentType)) { + Array.setBoolean(array, index, ((Boolean) value).booleanValue()); - } else { - throw new YAMLException("unexpected primitive type"); - } + } else { + throw new YAMLException("unexpected primitive type"); + } - } else { - // Non-primitive arrays can simply be assigned: - Array.set(array, index, value); - } + } else { + // Non-primitive arrays can simply be assigned: + Array.set(array, index, value); + } - ++index; + ++index; + } + return array; + } + + protected Set<Object> constructSet(MappingNode node) { + final Set<Object> set = newSet(node); + constructSet2ndStep(node, set); + return set; + } + + protected Map<Object, Object> constructMapping(MappingNode node) { + final Map<Object, Object> mapping = newMap(node); + constructMapping2ndStep(node, mapping); + return mapping; + } + + protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) { + List<NodeTuple> nodeValue = node.getValue(); + for (NodeTuple tuple : nodeValue) { + Node keyNode = tuple.getKeyNode(); + Node valueNode = tuple.getValueNode(); + Object key = constructObject(keyNode); + if (key != null) { + try { + key.hashCode();// check circular dependencies + } catch (Exception e) { + throw new ConstructorException("while constructing a mapping", node.getStartMark(), + "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e); } - return array; + } + Object value = constructObject(valueNode); + if (keyNode.isTwoStepsConstruction()) { + if (loadingConfig.getAllowRecursiveKeys()) { + postponeMapFilling(mapping, key, value); + } else { + throw new YAMLException( + "Recursive key for mapping is detected but it is not configured to be allowed."); + } + } else { + mapping.put(key, value); + } } - - protected Map<Object, Object> createDefaultMap() { - // respect order from YAML document - return new LinkedHashMap<Object, Object>(); + } + + /* + * if keyObject is created it 2 steps we should postpone putting it in map because it may have + * different hash after initialization compared to clean just created one. And map of course does + * not observe key hashCode changes. + */ + protected void postponeMapFilling(Map<Object, Object> mapping, Object key, Object value) { + maps2fill.add(0, new RecursiveTuple(mapping, new RecursiveTuple(key, value))); + } + + protected void constructSet2ndStep(MappingNode node, Set<Object> set) { + List<NodeTuple> nodeValue = node.getValue(); + for (NodeTuple tuple : nodeValue) { + Node keyNode = tuple.getKeyNode(); + Object key = constructObject(keyNode); + if (key != null) { + try { + key.hashCode();// check circular dependencies + } catch (Exception e) { + throw new ConstructorException("while constructing a Set", node.getStartMark(), + "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e); + } + } + if (keyNode.isTwoStepsConstruction()) { + postponeSetFilling(set, key); + } else { + set.add(key); + } } - - protected Set<Object> createDefaultSet() { - // respect order from YAML document - return new LinkedHashSet<Object>(); + } + + /* + * if keyObject is created it 2 steps we should postpone putting it into the set because it may + * have different hash after initialization compared to clean just created one. And set of course + * does not observe value hashCode changes. + */ + protected void postponeSetFilling(Set<Object> set, Object key) { + sets2fill.add(0, new RecursiveTuple<Set<Object>, Object>(set, key)); + } + + public void setPropertyUtils(PropertyUtils propertyUtils) { + this.propertyUtils = propertyUtils; + explicitPropertyUtils = true; + Collection<TypeDescription> tds = typeDefinitions.values(); + for (TypeDescription typeDescription : tds) { + typeDescription.setPropertyUtils(propertyUtils); } + } - protected Set<Object> constructSet(MappingNode node) { - Set<Object> set = createDefaultSet(); - constructSet2ndStep(node, set); - return set; + public final PropertyUtils getPropertyUtils() { + if (propertyUtils == null) { + propertyUtils = new PropertyUtils(); } - - protected Map<Object, Object> constructMapping(MappingNode node) { - Map<Object, Object> mapping = createDefaultMap(); - constructMapping2ndStep(node, mapping); - return mapping; + return propertyUtils; + } + + /** + * Make YAML aware how to parse a custom Class. If there is no root Class assigned in constructor + * then the 'root' property of this definition is respected. + * + * @param definition to be added to the Constructor + * @return the previous value associated with <code>definition</code>, or <code>null</code> if + * there was no mapping for <code>definition</code>. + */ + public TypeDescription addTypeDescription(TypeDescription definition) { + if (definition == null) { + throw new NullPointerException("TypeDescription is required."); } + Tag tag = definition.getTag(); + typeTags.put(tag, definition.getType()); + definition.setPropertyUtils(getPropertyUtils()); + return typeDefinitions.put(definition.getType(), definition); + } - protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) { - List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue(); - for (NodeTuple tuple : nodeValue) { - Node keyNode = tuple.getKeyNode(); - Node valueNode = tuple.getValueNode(); - Object key = constructObject(keyNode); - if (key != null) { - try { - key.hashCode();// check circular dependencies - } catch (Exception e) { - throw new ConstructorException("while constructing a mapping", - node.getStartMark(), "found unacceptable key " + key, tuple - .getKeyNode().getStartMark(), e); - } - } - Object value = constructObject(valueNode); - if (keyNode.isTwoStepsConstruction()) { - /* - * if keyObject is created it 2 steps we should postpone putting - * it in map because it may have different hash after - * initialization compared to clean just created one. And map of - * course does not observe key hashCode changes. - */ - maps2fill.add(0, - new RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>( - mapping, new RecursiveTuple<Object, Object>(key, value))); - } else { - mapping.put(key, value); - } - } - } + private static class RecursiveTuple<T, K> { - protected void constructSet2ndStep(MappingNode node, Set<Object> set) { - List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue(); - for (NodeTuple tuple : nodeValue) { - Node keyNode = tuple.getKeyNode(); - Object key = constructObject(keyNode); - if (key != null) { - try { - key.hashCode();// check circular dependencies - } catch (Exception e) { - throw new ConstructorException("while constructing a Set", node.getStartMark(), - "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e); - } - } - if (keyNode.isTwoStepsConstruction()) { - /* - * if keyObject is created it 2 steps we should postpone putting - * it into the set because it may have different hash after - * initialization compared to clean just created one. And set of - * course does not observe value hashCode changes. - */ - sets2fill.add(0, new RecursiveTuple<Set<Object>, Object>(set, key)); - } else { - set.add(key); - } - } + private final T _1; + private final K _2; + + public RecursiveTuple(T _1, K _2) { + this._1 = _1; + this._2 = _2; } - public void setPropertyUtils(PropertyUtils propertyUtils) { - this.propertyUtils = propertyUtils; - explicitPropertyUtils = true; + public K _2() { + return _2; } - public final PropertyUtils getPropertyUtils() { - if (propertyUtils == null) { - propertyUtils = new PropertyUtils(); - } - return propertyUtils; + public T _1() { + return _1; } + } - private static class RecursiveTuple<T, K> { - private final T _1; - private final K _2; + public final boolean isExplicitPropertyUtils() { + return explicitPropertyUtils; + } - public RecursiveTuple(T _1, K _2) { - this._1 = _1; - this._2 = _2; - } + public boolean isAllowDuplicateKeys() { + return allowDuplicateKeys; + } - public K _2() { - return _2; - } + public void setAllowDuplicateKeys(boolean allowDuplicateKeys) { + this.allowDuplicateKeys = allowDuplicateKeys; + } - public T _1() { - return _1; - } - } + public boolean isWrappedToRootException() { + return wrappedToRootException; + } - public final boolean isExplicitPropertyUtils() { - return explicitPropertyUtils; - } + public void setWrappedToRootException(boolean wrappedToRootException) { + this.wrappedToRootException = wrappedToRootException; + } + + public boolean isEnumCaseSensitive() { + return enumCaseSensitive; + } + + public void setEnumCaseSensitive(boolean enumCaseSensitive) { + this.enumCaseSensitive = enumCaseSensitive; + } } diff --git a/src/main/java/org/yaml/snakeyaml/constructor/Construct.java b/src/main/java/org/yaml/snakeyaml/constructor/Construct.java index 4fa91186..81ef4446 100644 --- a/src/main/java/org/yaml/snakeyaml/constructor/Construct.java +++ b/src/main/java/org/yaml/snakeyaml/constructor/Construct.java @@ -1,50 +1,43 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import org.yaml.snakeyaml.nodes.Node; /** - * Provide a way to construct a Java instance out of the composed Node. Support - * recursive objects if it is required. (create Native Data Structure out of - * Node Graph) - * - * @see <a href="http://yaml.org/spec/1.1/#id859109">Chapter 3. Processing YAML - * Information</a> + * Provide a way to construct a Java instance out of the composed Node. Support recursive objects if + * it is required. (create Native Data Structure out of Node Graph) + * + * @see <a href="http://yaml.org/spec/1.1/#id859109">Chapter 3. Processing YAML Information</a> */ public interface Construct { - /** - * Construct a Java instance with all the properties injected when it is - * possible. - * - * @param node - * composed Node - * @return a complete Java instance - */ - Object construct(Node node); - /** - * Apply the second step when constructing recursive structures. Because the - * instance is already created it can assign a reference to itself. - * - * @param node - * composed Node - * @param object - * the instance constructed earlier by - * <code>construct(Node node)</code> for the provided Node - */ - void construct2ndStep(Node node, Object object); + /** + * Construct a Java instance with all the properties injected when it is possible. + * + * @param node composed Node + * @return a complete Java instance + */ + Object construct(Node node); + + /** + * Apply the second step when constructing recursive structures. Because the instance is already + * created it can assign a reference to itself. + * + * @param node composed Node + * @param object the instance constructed earlier by <code>construct(Node node)</code> for the + * provided Node + */ + void construct2ndStep(Node node, Object object); } diff --git a/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java b/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java index 943702f2..52dd5da8 100644 --- a/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java +++ b/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java @@ -1,38 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; -import java.beans.IntrospectionException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; import java.util.UUID; - +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.introspector.Property; @@ -43,640 +34,635 @@ import org.yaml.snakeyaml.nodes.NodeTuple; import org.yaml.snakeyaml.nodes.ScalarNode; import org.yaml.snakeyaml.nodes.SequenceNode; import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.util.EnumUtils; /** * Construct a custom Java instance. */ public class Constructor extends SafeConstructor { - private final Map<Tag, Class<? extends Object>> typeTags; - protected final Map<Class<? extends Object>, TypeDescription> typeDefinitions; - public Constructor() { - this(Object.class); + public Constructor() { + this(Object.class); + } + + public Constructor(LoaderOptions loadingConfig) { + this(Object.class, loadingConfig); + } + + /** + * Create Constructor for the specified class as the root. + * + * @param theRoot - the class (usually JavaBean) to be constructed + */ + public Constructor(Class<? extends Object> theRoot) { + this(new TypeDescription(checkRoot(theRoot))); + } + + public Constructor(Class<? extends Object> theRoot, LoaderOptions loadingConfig) { + this(new TypeDescription(checkRoot(theRoot)), loadingConfig); + } + + /** + * Ugly Java way to check the argument in the constructor + */ + private static Class<? extends Object> checkRoot(Class<? extends Object> theRoot) { + if (theRoot == null) { + throw new NullPointerException("Root class must be provided."); + } else { + return theRoot; } - - /** - * Create Constructor for the specified class as the root. - * - * @param theRoot - * - the class (usually JavaBean) to be constructed - */ - public Constructor(Class<? extends Object> theRoot) { - this(new TypeDescription(checkRoot(theRoot))); + } + + public Constructor(TypeDescription theRoot) { + this(theRoot, null, new LoaderOptions()); + } + + public Constructor(TypeDescription theRoot, LoaderOptions loadingConfig) { + this(theRoot, null, loadingConfig); + } + + public Constructor(TypeDescription theRoot, Collection<TypeDescription> moreTDs) { + this(theRoot, moreTDs, new LoaderOptions()); + } + + /** + * Create with all possible arguments + * + * @param theRoot - the class (usually JavaBean) to be constructed + * @param moreTDs - collection of classes used by the root class + * @param loadingConfig - configuration + */ + public Constructor(TypeDescription theRoot, Collection<TypeDescription> moreTDs, + LoaderOptions loadingConfig) { + super(loadingConfig); + if (theRoot == null) { + throw new NullPointerException("Root type must be provided."); } - - /** - * Ugly Java way to check the argument in the constructor - */ - private static Class<? extends Object> checkRoot(Class<? extends Object> theRoot) { - if (theRoot == null) { - throw new NullPointerException("Root class must be provided."); - } else - return theRoot; + this.yamlConstructors.put(null, new ConstructYamlObject()); + if (!Object.class.equals(theRoot.getType())) { + rootTag = new Tag(theRoot.getType()); } - - public Constructor(TypeDescription theRoot) { - if (theRoot == null) { - throw new NullPointerException("Root type must be provided."); - } - this.yamlConstructors.put(null, new ConstructYamlObject()); - if (!Object.class.equals(theRoot.getType())) { - rootTag = new Tag(theRoot.getType()); - } - typeTags = new HashMap<Tag, Class<? extends Object>>(); - typeDefinitions = new HashMap<Class<? extends Object>, TypeDescription>(); - yamlClassConstructors.put(NodeId.scalar, new ConstructScalar()); - yamlClassConstructors.put(NodeId.mapping, new ConstructMapping()); - yamlClassConstructors.put(NodeId.sequence, new ConstructSequence()); - addTypeDescription(theRoot); + yamlClassConstructors.put(NodeId.scalar, new ConstructScalar()); + yamlClassConstructors.put(NodeId.mapping, new ConstructMapping()); + yamlClassConstructors.put(NodeId.sequence, new ConstructSequence()); + addTypeDescription(theRoot); + if (moreTDs != null) { + for (TypeDescription td : moreTDs) { + addTypeDescription(td); + } } + } + + /** + * Create Constructor for a class which does not have to be in the classpath or for a definition + * from a Spring ApplicationContext. + * + * @param theRoot fully qualified class name of the root class (usually JavaBean) + * @throws ClassNotFoundException if cannot be loaded by the classloader + */ + public Constructor(String theRoot) throws ClassNotFoundException { + this(Class.forName(check(theRoot))); + } + + public Constructor(String theRoot, LoaderOptions loadingConfig) throws ClassNotFoundException { + this(Class.forName(check(theRoot)), loadingConfig); + } + + private static final String check(String s) { + if (s == null) { + throw new NullPointerException("Root type must be provided."); + } + if (s.trim().length() == 0) { + throw new YAMLException("Root type must be provided."); + } + return s; + } + + /** + * Construct mapping instance (Map, JavaBean) when the runtime class is known. + */ + protected class ConstructMapping implements Construct { /** - * Create Constructor for a class which does not have to be in the classpath - * or for a definition from a Spring ApplicationContext. - * - * @param theRoot - * fully qualified class name of the root class (usually - * JavaBean) - * @throws ClassNotFoundException + * Construct JavaBean. If type safe collections are used please look at + * <code>TypeDescription</code>. + * + * @param node node where the keys are property names (they can only be <code>String</code>s) + * and values are objects to be created + * @return constructed JavaBean */ - public Constructor(String theRoot) throws ClassNotFoundException { - this(Class.forName(check(theRoot))); - } - - private static final String check(String s) { - if (s == null) { - throw new NullPointerException("Root type must be provided."); + public Object construct(Node node) { + MappingNode mnode = (MappingNode) node; + if (Map.class.isAssignableFrom(node.getType())) { + if (node.isTwoStepsConstruction()) { + return newMap(mnode); + } else { + return constructMapping(mnode); } - if (s.trim().length() == 0) { - throw new YAMLException("Root type must be provided."); + } else if (Collection.class.isAssignableFrom(node.getType())) { + if (node.isTwoStepsConstruction()) { + return newSet(mnode); + } else { + return constructSet(mnode); } - return s; + } else { + Object obj = Constructor.this.newInstance(mnode); + if (obj != NOT_INSTANTIATED_OBJECT) { + if (node.isTwoStepsConstruction()) { + return obj; + } else { + return constructJavaBean2ndStep(mnode, obj); + } + } else { + throw new ConstructorException(null, null, + "Can't create an instance for " + mnode.getTag(), node.getStartMark()); + } + } } - /** - * Make YAML aware how to parse a custom Class. If there is no root Class - * assigned in constructor then the 'root' property of this definition is - * respected. - * - * @param definition - * to be added to the Constructor - * @return the previous value associated with <tt>definition</tt>, or - * <tt>null</tt> if there was no mapping for <tt>definition</tt>. - */ - public TypeDescription addTypeDescription(TypeDescription definition) { - if (definition == null) { - throw new NullPointerException("TypeDescription is required."); - } - Tag tag = definition.getTag(); - typeTags.put(tag, definition.getType()); - return typeDefinitions.put(definition.getType(), definition); + @SuppressWarnings("unchecked") + public void construct2ndStep(Node node, Object object) { + if (Map.class.isAssignableFrom(node.getType())) { + constructMapping2ndStep((MappingNode) node, (Map<Object, Object>) object); + } else if (Set.class.isAssignableFrom(node.getType())) { + constructSet2ndStep((MappingNode) node, (Set<Object>) object); + } else { + constructJavaBean2ndStep((MappingNode) node, object); + } } - /** - * Construct mapping instance (Map, JavaBean) when the runtime class is - * known. - */ - protected class ConstructMapping implements Construct { - - /** - * Construct JavaBean. If type safe collections are used please look at - * <code>TypeDescription</code>. - * - * @param node - * node where the keys are property names (they can only be - * <code>String</code>s) and values are objects to be created - * @return constructed JavaBean - */ - public Object construct(Node node) { - MappingNode mnode = (MappingNode) node; - if (Properties.class.isAssignableFrom(node.getType())) { - Properties properties = new Properties(); - if (!node.isTwoStepsConstruction()) { - constructMapping2ndStep(mnode, properties); - } else { - throw new YAMLException("Properties must not be recursive."); - } - return properties; - } else if (SortedMap.class.isAssignableFrom(node.getType())) { - SortedMap<Object, Object> map = new TreeMap<Object, Object>(); - if (!node.isTwoStepsConstruction()) { - constructMapping2ndStep(mnode, map); - } - return map; - } else if (Map.class.isAssignableFrom(node.getType())) { - if (node.isTwoStepsConstruction()) { - return createDefaultMap(); - } else { - return constructMapping(mnode); - } - } else if (SortedSet.class.isAssignableFrom(node.getType())) { - SortedSet<Object> set = new TreeSet<Object>(); - // XXX why this is not used ? - // if (!node.isTwoStepsConstruction()) { - constructSet2ndStep(mnode, set); - // } - return set; - } else if (Collection.class.isAssignableFrom(node.getType())) { - if (node.isTwoStepsConstruction()) { - return createDefaultSet(); - } else { - return constructSet(mnode); - } - } else { - if (node.isTwoStepsConstruction()) { - return createEmptyJavaBean(mnode); - } else { - return constructJavaBean2ndStep(mnode, createEmptyJavaBean(mnode)); - } + // protected Object createEmptyJavaBean(MappingNode node) { + // try { + // Object instance = Constructor.this.newInstance(node); + // if (instance != null) { + // return instance; + // } + // + // /** + // * Using only default constructor. Everything else will be + // * initialized on 2nd step. If we do here some partial + // * initialization, how do we then track what need to be done on + // * 2nd step? I think it is better to get only object here (to + // * have it as reference for recursion) and do all other thing on + // * 2nd step. + // */ + // java.lang.reflect.Constructor<?> c = + // node.getType().getDeclaredConstructor(); + // c.setAccessible(true); + // return c.newInstance(); + // } catch (Exception e) { + // throw new YAMLException(e); + // } + // } + + protected Object constructJavaBean2ndStep(MappingNode node, Object object) { + flattenMapping(node, true); + Class<? extends Object> beanType = node.getType(); + List<NodeTuple> nodeValue = node.getValue(); + for (NodeTuple tuple : nodeValue) { + Node valueNode = tuple.getValueNode(); + // flattenMapping enforces keys to be Strings + String key = (String) constructObject(tuple.getKeyNode()); + try { + TypeDescription memberDescription = typeDefinitions.get(beanType); + Property property = memberDescription == null ? getProperty(beanType, key) + : memberDescription.getProperty(key); + + if (!property.isWritable()) { + throw new YAMLException( + "No writable property '" + key + "' on class: " + beanType.getName()); + } + + valueNode.setType(property.getType()); + final boolean typeDetected = + memberDescription != null && memberDescription.setupPropertyType(key, valueNode); + if (!typeDetected && valueNode.getNodeId() != NodeId.scalar) { + // only if there is no explicit TypeDescription + Class<?>[] arguments = property.getActualTypeArguments(); + if (arguments != null && arguments.length > 0) { + // type safe (generic) collection may contain the + // proper class + if (valueNode.getNodeId() == NodeId.sequence) { + Class<?> t = arguments[0]; + SequenceNode snode = (SequenceNode) valueNode; + snode.setListType(t); + } else if (Map.class.isAssignableFrom(valueNode.getType())) { + Class<?> keyType = arguments[0]; + Class<?> valueType = arguments[1]; + MappingNode mnode = (MappingNode) valueNode; + mnode.setTypes(keyType, valueType); + mnode.setUseClassConstructor(true); + } else if (Collection.class.isAssignableFrom(valueNode.getType())) { + Class<?> t = arguments[0]; + MappingNode mnode = (MappingNode) valueNode; + mnode.setOnlyKeyType(t); + mnode.setUseClassConstructor(true); + } } - } - - @SuppressWarnings("unchecked") - public void construct2ndStep(Node node, Object object) { - if (Map.class.isAssignableFrom(node.getType())) { - constructMapping2ndStep((MappingNode) node, (Map<Object, Object>) object); - } else if (Set.class.isAssignableFrom(node.getType())) { - constructSet2ndStep((MappingNode) node, (Set<Object>) object); - } else { - constructJavaBean2ndStep((MappingNode) node, object); + } + + Object value = + (memberDescription != null) ? newInstance(memberDescription, key, valueNode) + : constructObject(valueNode); + // Correct when the property expects float but double was + // constructed + if (property.getType() == Float.TYPE || property.getType() == Float.class) { + if (value instanceof Double) { + value = ((Double) value).floatValue(); } + } + // Correct when the property a String but the value is binary + if (property.getType() == String.class && Tag.BINARY.equals(valueNode.getTag()) + && value instanceof byte[]) { + value = new String((byte[]) value); + } + + if (memberDescription == null || !memberDescription.setProperty(object, key, value)) { + property.set(object, value); + } + } catch (DuplicateKeyException e) { + throw e; + } catch (Exception e) { + throw new ConstructorException( + "Cannot create property=" + key + " for JavaBean=" + object, node.getStartMark(), + e.getMessage(), valueNode.getStartMark(), e); } + } + return object; + } - protected Object createEmptyJavaBean(MappingNode node) { - try { - /** - * Using only default constructor. Everything else will be - * initialized on 2nd step. If we do here some partial - * initialization, how do we then track what need to be done on - * 2nd step? I think it is better to get only object here (to - * have it as reference for recursion) and do all other thing on - * 2nd step. - */ - java.lang.reflect.Constructor<?> c = node.getType().getDeclaredConstructor(); - c.setAccessible(true); - return c.newInstance(); - } catch (Exception e) { - throw new YAMLException(e); - } - } + private Object newInstance(TypeDescription memberDescription, String propertyName, Node node) { + Object newInstance = memberDescription.newInstance(propertyName, node); + if (newInstance != null) { + constructedObjects.put(node, newInstance); + return constructObjectNoCheck(node); + } + return constructObject(node); + } - protected Object constructJavaBean2ndStep(MappingNode node, Object object) { - flattenMapping(node); - Class<? extends Object> beanType = node.getType(); - List<NodeTuple> nodeValue = node.getValue(); - for (NodeTuple tuple : nodeValue) { - ScalarNode keyNode; - if (tuple.getKeyNode() instanceof ScalarNode) { - // key must be scalar - keyNode = (ScalarNode) tuple.getKeyNode(); - } else { - throw new YAMLException("Keys must be scalars but found: " + tuple.getKeyNode()); - } - Node valueNode = tuple.getValueNode(); - // keys can only be Strings - keyNode.setType(String.class); - String key = (String) constructObject(keyNode); - try { - Property property = getProperty(beanType, key); - valueNode.setType(property.getType()); - TypeDescription memberDescription = typeDefinitions.get(beanType); - boolean typeDetected = false; - if (memberDescription != null) { - switch (valueNode.getNodeId()) { - case sequence: - SequenceNode snode = (SequenceNode) valueNode; - Class<? extends Object> memberType = memberDescription - .getListPropertyType(key); - if (memberType != null) { - snode.setListType(memberType); - typeDetected = true; - } else if (property.getType().isArray()) { - snode.setListType(property.getType().getComponentType()); - typeDetected = true; - } - break; - case mapping: - MappingNode mnode = (MappingNode) valueNode; - Class<? extends Object> keyType = memberDescription.getMapKeyType(key); - if (keyType != null) { - mnode.setTypes(keyType, memberDescription.getMapValueType(key)); - typeDetected = true; - } - break; - default: // scalar - } - } - if (!typeDetected && valueNode.getNodeId() != NodeId.scalar) { - // only if there is no explicit TypeDescription - Class<?>[] arguments = property.getActualTypeArguments(); - if (arguments != null && arguments.length > 0) { - // type safe (generic) collection may contain the - // proper class - if (valueNode.getNodeId() == NodeId.sequence) { - Class<?> t = arguments[0]; - SequenceNode snode = (SequenceNode) valueNode; - snode.setListType(t); - } else if (valueNode.getTag().equals(Tag.SET)) { - Class<?> t = arguments[0]; - MappingNode mnode = (MappingNode) valueNode; - mnode.setOnlyKeyType(t); - mnode.setUseClassConstructor(true); - } else if (property.getType().isAssignableFrom(Map.class)) { - Class<?> ketType = arguments[0]; - Class<?> valueType = arguments[1]; - MappingNode mnode = (MappingNode) valueNode; - mnode.setTypes(ketType, valueType); - mnode.setUseClassConstructor(true); - } else { - // the type for collection entries cannot be - // detected - } - } - } - - Object value = constructObject(valueNode); - // Correct when the property expects float but double was - // constructed - if (property.getType() == Float.TYPE || property.getType() == Float.class) { - if (value instanceof Double) { - value = ((Double) value).floatValue(); - } - } - // Correct when the property a String but the value is binary - if (property.getType() == String.class && Tag.BINARY.equals(valueNode.getTag()) && value instanceof byte[]) { - value = new String((byte[])value); - } - - property.set(object, value); - } catch (Exception e) { - throw new ConstructorException("Cannot create property=" + key - + " for JavaBean=" + object, node.getStartMark(), e.getMessage(), - valueNode.getStartMark(), e); - } - } - return object; - } + protected Property getProperty(Class<? extends Object> type, String name) { + return getPropertyUtils().getProperty(type, name); + } + } + + /** + * Construct an instance when the runtime class is not known but a global tag with a class name is + * defined. It delegates the construction to the appropriate constructor based on the node kind + * (scalar, sequence, mapping) + */ + protected class ConstructYamlObject implements Construct { + + private Construct getConstructor(Node node) { + Class<?> cl = getClassForNode(node); + node.setType(cl); + // call the constructor as if the runtime class is defined + Construct constructor = yamlClassConstructors.get(node.getNodeId()); + return constructor; + } - protected Property getProperty(Class<? extends Object> type, String name) - throws IntrospectionException { - return getPropertyUtils().getProperty(type, name); - } + public Object construct(Node node) { + try { + return getConstructor(node).construct(node); + } catch (ConstructorException e) { + throw e; + } catch (Exception e) { + throw new ConstructorException(null, null, + "Can't construct a java object for " + node.getTag() + "; exception=" + e.getMessage(), + node.getStartMark(), e); + } } - /** - * Construct an instance when the runtime class is not known but a global - * tag with a class name is defined. It delegates the construction to the - * appropriate constructor based on the node kind (scalar, sequence, - * mapping) - */ - protected class ConstructYamlObject implements Construct { - - private Construct getConstructor(Node node) { - Class<?> cl = getClassForNode(node); - node.setType(cl); - // call the constructor as if the runtime class is defined - Construct constructor = yamlClassConstructors.get(node.getNodeId()); - return constructor; + public void construct2ndStep(Node node, Object object) { + try { + getConstructor(node).construct2ndStep(node, object); + } catch (Exception e) { + throw new ConstructorException(null, null, + "Can't construct a second step for a java object for " + node.getTag() + "; exception=" + + e.getMessage(), + node.getStartMark(), e); + } + } + } + + /** + * Construct scalar instance when the runtime class is known. Recursive structures are not + * supported. + */ + protected class ConstructScalar extends AbstractConstruct { + + public Object construct(Node nnode) { + ScalarNode node = (ScalarNode) nnode; + Class<?> type = node.getType(); + + // In case there is TypeDefinition for the 'type' + Object instance = newInstance(type, node, false); + if (instance != NOT_INSTANTIATED_OBJECT) { + return instance; + } + + Object result; + if (type.isPrimitive() || type == String.class || Number.class.isAssignableFrom(type) + || type == Boolean.class || Date.class.isAssignableFrom(type) || type == Character.class + || type == BigInteger.class || type == BigDecimal.class + || Enum.class.isAssignableFrom(type) || Tag.BINARY.equals(node.getTag()) + || Calendar.class.isAssignableFrom(type) || type == UUID.class) { + // standard classes created directly + result = constructStandardJavaInstance(type, node); + } else { + // there must be only 1 constructor with 1 argument + java.lang.reflect.Constructor<?>[] javaConstructors = type.getDeclaredConstructors(); + int oneArgCount = 0; + java.lang.reflect.Constructor<?> javaConstructor = null; + for (java.lang.reflect.Constructor<?> c : javaConstructors) { + if (c.getParameterTypes().length == 1) { + oneArgCount++; + javaConstructor = c; + } } - - public Object construct(Node node) { - Object result = null; - try { - result = getConstructor(node).construct(node); - } catch (ConstructorException e) { - throw e; - } catch (Exception e) { - throw new ConstructorException(null, null, "Can't construct a java object for " - + node.getTag() + "; exception=" + e.getMessage(), node.getStartMark(), e); - } - return result; + Object argument; + if (javaConstructor == null) { + throw new YAMLException("No single argument constructor found for " + type); + } else if (oneArgCount == 1) { + argument = constructStandardJavaInstance(javaConstructor.getParameterTypes()[0], node); + } else { + // TODO it should be possible to use implicit types instead + // of forcing String. Resolver must be available here to + // obtain the implicit tag. Then we can set the tag and call + // callConstructor(node) to create the argument instance. + // On the other hand it may be safer to require a custom + // constructor to avoid guessing the argument class + argument = constructScalar(node); + try { + javaConstructor = type.getDeclaredConstructor(String.class); + } catch (Exception e) { + throw new YAMLException("Can't construct a java object for scalar " + node.getTag() + + "; No String constructor found. Exception=" + e.getMessage(), e); + } } - - public void construct2ndStep(Node node, Object object) { - try { - getConstructor(node).construct2ndStep(node, object); - } catch (Exception e) { - throw new ConstructorException(null, null, - "Can't construct a second step for a java object for " + node.getTag() - + "; exception=" + e.getMessage(), node.getStartMark(), e); - } + try { + javaConstructor.setAccessible(true); + result = javaConstructor.newInstance(argument); + } catch (Exception e) { + throw new ConstructorException(null, null, "Can't construct a java object for scalar " + + node.getTag() + "; exception=" + e.getMessage(), node.getStartMark(), e); } + } + return result; } - /** - * Construct scalar instance when the runtime class is known. Recursive - * structures are not supported. - */ - protected class ConstructScalar extends AbstractConstruct { - public Object construct(Node nnode) { - ScalarNode node = (ScalarNode) nnode; - Class<?> type = node.getType(); - Object result; - if (type.isPrimitive() || type == String.class || Number.class.isAssignableFrom(type) - || type == Boolean.class || Date.class.isAssignableFrom(type) - || type == Character.class || type == BigInteger.class - || type == BigDecimal.class || Enum.class.isAssignableFrom(type) - || Tag.BINARY.equals(node.getTag()) || Calendar.class.isAssignableFrom(type) || type == UUID.class) { - // standard classes created directly - result = constructStandardJavaInstance(type, node); - } else { - // there must be only 1 constructor with 1 argument - java.lang.reflect.Constructor<?>[] javaConstructors = type - .getDeclaredConstructors(); - int oneArgCount = 0; - java.lang.reflect.Constructor<?> javaConstructor = null; - for (java.lang.reflect.Constructor<?> c : javaConstructors) { - if (c.getParameterTypes().length == 1) { - oneArgCount++; - javaConstructor = c; - } - } - Object argument; - if (javaConstructor == null) { - throw new YAMLException("No single argument constructor found for " + type); - } else if (oneArgCount == 1) { - argument = constructStandardJavaInstance( - javaConstructor.getParameterTypes()[0], node); - } else { - // TODO it should be possible to use implicit types instead - // of forcing String. Resolver must be available here to - // obtain the implicit tag. Then we can set the tag and call - // callConstructor(node) to create the argument instance. - // On the other hand it may be safer to require a custom - // constructor to avoid guessing the argument class - argument = constructScalar(node); - try { - javaConstructor = type.getDeclaredConstructor(String.class); - } catch (Exception e) { - throw new YAMLException("Can't construct a java object for scalar " - + node.getTag() + "; No String constructor found. Exception=" - + e.getMessage(), e); - } - } - try { - javaConstructor.setAccessible(true); - result = javaConstructor.newInstance(argument); - } catch (Exception e) { - throw new ConstructorException(null, null, - "Can't construct a java object for scalar " + node.getTag() - + "; exception=" + e.getMessage(), node.getStartMark(), e); - } - } - return result; + @SuppressWarnings("unchecked") + private Object constructStandardJavaInstance(@SuppressWarnings("rawtypes") Class type, + ScalarNode node) { + Object result; + if (type == String.class) { + Construct stringConstructor = yamlConstructors.get(Tag.STR); + result = stringConstructor.construct(node); + } else if (type == Boolean.class || type == Boolean.TYPE) { + Construct boolConstructor = yamlConstructors.get(Tag.BOOL); + result = boolConstructor.construct(node); + } else if (type == Character.class || type == Character.TYPE) { + Construct charConstructor = yamlConstructors.get(Tag.STR); + String ch = (String) charConstructor.construct(node); + if (ch.length() == 0) { + result = null; + } else if (ch.length() != 1) { + throw new YAMLException("Invalid node Character: '" + ch + "'; length: " + ch.length()); + } else { + result = Character.valueOf(ch.charAt(0)); } - - @SuppressWarnings("unchecked") - private Object constructStandardJavaInstance(@SuppressWarnings("rawtypes") - Class type, ScalarNode node) { - Object result; - if (type == String.class) { - Construct stringConstructor = yamlConstructors.get(Tag.STR); - result = stringConstructor.construct(node); - } else if (type == Boolean.class || type == Boolean.TYPE) { - Construct boolConstructor = yamlConstructors.get(Tag.BOOL); - result = boolConstructor.construct(node); - } else if (type == Character.class || type == Character.TYPE) { - Construct charConstructor = yamlConstructors.get(Tag.STR); - String ch = (String) charConstructor.construct(node); - if (ch.length() == 0) { - result = null; - } else if (ch.length() != 1) { - throw new YAMLException("Invalid node Character: '" + ch + "'; length: " - + ch.length()); - } else { - result = Character.valueOf(ch.charAt(0)); - } - } else if (Date.class.isAssignableFrom(type)) { - Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP); - Date date = (Date) dateConstructor.construct(node); - if (type == Date.class) { - result = date; - } else { - try { - java.lang.reflect.Constructor<?> constr = type.getConstructor(long.class); - result = constr.newInstance(date.getTime()); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new YAMLException("Cannot construct: '" + type + "'"); - } - } - } else if (type == Float.class || type == Double.class || type == Float.TYPE - || type == Double.TYPE || type == BigDecimal.class) { - if (type == BigDecimal.class) { - result = new BigDecimal(node.getValue()); - } else { - Construct doubleConstructor = yamlConstructors.get(Tag.FLOAT); - result = doubleConstructor.construct(node); - if (type == Float.class || type == Float.TYPE) { - result = new Float((Double) result); - } - } - } else if (type == Byte.class || type == Short.class || type == Integer.class - || type == Long.class || type == BigInteger.class || type == Byte.TYPE - || type == Short.TYPE || type == Integer.TYPE || type == Long.TYPE) { - Construct intConstructor = yamlConstructors.get(Tag.INT); - result = intConstructor.construct(node); - if (type == Byte.class || type == Byte.TYPE) { - result = Byte.valueOf(result.toString()); - } else if (type == Short.class || type == Short.TYPE) { - result = Short.valueOf(result.toString()); - } else if (type == Integer.class || type == Integer.TYPE) { - result = Integer.parseInt(result.toString()); - } else if (type == Long.class || type == Long.TYPE) { - result = Long.valueOf(result.toString()); - } else { - // only BigInteger left - result = new BigInteger(result.toString()); - } - } else if (Enum.class.isAssignableFrom(type)) { - String enumValueName = node.getValue(); - try { - result = Enum.valueOf(type, enumValueName); - } catch (Exception ex) { - throw new YAMLException("Unable to find enum value '" + enumValueName - + "' for enum class: " + type.getName()); - } - } else if (Calendar.class.isAssignableFrom(type)) { - ConstructYamlTimestamp contr = new ConstructYamlTimestamp(); - contr.construct(node); - result = contr.getCalendar(); - } else if (Number.class.isAssignableFrom(type)) { - ConstructYamlNumber contr = new ConstructYamlNumber(); - result = contr.construct(node); - } else if (UUID.class == type) { - result = UUID.fromString(node.getValue()); - } else { - if (yamlConstructors.containsKey(node.getTag())) { - result = yamlConstructors.get(node.getTag()).construct(node); - } else { - throw new YAMLException("Unsupported class: " + type); - } - } - return result; + } else if (Date.class.isAssignableFrom(type)) { + Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP); + Date date = (Date) dateConstructor.construct(node); + if (type == Date.class) { + result = date; + } else { + try { + java.lang.reflect.Constructor<?> constr = type.getConstructor(long.class); + result = constr.newInstance(date.getTime()); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new YAMLException("Cannot construct: '" + type + "'"); + } + } + } else if (type == Float.class || type == Double.class || type == Float.TYPE + || type == Double.TYPE || type == BigDecimal.class) { + if (type == BigDecimal.class) { + result = new BigDecimal(node.getValue()); + } else { + Construct doubleConstructor = yamlConstructors.get(Tag.FLOAT); + result = doubleConstructor.construct(node); + if (type == Float.class || type == Float.TYPE) { + result = Float.valueOf(((Double) result).floatValue()); + } + } + } else if (type == Byte.class || type == Short.class || type == Integer.class + || type == Long.class || type == BigInteger.class || type == Byte.TYPE + || type == Short.TYPE || type == Integer.TYPE || type == Long.TYPE) { + Construct intConstructor = yamlConstructors.get(Tag.INT); + result = intConstructor.construct(node); + if (type == Byte.class || type == Byte.TYPE) { + result = Integer.valueOf(result.toString()).byteValue(); + } else if (type == Short.class || type == Short.TYPE) { + result = Integer.valueOf(result.toString()).shortValue(); + } else if (type == Integer.class || type == Integer.TYPE) { + result = Integer.parseInt(result.toString()); + } else if (type == Long.class || type == Long.TYPE) { + result = Long.valueOf(result.toString()); + } else { + // only BigInteger left + result = new BigInteger(result.toString()); } + } else if (Enum.class.isAssignableFrom(type)) { + String enumValueName = node.getValue(); + try { + if (loadingConfig.isEnumCaseSensitive()) { + result = Enum.valueOf(type, enumValueName); + } else { + result = EnumUtils.findEnumInsensitiveCase(type, enumValueName); + } + } catch (Exception ex) { + throw new YAMLException("Unable to find enum value '" + enumValueName + + "' for enum class: " + type.getName()); + } + } else if (Calendar.class.isAssignableFrom(type)) { + ConstructYamlTimestamp contr = new ConstructYamlTimestamp(); + contr.construct(node); + result = contr.getCalendar(); + } else if (Number.class.isAssignableFrom(type)) { + // since we do not know the exact type we create Float + ConstructYamlFloat contr = new ConstructYamlFloat(); + result = contr.construct(node); + } else if (UUID.class == type) { + result = UUID.fromString(node.getValue()); + } else { + if (yamlConstructors.containsKey(node.getTag())) { + result = yamlConstructors.get(node.getTag()).construct(node); + } else { + throw new YAMLException("Unsupported class: " + type); + } + } + return result; } - - /** - * Construct sequence (List, Array, or immutable object) when the runtime - * class is known. - */ - protected class ConstructSequence implements Construct { - @SuppressWarnings("unchecked") - public Object construct(Node node) { - SequenceNode snode = (SequenceNode) node; - if (Set.class.isAssignableFrom(node.getType())) { - if (node.isTwoStepsConstruction()) { - throw new YAMLException("Set cannot be recursive."); - } else { - return constructSet(snode); - } - } else if (Collection.class.isAssignableFrom(node.getType())) { - if (node.isTwoStepsConstruction()) { - return createDefaultList(snode.getValue().size()); - } else { - return constructSequence(snode); - } - } else if (node.getType().isArray()) { - if (node.isTwoStepsConstruction()) { - return createArray(node.getType(), snode.getValue().size()); - } else { - return constructArray(snode); - } - } else { - // create immutable object - List<java.lang.reflect.Constructor<?>> possibleConstructors = new ArrayList<java.lang.reflect.Constructor<?>>( - snode.getValue().size()); - for (java.lang.reflect.Constructor<?> constructor : node - .getType().getDeclaredConstructors()) { - if (snode.getValue() - .size() == constructor.getParameterTypes().length) { - possibleConstructors.add(constructor); - } - } - if (!possibleConstructors.isEmpty()) { - if (possibleConstructors.size() == 1) { - Object[] argumentList = new Object[snode.getValue().size()]; - java.lang.reflect.Constructor<?> c = possibleConstructors.get(0); - int index = 0; - for (Node argumentNode : snode.getValue()) { - Class<?> type = c.getParameterTypes()[index]; - // set runtime classes for arguments - argumentNode.setType(type); - argumentList[index++] = constructObject(argumentNode); - } - - try { - c.setAccessible(true); - return c.newInstance(argumentList); - } catch (Exception e) { - throw new YAMLException(e); - } - } - - // use BaseConstructor - List<Object> argumentList = (List<Object>) constructSequence(snode); - Class<?>[] parameterTypes = new Class[argumentList.size()]; - int index = 0; - for (Object parameter : argumentList) { - parameterTypes[index] = parameter.getClass(); - index++; - } - - for (java.lang.reflect.Constructor<?> c : possibleConstructors) { - Class<?>[] argTypes = c.getParameterTypes(); - boolean foundConstructor = true; - for (int i = 0; i < argTypes.length; i++) { - if (!wrapIfPrimitive(argTypes[i]).isAssignableFrom(parameterTypes[i])) { - foundConstructor = false; - break; - } - } - if (foundConstructor) { - try { - c.setAccessible(true); - return c.newInstance(argumentList.toArray()); - } catch (Exception e) { - throw new YAMLException(e); - } - } - } - } - throw new YAMLException("No suitable constructor with " - + String.valueOf(snode.getValue().size()) + " arguments found for " - + node.getType()); - - } + } + + /** + * Construct sequence (List, Array, or immutable object) when the runtime class is known. + */ + protected class ConstructSequence implements Construct { + + @SuppressWarnings("unchecked") + public Object construct(Node node) { + SequenceNode snode = (SequenceNode) node; + if (Set.class.isAssignableFrom(node.getType())) { + if (node.isTwoStepsConstruction()) { + throw new YAMLException("Set cannot be recursive."); + } else { + return constructSet(snode); } - - private final Class<? extends Object> wrapIfPrimitive(Class<?> clazz) { - if (!clazz.isPrimitive()) { - return clazz; - } - if (clazz == Integer.TYPE) { - return Integer.class; - } - if (clazz == Float.TYPE) { - return Float.class; - } - if (clazz == Double.TYPE) { - return Double.class; - } - if (clazz == Boolean.TYPE) { - return Boolean.class; - } - if (clazz == Long.TYPE) { - return Long.class; + } else if (Collection.class.isAssignableFrom(node.getType())) { + if (node.isTwoStepsConstruction()) { + return newList(snode); + } else { + return constructSequence(snode); + } + } else if (node.getType().isArray()) { + if (node.isTwoStepsConstruction()) { + return createArray(node.getType(), snode.getValue().size()); + } else { + return constructArray(snode); + } + } else { + // create immutable object + List<java.lang.reflect.Constructor<?>> possibleConstructors = + new ArrayList<java.lang.reflect.Constructor<?>>(snode.getValue().size()); + for (java.lang.reflect.Constructor<?> constructor : node.getType() + .getDeclaredConstructors()) { + if (snode.getValue().size() == constructor.getParameterTypes().length) { + possibleConstructors.add(constructor); + } + } + if (!possibleConstructors.isEmpty()) { + if (possibleConstructors.size() == 1) { + Object[] argumentList = new Object[snode.getValue().size()]; + java.lang.reflect.Constructor<?> c = possibleConstructors.get(0); + int index = 0; + for (Node argumentNode : snode.getValue()) { + Class<?> type = c.getParameterTypes()[index]; + // set runtime classes for arguments + argumentNode.setType(type); + argumentList[index++] = constructObject(argumentNode); } - if (clazz == Character.TYPE) { - return Character.class; + + try { + c.setAccessible(true); + return c.newInstance(argumentList); + } catch (Exception e) { + throw new YAMLException(e); } - if (clazz == Short.TYPE) { - return Short.class; + } + + // use BaseConstructor + List<Object> argumentList = (List<Object>) constructSequence(snode); + Class<?>[] parameterTypes = new Class[argumentList.size()]; + int index = 0; + for (Object parameter : argumentList) { + parameterTypes[index] = parameter.getClass(); + index++; + } + + for (java.lang.reflect.Constructor<?> c : possibleConstructors) { + Class<?>[] argTypes = c.getParameterTypes(); + boolean foundConstructor = true; + for (int i = 0; i < argTypes.length; i++) { + if (!wrapIfPrimitive(argTypes[i]).isAssignableFrom(parameterTypes[i])) { + foundConstructor = false; + break; + } } - if (clazz == Byte.TYPE) { - return Byte.class; + if (foundConstructor) { + try { + c.setAccessible(true); + return c.newInstance(argumentList.toArray()); + } catch (Exception e) { + throw new YAMLException(e); + } } - throw new YAMLException("Unexpected primitive " + clazz); + } } + throw new YAMLException("No suitable constructor with " + snode.getValue().size() + + " arguments found for " + node.getType()); - @SuppressWarnings("unchecked") - public void construct2ndStep(Node node, Object object) { - SequenceNode snode = (SequenceNode) node; - if (List.class.isAssignableFrom(node.getType())) { - List<Object> list = (List<Object>) object; - constructSequenceStep2(snode, list); - } else if (node.getType().isArray()) { - constructArrayStep2(snode, object); - } else { - throw new YAMLException("Immutable objects cannot be recursive."); - } - } + } } - protected Class<?> getClassForNode(Node node) { - Class<? extends Object> classForTag = typeTags.get(node.getTag()); - if (classForTag == null) { - String name = node.getTag().getClassName(); - Class<?> cl; - try { - cl = getClassForName(name); - } catch (ClassNotFoundException e) { - throw new YAMLException("Class not found: " + name); - } - typeTags.put(node.getTag(), cl); - return cl; - } else { - return classForTag; - } + private final Class<? extends Object> wrapIfPrimitive(Class<?> clazz) { + if (!clazz.isPrimitive()) { + return clazz; + } + if (clazz == Integer.TYPE) { + return Integer.class; + } + if (clazz == Float.TYPE) { + return Float.class; + } + if (clazz == Double.TYPE) { + return Double.class; + } + if (clazz == Boolean.TYPE) { + return Boolean.class; + } + if (clazz == Long.TYPE) { + return Long.class; + } + if (clazz == Character.TYPE) { + return Character.class; + } + if (clazz == Short.TYPE) { + return Short.class; + } + if (clazz == Byte.TYPE) { + return Byte.class; + } + throw new YAMLException("Unexpected primitive " + clazz); } - protected Class<?> getClassForName(String name) throws ClassNotFoundException { - try { - return Class.forName(name, true, Thread.currentThread().getContextClassLoader()); - } catch (ClassNotFoundException e) { - return Class.forName(name); - } + @SuppressWarnings("unchecked") + public void construct2ndStep(Node node, Object object) { + SequenceNode snode = (SequenceNode) node; + if (List.class.isAssignableFrom(node.getType())) { + List<Object> list = (List<Object>) object; + constructSequenceStep2(snode, list); + } else if (node.getType().isArray()) { + constructArrayStep2(snode, object); + } else { + throw new YAMLException("Immutable objects cannot be recursive."); + } + } + } + + protected Class<?> getClassForNode(Node node) { + Class<? extends Object> classForTag = typeTags.get(node.getTag()); + if (classForTag == null) { + String name = node.getTag().getClassName(); + Class<?> cl; + try { + cl = getClassForName(name); + } catch (ClassNotFoundException e) { + throw new YAMLException("Class not found: " + name); + } + typeTags.put(node.getTag(), cl); + return cl; + } else { + return classForTag; + } + } + + protected Class<?> getClassForName(String name) throws ClassNotFoundException { + try { + return Class.forName(name, true, Thread.currentThread().getContextClassLoader()); + } catch (ClassNotFoundException e) { + return Class.forName(name); } + } } diff --git a/src/main/java/org/yaml/snakeyaml/constructor/ConstructorException.java b/src/main/java/org/yaml/snakeyaml/constructor/ConstructorException.java index 336e3bae..13a672f4 100644 --- a/src/main/java/org/yaml/snakeyaml/constructor/ConstructorException.java +++ b/src/main/java/org/yaml/snakeyaml/constructor/ConstructorException.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,15 +17,16 @@ import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.MarkedYAMLException; public class ConstructorException extends MarkedYAMLException { - private static final long serialVersionUID = -8816339931365239910L; - protected ConstructorException(String context, Mark contextMark, String problem, - Mark problemMark, Throwable cause) { - super(context, contextMark, problem, problemMark, cause); - } + private static final long serialVersionUID = -8816339931365239910L; - protected ConstructorException(String context, Mark contextMark, String problem, - Mark problemMark) { - this(context, contextMark, problem, problemMark, null); - } + protected ConstructorException(String context, Mark contextMark, String problem, Mark problemMark, + Throwable cause) { + super(context, contextMark, problem, problemMark, cause); + } + + protected ConstructorException(String context, Mark contextMark, String problem, + Mark problemMark) { + this(context, contextMark, problem, problemMark, null); + } } diff --git a/src/main/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructor.java b/src/main/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructor.java index edb163da..8773e3ee 100644 --- a/src/main/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructor.java +++ b/src/main/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructor.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,22 +17,23 @@ package org.yaml.snakeyaml.constructor; * Construct instances with a custom Class Loader. */ public class CustomClassLoaderConstructor extends Constructor { - private ClassLoader loader = CustomClassLoaderConstructor.class.getClassLoader(); - public CustomClassLoaderConstructor(ClassLoader cLoader) { - this(Object.class, cLoader); - } + private ClassLoader loader = CustomClassLoaderConstructor.class.getClassLoader(); - public CustomClassLoaderConstructor(Class<? extends Object> theRoot, ClassLoader theLoader) { - super(theRoot); - if (theLoader == null) { - throw new NullPointerException("Loader must be provided."); - } - this.loader = theLoader; - } + public CustomClassLoaderConstructor(ClassLoader cLoader) { + this(Object.class, cLoader); + } - @Override - protected Class<?> getClassForName(String name) throws ClassNotFoundException { - return Class.forName(name, true, loader); + public CustomClassLoaderConstructor(Class<? extends Object> theRoot, ClassLoader theLoader) { + super(theRoot); + if (theLoader == null) { + throw new NullPointerException("Loader must be provided."); } + this.loader = theLoader; + } + + @Override + protected Class<?> getClassForName(String name) throws ClassNotFoundException { + return Class.forName(name, true, loader); + } } diff --git a/src/main/java/org/yaml/snakeyaml/constructor/DuplicateKeyException.java b/src/main/java/org/yaml/snakeyaml/constructor/DuplicateKeyException.java new file mode 100644 index 00000000..3a992104 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/constructor/DuplicateKeyException.java @@ -0,0 +1,23 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.constructor; + +import org.yaml.snakeyaml.error.Mark; + +public class DuplicateKeyException extends ConstructorException { + + protected DuplicateKeyException(Mark contextMark, Object key, Mark problemMark) { + super("while constructing a mapping", contextMark, "found duplicate key " + key, problemMark); + } +} diff --git a/src/main/java/org/yaml/snakeyaml/constructor/SafeConstructor.java b/src/main/java/org/yaml/snakeyaml/constructor/SafeConstructor.java index b5572ea0..b34011c5 100644 --- a/src/main/java/org/yaml/snakeyaml/constructor/SafeConstructor.java +++ b/src/main/java/org/yaml/snakeyaml/constructor/SafeConstructor.java @@ -1,26 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.math.BigInteger; -import java.text.NumberFormat; -import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; @@ -28,9 +23,10 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; +import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; - +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import org.yaml.snakeyaml.nodes.MappingNode; @@ -46,465 +42,578 @@ import org.yaml.snakeyaml.nodes.Tag; */ public class SafeConstructor extends BaseConstructor { - public static final ConstructUndefined undefinedConstructor = new ConstructUndefined(); - - public SafeConstructor() { - this.yamlConstructors.put(Tag.NULL, new ConstructYamlNull()); - this.yamlConstructors.put(Tag.BOOL, new ConstructYamlBool()); - this.yamlConstructors.put(Tag.INT, new ConstructYamlInt()); - this.yamlConstructors.put(Tag.FLOAT, new ConstructYamlFloat()); - this.yamlConstructors.put(Tag.BINARY, new ConstructYamlBinary()); - this.yamlConstructors.put(Tag.TIMESTAMP, new ConstructYamlTimestamp()); - this.yamlConstructors.put(Tag.OMAP, new ConstructYamlOmap()); - this.yamlConstructors.put(Tag.PAIRS, new ConstructYamlPairs()); - this.yamlConstructors.put(Tag.SET, new ConstructYamlSet()); - this.yamlConstructors.put(Tag.STR, new ConstructYamlStr()); - this.yamlConstructors.put(Tag.SEQ, new ConstructYamlSeq()); - this.yamlConstructors.put(Tag.MAP, new ConstructYamlMap()); - this.yamlConstructors.put(null, undefinedConstructor); - this.yamlClassConstructors.put(NodeId.scalar, undefinedConstructor); - this.yamlClassConstructors.put(NodeId.sequence, undefinedConstructor); - this.yamlClassConstructors.put(NodeId.mapping, undefinedConstructor); + public static final ConstructUndefined undefinedConstructor = new ConstructUndefined(); + + public SafeConstructor() { + this(new LoaderOptions()); + } + + public SafeConstructor(LoaderOptions loadingConfig) { + super(loadingConfig); + this.yamlConstructors.put(Tag.NULL, new ConstructYamlNull()); + this.yamlConstructors.put(Tag.BOOL, new ConstructYamlBool()); + this.yamlConstructors.put(Tag.INT, new ConstructYamlInt()); + this.yamlConstructors.put(Tag.FLOAT, new ConstructYamlFloat()); + this.yamlConstructors.put(Tag.BINARY, new ConstructYamlBinary()); + this.yamlConstructors.put(Tag.TIMESTAMP, new ConstructYamlTimestamp()); + this.yamlConstructors.put(Tag.OMAP, new ConstructYamlOmap()); + this.yamlConstructors.put(Tag.PAIRS, new ConstructYamlPairs()); + this.yamlConstructors.put(Tag.SET, new ConstructYamlSet()); + this.yamlConstructors.put(Tag.STR, new ConstructYamlStr()); + this.yamlConstructors.put(Tag.SEQ, new ConstructYamlSeq()); + this.yamlConstructors.put(Tag.MAP, new ConstructYamlMap()); + this.yamlConstructors.put(null, undefinedConstructor); + this.yamlClassConstructors.put(NodeId.scalar, undefinedConstructor); + this.yamlClassConstructors.put(NodeId.sequence, undefinedConstructor); + this.yamlClassConstructors.put(NodeId.mapping, undefinedConstructor); + } + + protected void flattenMapping(MappingNode node) { + flattenMapping(node, false); + } + + protected void flattenMapping(MappingNode node, boolean forceStringKeys) { + // perform merging only on nodes containing merge node(s) + processDuplicateKeys(node, forceStringKeys); + if (node.isMerged()) { + node.setValue(mergeNode(node, true, new HashMap<Object, Integer>(), + new ArrayList<NodeTuple>(), forceStringKeys)); } + } + + protected void processDuplicateKeys(MappingNode node) { + processDuplicateKeys(node, false); + } + + protected void processDuplicateKeys(MappingNode node, boolean forceStringKeys) { + List<NodeTuple> nodeValue = node.getValue(); + Map<Object, Integer> keys = new HashMap<Object, Integer>(nodeValue.size()); + TreeSet<Integer> toRemove = new TreeSet<Integer>(); + int i = 0; + for (NodeTuple tuple : nodeValue) { + Node keyNode = tuple.getKeyNode(); + if (!keyNode.getTag().equals(Tag.MERGE)) { + if (forceStringKeys) { + if (keyNode instanceof ScalarNode) { + keyNode.setType(String.class); + keyNode.setTag(Tag.STR); + } else { + throw new YAMLException("Keys must be scalars but found: " + keyNode); + } + } + Object key = constructObject(keyNode); + if (key != null && !forceStringKeys) { + if (keyNode.isTwoStepsConstruction()) { + if (!loadingConfig.getAllowRecursiveKeys()) { + throw new YAMLException( + "Recursive key for mapping is detected but it is not configured to be allowed."); + } else { + try { + key.hashCode();// check circular dependencies + } catch (Exception e) { + throw new ConstructorException("while constructing a mapping", node.getStartMark(), + "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e); + } + } + } + } - protected void flattenMapping(MappingNode node) { - // perform merging only on nodes containing merge node(s) - if (node.isMerged()) { - node.setValue(mergeNode(node, true, new HashMap<Object, Integer>(), - new ArrayList<NodeTuple>())); + Integer prevIndex = keys.put(key, i); + if (prevIndex != null) { + if (!isAllowDuplicateKeys()) { + throw new DuplicateKeyException(node.getStartMark(), key, + tuple.getKeyNode().getStartMark()); + } + toRemove.add(prevIndex); } + } + i = i + 1; } - /** - * Does merge for supplied mapping node. - * - * @param node - * where to merge - * @param isPreffered - * true if keys of node should take precedence over others... - * @param key2index - * maps already merged keys to index from values - * @param values - * collects merged NodeTuple - * @return list of the merged NodeTuple (to be set as value for the - * MappingNode) - */ - private List<NodeTuple> mergeNode(MappingNode node, boolean isPreffered, - Map<Object, Integer> key2index, List<NodeTuple> values) { - List<NodeTuple> nodeValue = node.getValue(); - // reversed for http://code.google.com/p/snakeyaml/issues/detail?id=139 - Collections.reverse(nodeValue); - for (Iterator<NodeTuple> iter = nodeValue.iterator(); iter.hasNext();) { - final NodeTuple nodeTuple = iter.next(); - final Node keyNode = nodeTuple.getKeyNode(); - final Node valueNode = nodeTuple.getValueNode(); - if (keyNode.getTag().equals(Tag.MERGE)) { - iter.remove(); - switch (valueNode.getNodeId()) { - case mapping: - MappingNode mn = (MappingNode) valueNode; - mergeNode(mn, false, key2index, values); - break; - case sequence: - SequenceNode sn = (SequenceNode) valueNode; - List<Node> vals = sn.getValue(); - for (Node subnode : vals) { - if (!(subnode instanceof MappingNode)) { - throw new ConstructorException("while constructing a mapping", - node.getStartMark(), - "expected a mapping for merging, but found " - + subnode.getNodeId(), subnode.getStartMark()); - } - MappingNode mnode = (MappingNode) subnode; - mergeNode(mnode, false, key2index, values); - } - break; - default: - throw new ConstructorException("while constructing a mapping", - node.getStartMark(), - "expected a mapping or list of mappings for merging, but found " - + valueNode.getNodeId(), valueNode.getStartMark()); - } - } else { - // we need to construct keys to avoid duplications - Object key = constructObject(keyNode); - if (!key2index.containsKey(key)) { // 1st time merging key - values.add(nodeTuple); - // keep track where tuple for the key is - key2index.put(key, values.size() - 1); - } else if (isPreffered) { // there is value for the key, but we - // need to override it - // change value for the key using saved position - values.set(key2index.get(key), nodeTuple); - } + Iterator<Integer> indices2remove = toRemove.descendingIterator(); + while (indices2remove.hasNext()) { + nodeValue.remove(indices2remove.next().intValue()); + } + } + + /** + * Does merge for supplied mapping node. + * + * @param node where to merge + * @param isPreffered true if keys of node should take precedence over others... + * @param key2index maps already merged keys to index from values + * @param values collects merged NodeTuple + * @return list of the merged NodeTuple (to be set as value for the MappingNode) + */ + private List<NodeTuple> mergeNode(MappingNode node, boolean isPreffered, + Map<Object, Integer> key2index, List<NodeTuple> values, boolean forceStringKeys) { + Iterator<NodeTuple> iter = node.getValue().iterator(); + while (iter.hasNext()) { + final NodeTuple nodeTuple = iter.next(); + final Node keyNode = nodeTuple.getKeyNode(); + final Node valueNode = nodeTuple.getValueNode(); + if (keyNode.getTag().equals(Tag.MERGE)) { + iter.remove(); + switch (valueNode.getNodeId()) { + case mapping: + MappingNode mn = (MappingNode) valueNode; + mergeNode(mn, false, key2index, values, forceStringKeys); + break; + case sequence: + SequenceNode sn = (SequenceNode) valueNode; + List<Node> vals = sn.getValue(); + for (Node subnode : vals) { + if (!(subnode instanceof MappingNode)) { + throw new ConstructorException("while constructing a mapping", node.getStartMark(), + "expected a mapping for merging, but found " + subnode.getNodeId(), + subnode.getStartMark()); + } + MappingNode mnode = (MappingNode) subnode; + mergeNode(mnode, false, key2index, values, forceStringKeys); } + break; + default: + throw new ConstructorException("while constructing a mapping", node.getStartMark(), + "expected a mapping or list of mappings for merging, but found " + + valueNode.getNodeId(), + valueNode.getStartMark()); + } + } else { + // we need to construct keys to avoid duplications + if (forceStringKeys) { + if (keyNode instanceof ScalarNode) { + keyNode.setType(String.class); + keyNode.setTag(Tag.STR); + } else { + throw new YAMLException("Keys must be scalars but found: " + keyNode); + } + } + Object key = constructObject(keyNode); + if (!key2index.containsKey(key)) { // 1st time merging key + values.add(nodeTuple); + // keep track where tuple for the key is + key2index.put(key, values.size() - 1); + } else if (isPreffered) { // there is value for the key, but we + // need to override it + // change value for the key using saved position + values.set(key2index.get(key), nodeTuple); } - return values; + } } + return values; + } + + @Override + protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) { + flattenMapping(node); + super.constructMapping2ndStep(node, mapping); + } + + @Override + protected void constructSet2ndStep(MappingNode node, Set<Object> set) { + flattenMapping(node); + super.constructSet2ndStep(node, set); + } + + public class ConstructYamlNull extends AbstractConstruct { - protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) { - flattenMapping(node); - super.constructMapping2ndStep(node, mapping); + @Override + public Object construct(Node node) { + if (node != null) { + constructScalar((ScalarNode) node); + } + return null; } + } + + private final static Map<String, Boolean> BOOL_VALUES = new HashMap<String, Boolean>(); + + static { + BOOL_VALUES.put("yes", Boolean.TRUE); + BOOL_VALUES.put("no", Boolean.FALSE); + BOOL_VALUES.put("true", Boolean.TRUE); + BOOL_VALUES.put("false", Boolean.FALSE); + BOOL_VALUES.put("on", Boolean.TRUE); + BOOL_VALUES.put("off", Boolean.FALSE); + } + + public class ConstructYamlBool extends AbstractConstruct { @Override - protected void constructSet2ndStep(MappingNode node, Set<Object> set) { - flattenMapping(node); - super.constructSet2ndStep(node, set); + public Object construct(Node node) { + String val = constructScalar((ScalarNode) node); + return BOOL_VALUES.get(val.toLowerCase()); } + } + + public class ConstructYamlInt extends AbstractConstruct { - public class ConstructYamlNull extends AbstractConstruct { - public Object construct(Node node) { - constructScalar((ScalarNode) node); - return null; + @Override + public Object construct(Node node) { + String value = constructScalar((ScalarNode) node).replaceAll("_", ""); + if (value.isEmpty()) { + throw new ConstructorException("while constructing an int", node.getStartMark(), + "found empty value", node.getStartMark()); + } + int sign = +1; + char first = value.charAt(0); + if (first == '-') { + sign = -1; + value = value.substring(1); + } else if (first == '+') { + value = value.substring(1); + } + int base = 10; + if ("0".equals(value)) { + return Integer.valueOf(0); + } else if (value.startsWith("0b")) { + value = value.substring(2); + base = 2; + } else if (value.startsWith("0x")) { + value = value.substring(2); + base = 16; + } else if (value.startsWith("0")) { + value = value.substring(1); + base = 8; + } else if (value.indexOf(':') != -1) { + String[] digits = value.split(":"); + int bes = 1; + int val = 0; + for (int i = 0, j = digits.length; i < j; i++) { + val += Long.parseLong(digits[j - i - 1]) * bes; + bes *= 60; } + return createNumber(sign, String.valueOf(val), 10); + } else { + return createNumber(sign, value, 10); + } + return createNumber(sign, value, base); } + } - private final static Map<String, Boolean> BOOL_VALUES = new HashMap<String, Boolean>(); - static { - BOOL_VALUES.put("yes", Boolean.TRUE); - BOOL_VALUES.put("no", Boolean.FALSE); - BOOL_VALUES.put("true", Boolean.TRUE); - BOOL_VALUES.put("false", Boolean.FALSE); - BOOL_VALUES.put("on", Boolean.TRUE); - BOOL_VALUES.put("off", Boolean.FALSE); + private static final int[][] RADIX_MAX = new int[17][2]; + + static { + int[] radixList = new int[] {2, 8, 10, 16}; + for (int radix : radixList) { + RADIX_MAX[radix] = + new int[] {maxLen(Integer.MAX_VALUE, radix), maxLen(Long.MAX_VALUE, radix)}; } + } + + private static int maxLen(final int max, final int radix) { + return Integer.toString(max, radix).length(); + } + + private static int maxLen(final long max, final int radix) { + return Long.toString(max, radix).length(); + } - public class ConstructYamlBool extends AbstractConstruct { - public Object construct(Node node) { - String val = (String) constructScalar((ScalarNode) node); - return BOOL_VALUES.get(val.toLowerCase()); + private Number createNumber(int sign, String number, int radix) { + final int len = number != null ? number.length() : 0; + if (sign < 0) { + number = "-" + number; + } + final int[] maxArr = radix < RADIX_MAX.length ? RADIX_MAX[radix] : null; + if (maxArr != null) { + final boolean gtInt = len > maxArr[0]; + if (gtInt) { + if (len > maxArr[1]) { + return new BigInteger(number, radix); } + return createLongOrBigInteger(number, radix); + } + } + Number result; + try { + result = Integer.valueOf(number, radix); + } catch (NumberFormatException e) { + result = createLongOrBigInteger(number, radix); + } + return result; + } + + protected static Number createLongOrBigInteger(final String number, final int radix) { + try { + return Long.valueOf(number, radix); + } catch (NumberFormatException e1) { + return new BigInteger(number, radix); } + } - public class ConstructYamlInt extends AbstractConstruct { - public Object construct(Node node) { - String value = constructScalar((ScalarNode) node).toString().replaceAll("_", ""); - int sign = +1; - char first = value.charAt(0); - if (first == '-') { - sign = -1; - value = value.substring(1); - } else if (first == '+') { - value = value.substring(1); - } - int base = 10; - if ("0".equals(value)) { - return Integer.valueOf(0); - } else if (value.startsWith("0b")) { - value = value.substring(2); - base = 2; - } else if (value.startsWith("0x")) { - value = value.substring(2); - base = 16; - } else if (value.startsWith("0")) { - value = value.substring(1); - base = 8; - } else if (value.indexOf(':') != -1) { - String[] digits = value.split(":"); - int bes = 1; - int val = 0; - for (int i = 0, j = digits.length; i < j; i++) { - val += Long.parseLong(digits[j - i - 1]) * bes; - bes *= 60; - } - return createNumber(sign, String.valueOf(val), 10); - } else { - return createNumber(sign, value, 10); - } - return createNumber(sign, value, base); + public class ConstructYamlFloat extends AbstractConstruct { + + @Override + public Object construct(Node node) { + String value = constructScalar((ScalarNode) node).replaceAll("_", ""); + if (value.isEmpty()) { + throw new ConstructorException("while constructing a float", node.getStartMark(), + "found empty value", node.getStartMark()); + } + int sign = +1; + char first = value.charAt(0); + if (first == '-') { + sign = -1; + value = value.substring(1); + } else if (first == '+') { + value = value.substring(1); + } + String valLower = value.toLowerCase(); + if (".inf".equals(valLower)) { + return Double.valueOf(sign == -1 ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); + } else if (".nan".equals(valLower)) { + return Double.valueOf(Double.NaN); + } else if (value.indexOf(':') != -1) { + String[] digits = value.split(":"); + int bes = 1; + double val = 0.0; + for (int i = 0, j = digits.length; i < j; i++) { + val += Double.parseDouble(digits[j - i - 1]) * bes; + bes *= 60; } + return Double.valueOf(sign * val); + } else { + Double d = Double.valueOf(value); + return Double.valueOf(d.doubleValue() * sign); + } } + } - private Number createNumber(int sign, String number, int radix) { - Number result; - if (sign < 0) { - number = "-" + number; - } - try { - result = Integer.valueOf(number, radix); - } catch (NumberFormatException e) { - try { - result = Long.valueOf(number, radix); - } catch (NumberFormatException e1) { - result = new BigInteger(number, radix); - } - } - return result; + public class ConstructYamlBinary extends AbstractConstruct { + + @Override + public Object construct(Node node) { + // Ignore white spaces for base64 encoded scalar + String noWhiteSpaces = constructScalar((ScalarNode) node).replaceAll("\\s", ""); + byte[] decoded = Base64Coder.decode(noWhiteSpaces.toCharArray()); + return decoded; } + } - public class ConstructYamlFloat extends AbstractConstruct { - public Object construct(Node node) { - String value = constructScalar((ScalarNode) node).toString().replaceAll("_", ""); - int sign = +1; - char first = value.charAt(0); - if (first == '-') { - sign = -1; - value = value.substring(1); - } else if (first == '+') { - value = value.substring(1); - } - String valLower = value.toLowerCase(); - if (".inf".equals(valLower)) { - return new Double(sign == -1 ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); - } else if (".nan".equals(valLower)) { - return new Double(Double.NaN); - } else if (value.indexOf(':') != -1) { - String[] digits = value.split(":"); - int bes = 1; - double val = 0.0; - for (int i = 0, j = digits.length; i < j; i++) { - val += Double.parseDouble(digits[j - i - 1]) * bes; - bes *= 60; - } - return new Double(sign * val); - } else { - Double d = Double.valueOf(value); - return new Double(d.doubleValue() * sign); - } - } + private final static Pattern TIMESTAMP_REGEXP = Pattern.compile( + "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:(?:[Tt]|[ \t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \t]*(?:Z|([-+][0-9][0-9]?)(?::([0-9][0-9])?)?))?)?$"); + private final static Pattern YMD_REGEXP = + Pattern.compile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)$"); + + public static class ConstructYamlTimestamp extends AbstractConstruct { + + private Calendar calendar; + + public Calendar getCalendar() { + return calendar; } - public class ConstructYamlBinary extends AbstractConstruct { - public Object construct(Node node) { - byte[] decoded = Base64Coder.decode(constructScalar((ScalarNode) node).toString() - .toCharArray()); - return decoded; + @Override + public Object construct(Node node) { + ScalarNode scalar = (ScalarNode) node; + String nodeValue = scalar.getValue(); + Matcher match = YMD_REGEXP.matcher(nodeValue); + if (match.matches()) { + String year_s = match.group(1); + String month_s = match.group(2); + String day_s = match.group(3); + calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + calendar.clear(); + calendar.set(Calendar.YEAR, Integer.parseInt(year_s)); + // Java's months are zero-based... + calendar.set(Calendar.MONTH, Integer.parseInt(month_s) - 1); // x + calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day_s)); + return calendar.getTime(); + } else { + match = TIMESTAMP_REGEXP.matcher(nodeValue); + if (!match.matches()) { + throw new YAMLException("Unexpected timestamp: " + nodeValue); } + String year_s = match.group(1); + String month_s = match.group(2); + String day_s = match.group(3); + String hour_s = match.group(4); + String min_s = match.group(5); + // seconds and milliseconds + String seconds = match.group(6); + String millis = match.group(7); + if (millis != null) { + seconds = seconds + "." + millis; + } + double fractions = Double.parseDouble(seconds); + int sec_s = (int) Math.round(Math.floor(fractions)); + int usec = (int) Math.round((fractions - sec_s) * 1000); + // timezone + String timezoneh_s = match.group(8); + String timezonem_s = match.group(9); + TimeZone timeZone; + if (timezoneh_s != null) { + String time = timezonem_s != null ? ":" + timezonem_s : "00"; + timeZone = TimeZone.getTimeZone("GMT" + timezoneh_s + time); + } else { + // no time zone provided + timeZone = TimeZone.getTimeZone("UTC"); + } + calendar = Calendar.getInstance(timeZone); + calendar.set(Calendar.YEAR, Integer.parseInt(year_s)); + // Java's months are zero-based... + calendar.set(Calendar.MONTH, Integer.parseInt(month_s) - 1); + calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day_s)); + calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour_s)); + calendar.set(Calendar.MINUTE, Integer.parseInt(min_s)); + calendar.set(Calendar.SECOND, sec_s); + calendar.set(Calendar.MILLISECOND, usec); + return calendar.getTime(); + } } + } - public class ConstructYamlNumber extends AbstractConstruct { - - private final NumberFormat nf = NumberFormat.getInstance(); - - public Object construct(Node node) { - ScalarNode scalar = (ScalarNode) node; - try { - return nf.parse(scalar.getValue()); - } catch (ParseException e) { - String lowerCaseValue = scalar.getValue().toLowerCase(); - if (lowerCaseValue.contains("inf") || lowerCaseValue.contains("nan")) { - /* - * Non-finites such as (+/-)infinity and NaN are not - * parseable by NumberFormat when these `Double` values are - * dumped by snakeyaml. Delegate to the `Tag.FLOAT` - * constructor when for this expected failure cause. - */ - return (Number) yamlConstructors.get(Tag.FLOAT).construct(node); - } else { - throw new IllegalArgumentException("Unable to parse as Number: " - + scalar.getValue()); - } - } + public class ConstructYamlOmap extends AbstractConstruct { + + @Override + public Object construct(Node node) { + // Note: we do not check for duplicate keys, because it's too + // CPU-expensive. + Map<Object, Object> omap = new LinkedHashMap<Object, Object>(); + if (!(node instanceof SequenceNode)) { + throw new ConstructorException("while constructing an ordered map", node.getStartMark(), + "expected a sequence, but found " + node.getNodeId(), node.getStartMark()); + } + SequenceNode snode = (SequenceNode) node; + for (Node subnode : snode.getValue()) { + if (!(subnode instanceof MappingNode)) { + throw new ConstructorException("while constructing an ordered map", node.getStartMark(), + "expected a mapping of length 1, but found " + subnode.getNodeId(), + subnode.getStartMark()); } + MappingNode mnode = (MappingNode) subnode; + if (mnode.getValue().size() != 1) { + throw new ConstructorException("while constructing an ordered map", node.getStartMark(), + "expected a single mapping item, but found " + mnode.getValue().size() + " items", + mnode.getStartMark()); + } + Node keyNode = mnode.getValue().get(0).getKeyNode(); + Node valueNode = mnode.getValue().get(0).getValueNode(); + Object key = constructObject(keyNode); + Object value = constructObject(valueNode); + omap.put(key, value); + } + return omap; } + } - private final static Pattern TIMESTAMP_REGEXP = Pattern - .compile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:(?:[Tt]|[ \t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \t]*(?:Z|([-+][0-9][0-9]?)(?::([0-9][0-9])?)?))?)?$"); - private final static Pattern YMD_REGEXP = Pattern - .compile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)$"); - - public static class ConstructYamlTimestamp extends AbstractConstruct { - private Calendar calendar; + public class ConstructYamlPairs extends AbstractConstruct { - public Calendar getCalendar() { - return calendar; + @Override + public Object construct(Node node) { + // Note: we do not check for duplicate keys, because it's too + // CPU-expensive. + if (!(node instanceof SequenceNode)) { + throw new ConstructorException("while constructing pairs", node.getStartMark(), + "expected a sequence, but found " + node.getNodeId(), node.getStartMark()); + } + SequenceNode snode = (SequenceNode) node; + List<Object[]> pairs = new ArrayList<Object[]>(snode.getValue().size()); + for (Node subnode : snode.getValue()) { + if (!(subnode instanceof MappingNode)) { + throw new ConstructorException("while constructingpairs", node.getStartMark(), + "expected a mapping of length 1, but found " + subnode.getNodeId(), + subnode.getStartMark()); } - - public Object construct(Node node) { - ScalarNode scalar = (ScalarNode) node; - String nodeValue = scalar.getValue(); - Matcher match = YMD_REGEXP.matcher(nodeValue); - if (match.matches()) { - String year_s = match.group(1); - String month_s = match.group(2); - String day_s = match.group(3); - calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - calendar.clear(); - calendar.set(Calendar.YEAR, Integer.parseInt(year_s)); - // Java's months are zero-based... - calendar.set(Calendar.MONTH, Integer.parseInt(month_s) - 1); // x - calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day_s)); - return calendar.getTime(); - } else { - match = TIMESTAMP_REGEXP.matcher(nodeValue); - if (!match.matches()) { - throw new YAMLException("Unexpected timestamp: " + nodeValue); - } - String year_s = match.group(1); - String month_s = match.group(2); - String day_s = match.group(3); - String hour_s = match.group(4); - String min_s = match.group(5); - // seconds and milliseconds - String seconds = match.group(6); - String millis = match.group(7); - if (millis != null) { - seconds = seconds + "." + millis; - } - double fractions = Double.parseDouble(seconds); - int sec_s = (int) Math.round(Math.floor(fractions)); - int usec = (int) Math.round((fractions - sec_s) * 1000); - // timezone - String timezoneh_s = match.group(8); - String timezonem_s = match.group(9); - TimeZone timeZone; - if (timezoneh_s != null) { - String time = timezonem_s != null ? ":" + timezonem_s : "00"; - timeZone = TimeZone.getTimeZone("GMT" + timezoneh_s + time); - } else { - // no time zone provided - timeZone = TimeZone.getTimeZone("UTC"); - } - calendar = Calendar.getInstance(timeZone); - calendar.set(Calendar.YEAR, Integer.parseInt(year_s)); - // Java's months are zero-based... - calendar.set(Calendar.MONTH, Integer.parseInt(month_s) - 1); - calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day_s)); - calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour_s)); - calendar.set(Calendar.MINUTE, Integer.parseInt(min_s)); - calendar.set(Calendar.SECOND, sec_s); - calendar.set(Calendar.MILLISECOND, usec); - return calendar.getTime(); - } + MappingNode mnode = (MappingNode) subnode; + if (mnode.getValue().size() != 1) { + throw new ConstructorException("while constructing pairs", node.getStartMark(), + "expected a single mapping item, but found " + mnode.getValue().size() + " items", + mnode.getStartMark()); } + Node keyNode = mnode.getValue().get(0).getKeyNode(); + Node valueNode = mnode.getValue().get(0).getValueNode(); + Object key = constructObject(keyNode); + Object value = constructObject(valueNode); + pairs.add(new Object[] {key, value}); + } + return pairs; } + } - public class ConstructYamlOmap extends AbstractConstruct { - public Object construct(Node node) { - // Note: we do not check for duplicate keys, because it's too - // CPU-expensive. - Map<Object, Object> omap = new LinkedHashMap<Object, Object>(); - if (!(node instanceof SequenceNode)) { - throw new ConstructorException("while constructing an ordered map", - node.getStartMark(), "expected a sequence, but found " + node.getNodeId(), - node.getStartMark()); - } - SequenceNode snode = (SequenceNode) node; - for (Node subnode : snode.getValue()) { - if (!(subnode instanceof MappingNode)) { - throw new ConstructorException("while constructing an ordered map", - node.getStartMark(), "expected a mapping of length 1, but found " - + subnode.getNodeId(), subnode.getStartMark()); - } - MappingNode mnode = (MappingNode) subnode; - if (mnode.getValue().size() != 1) { - throw new ConstructorException("while constructing an ordered map", - node.getStartMark(), "expected a single mapping item, but found " - + mnode.getValue().size() + " items", mnode.getStartMark()); - } - Node keyNode = mnode.getValue().get(0).getKeyNode(); - Node valueNode = mnode.getValue().get(0).getValueNode(); - Object key = constructObject(keyNode); - Object value = constructObject(valueNode); - omap.put(key, value); - } - return omap; - } + public class ConstructYamlSet implements Construct { + + @Override + public Object construct(Node node) { + if (node.isTwoStepsConstruction()) { + return (constructedObjects.containsKey(node) ? constructedObjects.get(node) + : createDefaultSet(((MappingNode) node).getValue().size())); + } else { + return constructSet((MappingNode) node); + } } - // Note: the same code as `construct_yaml_omap`. - public class ConstructYamlPairs extends AbstractConstruct { - public Object construct(Node node) { - // Note: we do not check for duplicate keys, because it's too - // CPU-expensive. - if (!(node instanceof SequenceNode)) { - throw new ConstructorException("while constructing pairs", node.getStartMark(), - "expected a sequence, but found " + node.getNodeId(), node.getStartMark()); - } - SequenceNode snode = (SequenceNode) node; - List<Object[]> pairs = new ArrayList<Object[]>(snode.getValue().size()); - for (Node subnode : snode.getValue()) { - if (!(subnode instanceof MappingNode)) { - throw new ConstructorException("while constructingpairs", node.getStartMark(), - "expected a mapping of length 1, but found " + subnode.getNodeId(), - subnode.getStartMark()); - } - MappingNode mnode = (MappingNode) subnode; - if (mnode.getValue().size() != 1) { - throw new ConstructorException("while constructing pairs", node.getStartMark(), - "expected a single mapping item, but found " + mnode.getValue().size() - + " items", mnode.getStartMark()); - } - Node keyNode = mnode.getValue().get(0).getKeyNode(); - Node valueNode = mnode.getValue().get(0).getValueNode(); - Object key = constructObject(keyNode); - Object value = constructObject(valueNode); - pairs.add(new Object[] { key, value }); - } - return pairs; - } + @Override + @SuppressWarnings("unchecked") + public void construct2ndStep(Node node, Object object) { + if (node.isTwoStepsConstruction()) { + constructSet2ndStep((MappingNode) node, (Set<Object>) object); + } else { + throw new YAMLException("Unexpected recursive set structure. Node: " + node); + } } + } - public class ConstructYamlSet implements Construct { - public Object construct(Node node) { - if (node.isTwoStepsConstruction()) { - return createDefaultSet(); - } else { - return constructSet((MappingNode) node); - } - } + public class ConstructYamlStr extends AbstractConstruct { - @SuppressWarnings("unchecked") - public void construct2ndStep(Node node, Object object) { - if (node.isTwoStepsConstruction()) { - constructSet2ndStep((MappingNode) node, (Set<Object>) object); - } else { - throw new YAMLException("Unexpected recursive set structure. Node: " + node); - } - } + @Override + public Object construct(Node node) { + return constructScalar((ScalarNode) node); } + } - public class ConstructYamlStr extends AbstractConstruct { - public Object construct(Node node) { - return constructScalar((ScalarNode) node); - } - } + public class ConstructYamlSeq implements Construct { - public class ConstructYamlSeq implements Construct { - public Object construct(Node node) { - SequenceNode seqNode = (SequenceNode) node; - if (node.isTwoStepsConstruction()) { - return createDefaultList(seqNode.getValue().size()); - } else { - return constructSequence(seqNode); - } - } + @Override + public Object construct(Node node) { + SequenceNode seqNode = (SequenceNode) node; + if (node.isTwoStepsConstruction()) { + return newList(seqNode); + } else { + return constructSequence(seqNode); + } + } - @SuppressWarnings("unchecked") - public void construct2ndStep(Node node, Object data) { - if (node.isTwoStepsConstruction()) { - constructSequenceStep2((SequenceNode) node, (List<Object>) data); - } else { - throw new YAMLException("Unexpected recursive sequence structure. Node: " + node); - } - } + @Override + @SuppressWarnings("unchecked") + public void construct2ndStep(Node node, Object data) { + if (node.isTwoStepsConstruction()) { + constructSequenceStep2((SequenceNode) node, (List<Object>) data); + } else { + throw new YAMLException("Unexpected recursive sequence structure. Node: " + node); + } } + } - public class ConstructYamlMap implements Construct { - public Object construct(Node node) { - if (node.isTwoStepsConstruction()) { - return createDefaultMap(); - } else { - return constructMapping((MappingNode) node); - } - } + public class ConstructYamlMap implements Construct { - @SuppressWarnings("unchecked") - public void construct2ndStep(Node node, Object object) { - if (node.isTwoStepsConstruction()) { - constructMapping2ndStep((MappingNode) node, (Map<Object, Object>) object); - } else { - throw new YAMLException("Unexpected recursive mapping structure. Node: " + node); - } - } + @Override + public Object construct(Node node) { + MappingNode mnode = (MappingNode) node; + if (node.isTwoStepsConstruction()) { + return createDefaultMap(mnode.getValue().size()); + } else { + return constructMapping(mnode); + } } - public static final class ConstructUndefined extends AbstractConstruct { - public Object construct(Node node) { - throw new ConstructorException(null, null, - "could not determine a constructor for the tag " + node.getTag(), - node.getStartMark()); - } + @Override + @SuppressWarnings("unchecked") + public void construct2ndStep(Node node, Object object) { + if (node.isTwoStepsConstruction()) { + constructMapping2ndStep((MappingNode) node, (Map<Object, Object>) object); + } else { + throw new YAMLException("Unexpected recursive mapping structure. Node: " + node); + } + } + } + + public static final class ConstructUndefined extends AbstractConstruct { + + @Override + public Object construct(Node node) { + throw new ConstructorException(null, null, + "could not determine a constructor for the tag " + node.getTag(), node.getStartMark()); } + } } diff --git a/src/main/java/org/yaml/snakeyaml/emitter/Emitable.java b/src/main/java/org/yaml/snakeyaml/emitter/Emitable.java index 87737280..dd72a702 100644 --- a/src/main/java/org/yaml/snakeyaml/emitter/Emitable.java +++ b/src/main/java/org/yaml/snakeyaml/emitter/Emitable.java @@ -1,24 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; import java.io.IOException; - import org.yaml.snakeyaml.events.Event; public interface Emitable { - void emit(Event event) throws IOException; + + void emit(Event event) throws IOException; } diff --git a/src/main/java/org/yaml/snakeyaml/emitter/Emitter.java b/src/main/java/org/yaml/snakeyaml/emitter/Emitter.java index 2136e21c..7ba6b4bb 100644 --- a/src/main/java/org/yaml/snakeyaml/emitter/Emitter.java +++ b/src/main/java/org/yaml/snakeyaml/emitter/Emitter.java @@ -1,41 +1,47 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; import java.io.IOException; import java.io.Writer; +import java.util.ArrayDeque; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.TreeSet; -import java.util.concurrent.ArrayBlockingQueue; +import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.ScalarStyle; import org.yaml.snakeyaml.DumperOptions.Version; +import org.yaml.snakeyaml.comments.CommentEventsCollector; +import org.yaml.snakeyaml.comments.CommentLine; +import org.yaml.snakeyaml.comments.CommentType; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.events.AliasEvent; import org.yaml.snakeyaml.events.CollectionEndEvent; import org.yaml.snakeyaml.events.CollectionStartEvent; +import org.yaml.snakeyaml.events.CommentEvent; import org.yaml.snakeyaml.events.DocumentEndEvent; import org.yaml.snakeyaml.events.DocumentStartEvent; import org.yaml.snakeyaml.events.Event; +import org.yaml.snakeyaml.events.Event.ID; import org.yaml.snakeyaml.events.MappingEndEvent; import org.yaml.snakeyaml.events.MappingStartEvent; import org.yaml.snakeyaml.events.NodeEvent; @@ -60,61 +66,141 @@ import org.yaml.snakeyaml.util.ArrayStack; * </pre> */ public final class Emitter implements Emitable { - private static final Map<Character, String> ESCAPE_REPLACEMENTS = new HashMap<Character, String>(); - public static final int MIN_INDENT = 1; - public static final int MAX_INDENT = 10; - - private static final char[] SPACE = { ' ' }; - - static { - ESCAPE_REPLACEMENTS.put('\0', "0"); - ESCAPE_REPLACEMENTS.put('\u0007', "a"); - ESCAPE_REPLACEMENTS.put('\u0008', "b"); - ESCAPE_REPLACEMENTS.put('\u0009', "t"); - ESCAPE_REPLACEMENTS.put('\n', "n"); - ESCAPE_REPLACEMENTS.put('\u000B', "v"); - ESCAPE_REPLACEMENTS.put('\u000C', "f"); - ESCAPE_REPLACEMENTS.put('\r', "r"); - ESCAPE_REPLACEMENTS.put('\u001B', "e"); - ESCAPE_REPLACEMENTS.put('"', "\""); - ESCAPE_REPLACEMENTS.put('\\', "\\"); - ESCAPE_REPLACEMENTS.put('\u0085', "N"); - ESCAPE_REPLACEMENTS.put('\u00A0', "_"); - ESCAPE_REPLACEMENTS.put('\u2028', "L"); - ESCAPE_REPLACEMENTS.put('\u2029', "P"); - } - - private final static Map<String, String> DEFAULT_TAG_PREFIXES = new LinkedHashMap<String, String>(); - static { - DEFAULT_TAG_PREFIXES.put("!", "!"); - DEFAULT_TAG_PREFIXES.put(Tag.PREFIX, "!!"); - } - // The stream should have the methods `write` and possibly `flush`. - private final Writer stream; - - // Encoding is defined by Writer (cannot be overriden by STREAM-START.) - // private Charset encoding; + public static final int MIN_INDENT = 1; + public static final int MAX_INDENT = 10; + private static final char[] SPACE = {' '}; + + private static final Pattern SPACES_PATTERN = Pattern.compile("\\s"); + private static final Set<Character> INVALID_ANCHOR = new HashSet(); + + static { + INVALID_ANCHOR.add('['); + INVALID_ANCHOR.add(']'); + INVALID_ANCHOR.add('{'); + INVALID_ANCHOR.add('}'); + INVALID_ANCHOR.add(','); + INVALID_ANCHOR.add('*'); + INVALID_ANCHOR.add('&'); + } + + private static final Map<Character, String> ESCAPE_REPLACEMENTS = + new HashMap<Character, String>(); + + static { + ESCAPE_REPLACEMENTS.put('\0', "0"); + ESCAPE_REPLACEMENTS.put('\u0007', "a"); + ESCAPE_REPLACEMENTS.put('\u0008', "b"); + ESCAPE_REPLACEMENTS.put('\u0009', "t"); + ESCAPE_REPLACEMENTS.put('\n', "n"); + ESCAPE_REPLACEMENTS.put('\u000B', "v"); + ESCAPE_REPLACEMENTS.put('\u000C', "f"); + ESCAPE_REPLACEMENTS.put('\r', "r"); + ESCAPE_REPLACEMENTS.put('\u001B', "e"); + ESCAPE_REPLACEMENTS.put('"', "\""); + ESCAPE_REPLACEMENTS.put('\\', "\\"); + ESCAPE_REPLACEMENTS.put('\u0085', "N"); + ESCAPE_REPLACEMENTS.put('\u00A0', "_"); + ESCAPE_REPLACEMENTS.put('\u2028', "L"); + ESCAPE_REPLACEMENTS.put('\u2029', "P"); + } + + private final static Map<String, String> DEFAULT_TAG_PREFIXES = + new LinkedHashMap<String, String>(); + + static { + DEFAULT_TAG_PREFIXES.put("!", "!"); + DEFAULT_TAG_PREFIXES.put(Tag.PREFIX, "!!"); + } + + // The stream should have the methods `write` and possibly `flush`. + private final Writer stream; + + // Encoding is defined by Writer (cannot be overridden by STREAM-START.) + // private Charset encoding; + + // Emitter is a state machine with a stack of states to handle nested + // structures. + private final ArrayStack<EmitterState> states; + private EmitterState state; + + // Current event and the event queue. + private final Queue<Event> events; + private Event event; + + // The current indentation level and the stack of previous indents. + private final ArrayStack<Integer> indents; + private Integer indent; + + // Flow level. + private int flowLevel; + + // Contexts. + private boolean rootContext; + private boolean mappingContext; + private boolean simpleKeyContext; + + // + // Characteristics of the last emitted character: + // - current position. + // - is it a whitespace? + // - is it an indention character + // (indentation space, '-', '?', or ':')? + // private int line; this variable is not used + private int column; + private boolean whitespace; + private boolean indention; + private boolean openEnded; + + // Formatting details. + private final Boolean canonical; + // pretty print flow by adding extra line breaks + private final Boolean prettyFlow; + + private final boolean allowUnicode; + private int bestIndent; + private final int indicatorIndent; + private final boolean indentWithIndicator; + private int bestWidth; + private final char[] bestLineBreak; + private final boolean splitLines; + private final int maxSimpleKeyLength; + private final boolean emitComments; + + // Tag prefixes. + private Map<String, String> tagPrefixes; + + // Prepared anchor and tag. + private String preparedAnchor; + private String preparedTag; + + // Scalar analysis and style. + private ScalarAnalysis analysis; + private DumperOptions.ScalarStyle style; + + // Comment processing + private final CommentEventsCollector blockCommentsCollector; + private final CommentEventsCollector inlineCommentsCollector; + + + public Emitter(Writer stream, DumperOptions opts) { + // The stream should have the methods `write` and possibly `flush`. + this.stream = stream; // Emitter is a state machine with a stack of states to handle nested // structures. - private final ArrayStack<EmitterState> states; - private EmitterState state; - + this.states = new ArrayStack<EmitterState>(100); + this.state = new ExpectStreamStart(); // Current event and the event queue. - private final Queue<Event> events; - private Event event; - + this.events = new ArrayDeque<>(100); + this.event = null; // The current indentation level and the stack of previous indents. - private final ArrayStack<Integer> indents; - private Integer indent; - + this.indents = new ArrayStack<Integer>(10); + this.indent = null; // Flow level. - private int flowLevel; - + this.flowLevel = 0; // Contexts. - private boolean rootContext; - private boolean mappingContext; - private boolean simpleKeyContext; + mappingContext = false; + simpleKeyContext = false; // // Characteristics of the last emitted character: @@ -122,1358 +208,1510 @@ public final class Emitter implements Emitable { // - is it a whitespace? // - is it an indention character // (indentation space, '-', '?', or ':')? - // private int line; this variable is not used - private int column; - private boolean whitespace; - private boolean indention; - private boolean openEnded; + column = 0; + whitespace = true; + indention = true; - // Formatting details. - private Boolean canonical; - // pretty print flow by adding extra line breaks - private Boolean prettyFlow; + // Whether the document requires an explicit document indicator + openEnded = false; - private boolean allowUnicode; - private int bestIndent; - private int indicatorIndent; - private int bestWidth; - private char[] bestLineBreak; - private boolean splitLines; + // Formatting details. + this.canonical = opts.isCanonical(); + this.prettyFlow = opts.isPrettyFlow(); + this.allowUnicode = opts.isAllowUnicode(); + this.bestIndent = 2; + if ((opts.getIndent() > MIN_INDENT) && (opts.getIndent() < MAX_INDENT)) { + this.bestIndent = opts.getIndent(); + } + this.indicatorIndent = opts.getIndicatorIndent(); + this.indentWithIndicator = opts.getIndentWithIndicator(); + this.bestWidth = 80; + if (opts.getWidth() > this.bestIndent * 2) { + this.bestWidth = opts.getWidth(); + } + this.bestLineBreak = opts.getLineBreak().getString().toCharArray(); + this.splitLines = opts.getSplitLines(); + this.maxSimpleKeyLength = opts.getMaxSimpleKeyLength(); + this.emitComments = opts.isProcessComments(); // Tag prefixes. - private Map<String, String> tagPrefixes; + this.tagPrefixes = new LinkedHashMap<String, String>(); // Prepared anchor and tag. - private String preparedAnchor; - private String preparedTag; + this.preparedAnchor = null; + this.preparedTag = null; // Scalar analysis and style. - private ScalarAnalysis analysis; - private Character style; - - public Emitter(Writer stream, DumperOptions opts) { - // The stream should have the methods `write` and possibly `flush`. - this.stream = stream; - // Emitter is a state machine with a stack of states to handle nested - // structures. - this.states = new ArrayStack<EmitterState>(100); - this.state = new ExpectStreamStart(); - // Current event and the event queue. - this.events = new ArrayBlockingQueue<Event>(100); - this.event = null; - // The current indentation level and the stack of previous indents. - this.indents = new ArrayStack<Integer>(10); - this.indent = null; - // Flow level. - this.flowLevel = 0; - // Contexts. - mappingContext = false; - simpleKeyContext = false; - - // - // Characteristics of the last emitted character: - // - current position. - // - is it a whitespace? - // - is it an indention character - // (indentation space, '-', '?', or ':')? - column = 0; - whitespace = true; - indention = true; - - // Whether the document requires an explicit document indicator - openEnded = false; - - // Formatting details. - this.canonical = opts.isCanonical(); - this.prettyFlow = opts.isPrettyFlow(); - this.allowUnicode = opts.isAllowUnicode(); - this.bestIndent = 2; - if ((opts.getIndent() > MIN_INDENT) && (opts.getIndent() < MAX_INDENT)) { - this.bestIndent = opts.getIndent(); - } - this.indicatorIndent = opts.getIndicatorIndent(); - this.bestWidth = 80; - if (opts.getWidth() > this.bestIndent * 2) { - this.bestWidth = opts.getWidth(); - } - this.bestLineBreak = opts.getLineBreak().getString().toCharArray(); - this.splitLines = opts.getSplitLines(); + this.analysis = null; + this.style = null; + + // Comment processing + this.blockCommentsCollector = + new CommentEventsCollector(events, CommentType.BLANK_LINE, CommentType.BLOCK); + this.inlineCommentsCollector = new CommentEventsCollector(events, CommentType.IN_LINE); + } + + public void emit(Event event) throws IOException { + this.events.add(event); + while (!needMoreEvents()) { + this.event = this.events.poll(); + this.state.expect(); + this.event = null; + } + } - // Tag prefixes. - this.tagPrefixes = new LinkedHashMap<String, String>(); + // In some cases, we wait for a few next events before emitting. - // Prepared anchor and tag. - this.preparedAnchor = null; - this.preparedTag = null; + private boolean needMoreEvents() { + if (events.isEmpty()) { + return true; + } - // Scalar analysis and style. - this.analysis = null; - this.style = null; + Iterator<Event> iter = events.iterator(); + Event event = iter.next(); // FIXME why without check ??? + while (event instanceof CommentEvent) { + if (!iter.hasNext()) { + return true; + } + event = iter.next(); } - public void emit(Event event) throws IOException { - this.events.add(event); - while (!needMoreEvents()) { - this.event = this.events.poll(); - this.state.expect(); - this.event = null; - } + if (event instanceof DocumentStartEvent) { + return needEvents(iter, 1); + } else if (event instanceof SequenceStartEvent) { + return needEvents(iter, 2); + } else if (event instanceof MappingStartEvent) { + return needEvents(iter, 3); + } else if (event instanceof StreamStartEvent) { + return needEvents(iter, 2); + } else if (event instanceof StreamEndEvent) { + return false; + } else if (emitComments) { + return needEvents(iter, 1); + } + return false; + } + + private boolean needEvents(Iterator<Event> iter, int count) { + int level = 0; + int actualCount = 0; + while (iter.hasNext()) { + Event event = iter.next(); + if (event instanceof CommentEvent) { + continue; + } + actualCount++; + if (event instanceof DocumentStartEvent || event instanceof CollectionStartEvent) { + level++; + } else if (event instanceof DocumentEndEvent || event instanceof CollectionEndEvent) { + level--; + } else if (event instanceof StreamEndEvent) { + level = -1; + } + if (level < 0) { + return false; + } + } + return actualCount < count; + } + + private void increaseIndent(boolean flow, boolean indentless) { + indents.push(indent); + if (indent == null) { + if (flow) { + indent = bestIndent; + } else { + indent = 0; + } + } else if (!indentless) { + this.indent += bestIndent; } + } - // In some cases, we wait for a few next events before emitting. + // States - private boolean needMoreEvents() { - if (events.isEmpty()) { - return true; - } - Event event = events.peek(); - if (event instanceof DocumentStartEvent) { - return needEvents(1); - } else if (event instanceof SequenceStartEvent) { - return needEvents(2); - } else if (event instanceof MappingStartEvent) { - return needEvents(3); - } else { - return false; - } - } + // Stream handlers. - private boolean needEvents(int count) { - int level = 0; - Iterator<Event> iter = events.iterator(); - iter.next(); - while (iter.hasNext()) { - Event event = iter.next(); - if (event instanceof DocumentStartEvent || event instanceof CollectionStartEvent) { - level++; - } else if (event instanceof DocumentEndEvent || event instanceof CollectionEndEvent) { - level--; - } else if (event instanceof StreamEndEvent) { - level = -1; - } - if (level < 0) { - return false; - } - } - return events.size() < count + 1; + private class ExpectStreamStart implements EmitterState { + + public void expect() throws IOException { + if (event instanceof StreamStartEvent) { + writeStreamStart(); + state = new ExpectFirstDocumentStart(); + } else { + throw new EmitterException("expected StreamStartEvent, but got " + event); + } } + } - private void increaseIndent(boolean flow, boolean indentless) { - indents.push(indent); - if (indent == null) { - if (flow) { - indent = bestIndent; - } else { - indent = 0; - } - } else if (!indentless) { - this.indent += bestIndent; - } + private class ExpectNothing implements EmitterState { + + public void expect() throws IOException { + throw new EmitterException("expecting nothing, but got " + event); } + } - // States + // Document handlers. - // Stream handlers. + private class ExpectFirstDocumentStart implements EmitterState { - private class ExpectStreamStart implements EmitterState { - public void expect() throws IOException { - if (event instanceof StreamStartEvent) { - writeStreamStart(); - state = new ExpectFirstDocumentStart(); - } else { - throw new EmitterException("expected StreamStartEvent, but got " + event); - } - } + public void expect() throws IOException { + new ExpectDocumentStart(true).expect(); } + } - private class ExpectNothing implements EmitterState { - public void expect() throws IOException { - throw new EmitterException("expecting nothing, but got " + event); - } - } + private class ExpectDocumentStart implements EmitterState { - // Document handlers. + private final boolean first; - private class ExpectFirstDocumentStart implements EmitterState { - public void expect() throws IOException { - new ExpectDocumentStart(true).expect(); - } + public ExpectDocumentStart(boolean first) { + this.first = first; } - private class ExpectDocumentStart implements EmitterState { - private boolean first; + public void expect() throws IOException { + if (event instanceof DocumentStartEvent) { + DocumentStartEvent ev = (DocumentStartEvent) event; + if ((ev.getVersion() != null || ev.getTags() != null) && openEnded) { + writeIndicator("...", true, false, false); + writeIndent(); + } + if (ev.getVersion() != null) { + String versionText = prepareVersion(ev.getVersion()); + writeVersionDirective(versionText); + } + tagPrefixes = new LinkedHashMap<String, String>(DEFAULT_TAG_PREFIXES); + if (ev.getTags() != null) { + Set<String> handles = new TreeSet<String>(ev.getTags().keySet()); + for (String handle : handles) { + String prefix = ev.getTags().get(handle); + tagPrefixes.put(prefix, handle); + String handleText = prepareTagHandle(handle); + String prefixText = prepareTagPrefix(prefix); + writeTagDirective(handleText, prefixText); + } + } + boolean implicit = first && !ev.getExplicit() && !canonical && ev.getVersion() == null + && (ev.getTags() == null || ev.getTags().isEmpty()) && !checkEmptyDocument(); + if (!implicit) { + writeIndent(); + writeIndicator("---", true, false, false); + if (canonical) { + writeIndent(); + } + } + state = new ExpectDocumentRoot(); + } else if (event instanceof StreamEndEvent) { + writeStreamEnd(); + state = new ExpectNothing(); + } else if (event instanceof CommentEvent) { + blockCommentsCollector.collectEvents(event); + writeBlockComment(); + // state = state; remains unchanged + } else { + throw new EmitterException("expected DocumentStartEvent, but got " + event); + } + } + } - public ExpectDocumentStart(boolean first) { - this.first = first; - } + private class ExpectDocumentEnd implements EmitterState { - public void expect() throws IOException { - if (event instanceof DocumentStartEvent) { - DocumentStartEvent ev = (DocumentStartEvent) event; - if ((ev.getVersion() != null || ev.getTags() != null) && openEnded) { - writeIndicator("...", true, false, false); - writeIndent(); - } - if (ev.getVersion() != null) { - String versionText = prepareVersion(ev.getVersion()); - writeVersionDirective(versionText); - } - tagPrefixes = new LinkedHashMap<String, String>(DEFAULT_TAG_PREFIXES); - if (ev.getTags() != null) { - Set<String> handles = new TreeSet<String>(ev.getTags().keySet()); - for (String handle : handles) { - String prefix = ev.getTags().get(handle); - tagPrefixes.put(prefix, handle); - String handleText = prepareTagHandle(handle); - String prefixText = prepareTagPrefix(prefix); - writeTagDirective(handleText, prefixText); - } - } - boolean implicit = first && !ev.getExplicit() && !canonical - && ev.getVersion() == null - && (ev.getTags() == null || ev.getTags().isEmpty()) - && !checkEmptyDocument(); - if (!implicit) { - writeIndent(); - writeIndicator("---", true, false, false); - if (canonical) { - writeIndent(); - } - } - state = new ExpectDocumentRoot(); - } else if (event instanceof StreamEndEvent) { - // TODO fix 313 PyYAML changeset - // if (openEnded) { - // writeIndicator("...", true, false, false); - // writeIndent(); - // } - writeStreamEnd(); - state = new ExpectNothing(); - } else { - throw new EmitterException("expected DocumentStartEvent, but got " + event); - } + public void expect() throws IOException { + event = blockCommentsCollector.collectEventsAndPoll(event); + writeBlockComment(); + if (event instanceof DocumentEndEvent) { + writeIndent(); + if (((DocumentEndEvent) event).getExplicit()) { + writeIndicator("...", true, false, false); + writeIndent(); } + flushStream(); + state = new ExpectDocumentStart(false); + } else { + throw new EmitterException("expected DocumentEndEvent, but got " + event); + } } + } - private class ExpectDocumentEnd implements EmitterState { - public void expect() throws IOException { - if (event instanceof DocumentEndEvent) { - writeIndent(); - if (((DocumentEndEvent) event).getExplicit()) { - writeIndicator("...", true, false, false); - writeIndent(); - } - flushStream(); - state = new ExpectDocumentStart(false); - } else { - throw new EmitterException("expected DocumentEndEvent, but got " + event); - } - } - } + private class ExpectDocumentRoot implements EmitterState { - private class ExpectDocumentRoot implements EmitterState { - public void expect() throws IOException { - states.push(new ExpectDocumentEnd()); - expectNode(true, false, false); + public void expect() throws IOException { + event = blockCommentsCollector.collectEventsAndPoll(event); + if (!blockCommentsCollector.isEmpty()) { + writeBlockComment(); + if (event instanceof DocumentEndEvent) { + new ExpectDocumentEnd().expect(); + return; } + } + states.push(new ExpectDocumentEnd()); + expectNode(true, false, false); } - - // Node handlers. - - private void expectNode(boolean root, boolean mapping, boolean simpleKey) throws IOException { - rootContext = root; - mappingContext = mapping; - simpleKeyContext = simpleKey; - if (event instanceof AliasEvent) { - expectAlias(); - } else if (event instanceof ScalarEvent || event instanceof CollectionStartEvent) { - processAnchor("&"); - processTag(); - if (event instanceof ScalarEvent) { - expectScalar(); - } else if (event instanceof SequenceStartEvent) { - if (flowLevel != 0 || canonical || ((SequenceStartEvent) event).getFlowStyle() - || checkEmptySequence()) { - expectFlowSequence(); - } else { - expectBlockSequence(); - } - } else {// MappingStartEvent - if (flowLevel != 0 || canonical || ((MappingStartEvent) event).getFlowStyle() - || checkEmptyMapping()) { - expectFlowMapping(); - } else { - expectBlockMapping(); - } - } + } + + // Node handlers. + + private void expectNode(boolean root, boolean mapping, boolean simpleKey) throws IOException { + rootContext = root; + mappingContext = mapping; + simpleKeyContext = simpleKey; + if (event instanceof AliasEvent) { + expectAlias(); + } else if (event instanceof ScalarEvent || event instanceof CollectionStartEvent) { + processAnchor("&"); + processTag(); + if (event instanceof ScalarEvent) { + expectScalar(); + } else if (event instanceof SequenceStartEvent) { + if (flowLevel != 0 || canonical || ((SequenceStartEvent) event).isFlow() + || checkEmptySequence()) { + expectFlowSequence(); + } else { + expectBlockSequence(); + } + } else {// MappingStartEvent + if (flowLevel != 0 || canonical || ((MappingStartEvent) event).isFlow() + || checkEmptyMapping()) { + expectFlowMapping(); } else { - throw new EmitterException("expected NodeEvent, but got " + event); + expectBlockMapping(); } + } + } else { + throw new EmitterException("expected NodeEvent, but got " + event); } + } - private void expectAlias() throws IOException { - if (((NodeEvent) event).getAnchor() == null) { - throw new EmitterException("anchor is not specified for alias"); - } - processAnchor("*"); - state = states.pop(); + private void expectAlias() throws IOException { + if (!(event instanceof AliasEvent)) { + throw new EmitterException("Alias must be provided"); } + processAnchor("*"); + state = states.pop(); + } + + private void expectScalar() throws IOException { + increaseIndent(true, false); + processScalar(); + indent = indents.pop(); + state = states.pop(); + } + + // Flow sequence handlers. + + private void expectFlowSequence() throws IOException { + writeIndicator("[", true, true, false); + flowLevel++; + increaseIndent(true, false); + if (prettyFlow) { + writeIndent(); + } + state = new ExpectFirstFlowSequenceItem(); + } - private void expectScalar() throws IOException { - increaseIndent(true, false); - processScalar(); + private class ExpectFirstFlowSequenceItem implements EmitterState { + + public void expect() throws IOException { + if (event instanceof SequenceEndEvent) { indent = indents.pop(); + flowLevel--; + writeIndicator("]", false, false, false); + inlineCommentsCollector.collectEvents(); + writeInlineComments(); state = states.pop(); + } else if (event instanceof CommentEvent) { + blockCommentsCollector.collectEvents(event); + writeBlockComment(); + } else { + if (canonical || (column > bestWidth && splitLines) || prettyFlow) { + writeIndent(); + } + states.push(new ExpectFlowSequenceItem()); + expectNode(false, false, false); + event = inlineCommentsCollector.collectEvents(event); + writeInlineComments(); + } } + } - // Flow sequence handlers. + private class ExpectFlowSequenceItem implements EmitterState { - private void expectFlowSequence() throws IOException { - writeIndicator("[", true, true, false); - flowLevel++; - increaseIndent(true, false); + public void expect() throws IOException { + if (event instanceof SequenceEndEvent) { + indent = indents.pop(); + flowLevel--; + if (canonical) { + writeIndicator(",", false, false, false); + writeIndent(); + } else if (prettyFlow) { + writeIndent(); + } + writeIndicator("]", false, false, false); + inlineCommentsCollector.collectEvents(); + writeInlineComments(); if (prettyFlow) { - writeIndent(); + writeIndent(); } - state = new ExpectFirstFlowSequenceItem(); + state = states.pop(); + } else if (event instanceof CommentEvent) { + event = blockCommentsCollector.collectEvents(event); + } else { + writeIndicator(",", false, false, false); + writeBlockComment(); + if (canonical || (column > bestWidth && splitLines) || prettyFlow) { + writeIndent(); + } + states.push(new ExpectFlowSequenceItem()); + expectNode(false, false, false); + event = inlineCommentsCollector.collectEvents(event); + writeInlineComments(); + } } + } - private class ExpectFirstFlowSequenceItem implements EmitterState { - public void expect() throws IOException { - if (event instanceof SequenceEndEvent) { - indent = indents.pop(); - flowLevel--; - writeIndicator("]", false, false, false); - state = states.pop(); - } else { - if (canonical || (column > bestWidth && splitLines) || prettyFlow) { - writeIndent(); - } - states.push(new ExpectFlowSequenceItem()); - expectNode(false, false, false); - } - } + // Flow mapping handlers. + + private void expectFlowMapping() throws IOException { + writeIndicator("{", true, true, false); + flowLevel++; + increaseIndent(true, false); + if (prettyFlow) { + writeIndent(); } + state = new ExpectFirstFlowMappingKey(); + } - private class ExpectFlowSequenceItem implements EmitterState { - public void expect() throws IOException { - if (event instanceof SequenceEndEvent) { - indent = indents.pop(); - flowLevel--; - if (canonical) { - writeIndicator(",", false, false, false); - writeIndent(); - } - writeIndicator("]", false, false, false); - if (prettyFlow) { - writeIndent(); - } - state = states.pop(); - } else { - writeIndicator(",", false, false, false); - if (canonical || (column > bestWidth && splitLines) || prettyFlow) { - writeIndent(); - } - states.push(new ExpectFlowSequenceItem()); - expectNode(false, false, false); - } + private class ExpectFirstFlowMappingKey implements EmitterState { + + public void expect() throws IOException { + event = blockCommentsCollector.collectEventsAndPoll(event); + writeBlockComment(); + if (event instanceof MappingEndEvent) { + indent = indents.pop(); + flowLevel--; + writeIndicator("}", false, false, false); + inlineCommentsCollector.collectEvents(); + writeInlineComments(); + state = states.pop(); + } else { + if (canonical || (column > bestWidth && splitLines) || prettyFlow) { + writeIndent(); } + if (!canonical && checkSimpleKey()) { + states.push(new ExpectFlowMappingSimpleValue()); + expectNode(false, true, true); + } else { + writeIndicator("?", true, false, false); + states.push(new ExpectFlowMappingValue()); + expectNode(false, true, false); + } + } } + } - // Flow mapping handlers. + private class ExpectFlowMappingKey implements EmitterState { - private void expectFlowMapping() throws IOException { - writeIndicator("{", true, true, false); - flowLevel++; - increaseIndent(true, false); + public void expect() throws IOException { + if (event instanceof MappingEndEvent) { + indent = indents.pop(); + flowLevel--; + if (canonical) { + writeIndicator(",", false, false, false); + writeIndent(); + } if (prettyFlow) { - writeIndent(); + writeIndent(); } - state = new ExpectFirstFlowMappingKey(); - } - - private class ExpectFirstFlowMappingKey implements EmitterState { - public void expect() throws IOException { - if (event instanceof MappingEndEvent) { - indent = indents.pop(); - flowLevel--; - writeIndicator("}", false, false, false); - state = states.pop(); - } else { - if (canonical || (column > bestWidth && splitLines) || prettyFlow) { - writeIndent(); - } - if (!canonical && checkSimpleKey()) { - states.push(new ExpectFlowMappingSimpleValue()); - expectNode(false, true, true); - } else { - writeIndicator("?", true, false, false); - states.push(new ExpectFlowMappingValue()); - expectNode(false, true, false); - } - } + writeIndicator("}", false, false, false); + inlineCommentsCollector.collectEvents(); + writeInlineComments(); + state = states.pop(); + } else { + writeIndicator(",", false, false, false); + event = blockCommentsCollector.collectEventsAndPoll(event); + writeBlockComment(); + if (canonical || (column > bestWidth && splitLines) || prettyFlow) { + writeIndent(); + } + if (!canonical && checkSimpleKey()) { + states.push(new ExpectFlowMappingSimpleValue()); + expectNode(false, true, true); + } else { + writeIndicator("?", true, false, false); + states.push(new ExpectFlowMappingValue()); + expectNode(false, true, false); } + } } - - private class ExpectFlowMappingKey implements EmitterState { - public void expect() throws IOException { - if (event instanceof MappingEndEvent) { - indent = indents.pop(); - flowLevel--; - if (canonical) { - writeIndicator(",", false, false, false); - writeIndent(); - } - if (prettyFlow) { - writeIndent(); - } - writeIndicator("}", false, false, false); - state = states.pop(); - } else { - writeIndicator(",", false, false, false); - if (canonical || (column > bestWidth && splitLines) || prettyFlow) { - writeIndent(); - } - if (!canonical && checkSimpleKey()) { - states.push(new ExpectFlowMappingSimpleValue()); - expectNode(false, true, true); - } else { - writeIndicator("?", true, false, false); - states.push(new ExpectFlowMappingValue()); - expectNode(false, true, false); - } - } - } + } + + private class ExpectFlowMappingSimpleValue implements EmitterState { + + public void expect() throws IOException { + writeIndicator(":", false, false, false); + event = inlineCommentsCollector.collectEventsAndPoll(event); + writeInlineComments(); + states.push(new ExpectFlowMappingKey()); + expectNode(false, true, false); + inlineCommentsCollector.collectEvents(event); + writeInlineComments(); } - - private class ExpectFlowMappingSimpleValue implements EmitterState { - public void expect() throws IOException { - writeIndicator(":", false, false, false); - states.push(new ExpectFlowMappingKey()); - expectNode(false, true, false); - } + } + + private class ExpectFlowMappingValue implements EmitterState { + + public void expect() throws IOException { + if (canonical || (column > bestWidth) || prettyFlow) { + writeIndent(); + } + writeIndicator(":", true, false, false); + event = inlineCommentsCollector.collectEventsAndPoll(event); + writeInlineComments(); + states.push(new ExpectFlowMappingKey()); + expectNode(false, true, false); + inlineCommentsCollector.collectEvents(event); + writeInlineComments(); } + } - private class ExpectFlowMappingValue implements EmitterState { - public void expect() throws IOException { - if (canonical || (column > bestWidth) || prettyFlow) { - writeIndent(); - } - writeIndicator(":", true, false, false); - states.push(new ExpectFlowMappingKey()); - expectNode(false, true, false); - } - } + // Block sequence handlers. - // Block sequence handlers. + private void expectBlockSequence() throws IOException { + boolean indentless = mappingContext && !indention; + increaseIndent(false, indentless); + state = new ExpectFirstBlockSequenceItem(); + } - private void expectBlockSequence() throws IOException { - boolean indentless = mappingContext && !indention; - increaseIndent(false, indentless); - state = new ExpectFirstBlockSequenceItem(); - } + private class ExpectFirstBlockSequenceItem implements EmitterState { - private class ExpectFirstBlockSequenceItem implements EmitterState { - public void expect() throws IOException { - new ExpectBlockSequenceItem(true).expect(); - } + public void expect() throws IOException { + new ExpectBlockSequenceItem(true).expect(); } + } - private class ExpectBlockSequenceItem implements EmitterState { - private boolean first; + private class ExpectBlockSequenceItem implements EmitterState { - public ExpectBlockSequenceItem(boolean first) { - this.first = first; - } + private final boolean first; - public void expect() throws IOException { - if (!this.first && event instanceof SequenceEndEvent) { - indent = indents.pop(); - state = states.pop(); - } else { - writeIndent(); - writeWhitespace(indicatorIndent); - writeIndicator("-", true, false, true); - states.push(new ExpectBlockSequenceItem(false)); - expectNode(false, false, false); - } - } + public ExpectBlockSequenceItem(boolean first) { + this.first = first; } - // Block mapping handlers. - private void expectBlockMapping() throws IOException { - increaseIndent(false, false); - state = new ExpectFirstBlockMappingKey(); + public void expect() throws IOException { + if (!this.first && event instanceof SequenceEndEvent) { + indent = indents.pop(); + state = states.pop(); + } else if (event instanceof CommentEvent) { + blockCommentsCollector.collectEvents(event); + } else { + writeIndent(); + if (!indentWithIndicator || this.first) { + writeWhitespace(indicatorIndent); + } + writeIndicator("-", true, false, true); + if (indentWithIndicator && this.first) { + indent += indicatorIndent; + } + if (!blockCommentsCollector.isEmpty()) { + increaseIndent(false, false); + writeBlockComment(); + if (event instanceof ScalarEvent) { + analysis = analyzeScalar(((ScalarEvent) event).getValue()); + if (!analysis.isEmpty()) { + writeIndent(); + } + } + indent = indents.pop(); + } + states.push(new ExpectBlockSequenceItem(false)); + expectNode(false, false, false); + inlineCommentsCollector.collectEvents(); + writeInlineComments(); + } } + } - private class ExpectFirstBlockMappingKey implements EmitterState { - public void expect() throws IOException { - new ExpectBlockMappingKey(true).expect(); - } + // Block mapping handlers. + private void expectBlockMapping() throws IOException { + increaseIndent(false, false); + state = new ExpectFirstBlockMappingKey(); + } + + private class ExpectFirstBlockMappingKey implements EmitterState { + + public void expect() throws IOException { + new ExpectBlockMappingKey(true).expect(); } + } - private class ExpectBlockMappingKey implements EmitterState { - private boolean first; + private class ExpectBlockMappingKey implements EmitterState { - public ExpectBlockMappingKey(boolean first) { - this.first = first; - } + private final boolean first; - public void expect() throws IOException { - if (!this.first && event instanceof MappingEndEvent) { - indent = indents.pop(); - state = states.pop(); - } else { - writeIndent(); - if (checkSimpleKey()) { - states.push(new ExpectBlockMappingSimpleValue()); - expectNode(false, true, true); - } else { - writeIndicator("?", true, false, true); - states.push(new ExpectBlockMappingValue()); - expectNode(false, true, false); - } - } - } + public ExpectBlockMappingKey(boolean first) { + this.first = first; } - private class ExpectBlockMappingSimpleValue implements EmitterState { - public void expect() throws IOException { - writeIndicator(":", false, false, false); - states.push(new ExpectBlockMappingKey(false)); - expectNode(false, true, false); + public void expect() throws IOException { + event = blockCommentsCollector.collectEventsAndPoll(event); + writeBlockComment(); + if (!this.first && event instanceof MappingEndEvent) { + indent = indents.pop(); + state = states.pop(); + } else { + writeIndent(); + if (checkSimpleKey()) { + states.push(new ExpectBlockMappingSimpleValue()); + expectNode(false, true, true); + } else { + writeIndicator("?", true, false, true); + states.push(new ExpectBlockMappingValue()); + expectNode(false, true, false); } + } } + } - private class ExpectBlockMappingValue implements EmitterState { - public void expect() throws IOException { - writeIndent(); - writeIndicator(":", true, false, true); - states.push(new ExpectBlockMappingKey(false)); - expectNode(false, true, false); - } + private boolean isFoldedOrLiteral(Event event) { + if (!event.is(ID.Scalar)) { + return false; } - - // Checkers. - - private boolean checkEmptySequence() { - return event instanceof SequenceStartEvent && !events.isEmpty() && events.peek() instanceof SequenceEndEvent; + ScalarEvent scalarEvent = (ScalarEvent) event; + ScalarStyle style = scalarEvent.getScalarStyle(); + return style == ScalarStyle.FOLDED || style == ScalarStyle.LITERAL; + } + + private class ExpectBlockMappingSimpleValue implements EmitterState { + + public void expect() throws IOException { + writeIndicator(":", false, false, false); + event = inlineCommentsCollector.collectEventsAndPoll(event); + if (!isFoldedOrLiteral(event)) { + if (writeInlineComments()) { + increaseIndent(true, false); + writeIndent(); + indent = indents.pop(); + } + } + event = blockCommentsCollector.collectEventsAndPoll(event); + if (!blockCommentsCollector.isEmpty()) { + increaseIndent(true, false); + writeBlockComment(); + writeIndent(); + indent = indents.pop(); + } + states.push(new ExpectBlockMappingKey(false)); + expectNode(false, true, false); + inlineCommentsCollector.collectEvents(); + writeInlineComments(); } - - private boolean checkEmptyMapping() { - return event instanceof MappingStartEvent && !events.isEmpty() && events.peek() instanceof MappingEndEvent; + } + + private class ExpectBlockMappingValue implements EmitterState { + + public void expect() throws IOException { + writeIndent(); + writeIndicator(":", true, false, true); + event = inlineCommentsCollector.collectEventsAndPoll(event); + writeInlineComments(); + event = blockCommentsCollector.collectEventsAndPoll(event); + writeBlockComment(); + states.push(new ExpectBlockMappingKey(false)); + expectNode(false, true, false); + inlineCommentsCollector.collectEvents(event); + writeInlineComments(); } + } - private boolean checkEmptyDocument() { - if (!(event instanceof DocumentStartEvent) || events.isEmpty()) { - return false; - } - Event event = events.peek(); - if (event instanceof ScalarEvent) { - ScalarEvent e = (ScalarEvent) event; - return e.getAnchor() == null && e.getTag() == null && e.getImplicit() != null && e - .getValue().length() == 0; - } - return false; - } + // Checkers. - private boolean checkSimpleKey() { - int length = 0; - if (event instanceof NodeEvent && ((NodeEvent) event).getAnchor() != null) { - if (preparedAnchor == null) { - preparedAnchor = prepareAnchor(((NodeEvent) event).getAnchor()); - } - length += preparedAnchor.length(); - } - String tag = null; - if (event instanceof ScalarEvent) { - tag = ((ScalarEvent) event).getTag(); - } else if (event instanceof CollectionStartEvent) { - tag = ((CollectionStartEvent) event).getTag(); - } - if (tag != null) { - if (preparedTag == null) { - preparedTag = prepareTag(tag); - } - length += preparedTag.length(); - } - if (event instanceof ScalarEvent) { - if (analysis == null) { - analysis = analyzeScalar(((ScalarEvent) event).getValue()); - } - length += analysis.scalar.length(); - } - return length < 128 && (event instanceof AliasEvent - || (event instanceof ScalarEvent && !analysis.empty && !analysis.multiline) - || checkEmptySequence() || checkEmptyMapping()); - } + private boolean checkEmptySequence() { + return event instanceof SequenceStartEvent && !events.isEmpty() + && events.peek() instanceof SequenceEndEvent; + } - // Anchor, Tag, and Scalar processors. + private boolean checkEmptyMapping() { + return event instanceof MappingStartEvent && !events.isEmpty() + && events.peek() instanceof MappingEndEvent; + } - private void processAnchor(String indicator) throws IOException { - NodeEvent ev = (NodeEvent) event; - if (ev.getAnchor() == null) { - preparedAnchor = null; - return; - } - if (preparedAnchor == null) { - preparedAnchor = prepareAnchor(ev.getAnchor()); - } - writeIndicator(indicator + preparedAnchor, true, false, false); - preparedAnchor = null; + private boolean checkEmptyDocument() { + if (!(event instanceof DocumentStartEvent) || events.isEmpty()) { + return false; } - - private void processTag() throws IOException { - String tag = null; - if (event instanceof ScalarEvent) { - ScalarEvent ev = (ScalarEvent) event; - tag = ev.getTag(); - if (style == null) { - style = chooseScalarStyle(); - } - if ((!canonical || tag == null) && ((style == null && ev.getImplicit() - .canOmitTagInPlainScalar()) || (style != null && ev.getImplicit() - .canOmitTagInNonPlainScalar()))) { - preparedTag = null; - return; - } - if (ev.getImplicit().canOmitTagInPlainScalar() && tag == null) { - tag = "!"; - preparedTag = null; - } - } else { - CollectionStartEvent ev = (CollectionStartEvent) event; - tag = ev.getTag(); - if ((!canonical || tag == null) && ev.getImplicit()) { - preparedTag = null; - return; - } - } - if (tag == null) { - throw new EmitterException("tag is not specified"); - } - if (preparedTag == null) { - preparedTag = prepareTag(tag); - } - writeIndicator(preparedTag, true, false, false); + Event event = events.peek(); + if (event instanceof ScalarEvent) { + ScalarEvent e = (ScalarEvent) event; + return e.getAnchor() == null && e.getTag() == null && e.getImplicit() != null + && e.getValue().length() == 0; + } + return false; + } + + private boolean checkSimpleKey() { + int length = 0; + if (event instanceof NodeEvent && ((NodeEvent) event).getAnchor() != null) { + if (preparedAnchor == null) { + preparedAnchor = prepareAnchor(((NodeEvent) event).getAnchor()); + } + length += preparedAnchor.length(); + } + String tag = null; + if (event instanceof ScalarEvent) { + tag = ((ScalarEvent) event).getTag(); + } else if (event instanceof CollectionStartEvent) { + tag = ((CollectionStartEvent) event).getTag(); + } + if (tag != null) { + if (preparedTag == null) { + preparedTag = prepareTag(tag); + } + length += preparedTag.length(); + } + if (event instanceof ScalarEvent) { + if (analysis == null) { + analysis = analyzeScalar(((ScalarEvent) event).getValue()); + } + length += analysis.getScalar().length(); + } + return length < maxSimpleKeyLength && (event instanceof AliasEvent + || (event instanceof ScalarEvent && !analysis.isEmpty() && !analysis.isMultiline()) + || checkEmptySequence() || checkEmptyMapping()); + } + + // Anchor, Tag, and Scalar processors. + + private void processAnchor(String indicator) throws IOException { + NodeEvent ev = (NodeEvent) event; + if (ev.getAnchor() == null) { + preparedAnchor = null; + return; + } + if (preparedAnchor == null) { + preparedAnchor = prepareAnchor(ev.getAnchor()); + } + writeIndicator(indicator + preparedAnchor, true, false, false); + preparedAnchor = null; + } + + private void processTag() throws IOException { + String tag = null; + if (event instanceof ScalarEvent) { + ScalarEvent ev = (ScalarEvent) event; + tag = ev.getTag(); + if (style == null) { + style = chooseScalarStyle(); + } + if ((!canonical || tag == null) + && ((style == null && ev.getImplicit().canOmitTagInPlainScalar()) + || (style != null && ev.getImplicit().canOmitTagInNonPlainScalar()))) { + preparedTag = null; + return; + } + if (ev.getImplicit().canOmitTagInPlainScalar() && tag == null) { + tag = "!"; preparedTag = null; + } + } else { + CollectionStartEvent ev = (CollectionStartEvent) event; + tag = ev.getTag(); + if ((!canonical || tag == null) && ev.getImplicit()) { + preparedTag = null; + return; + } } - - private Character chooseScalarStyle() { - ScalarEvent ev = (ScalarEvent) event; - if (analysis == null) { - analysis = analyzeScalar(ev.getValue()); - } - if (ev.getStyle() != null && ev.getStyle() == '"' || this.canonical) { - return '"'; - } - if (ev.getStyle() == null && ev.getImplicit().canOmitTagInPlainScalar()) { - if (!(simpleKeyContext && (analysis.empty || analysis.multiline)) - && ((flowLevel != 0 && analysis.allowFlowPlain) || (flowLevel == 0 && analysis.allowBlockPlain))) { - return null; - } - } - if (ev.getStyle() != null && (ev.getStyle() == '|' || ev.getStyle() == '>')) { - if (flowLevel == 0 && !simpleKeyContext && analysis.allowBlock) { - return ev.getStyle(); - } - } - if (ev.getStyle() == null || ev.getStyle() == '\'') { - if (analysis.allowSingleQuoted && !(simpleKeyContext && analysis.multiline)) { - return '\''; - } - } - return '"'; + if (tag == null) { + throw new EmitterException("tag is not specified"); } - - private void processScalar() throws IOException { - ScalarEvent ev = (ScalarEvent) event; - if (analysis == null) { - analysis = analyzeScalar(ev.getValue()); - } - if (style == null) { - style = chooseScalarStyle(); - } - boolean split = !simpleKeyContext && splitLines; - if (style == null) { - writePlain(analysis.scalar, split); - } else { - switch (style) { - case '"': - writeDoubleQuoted(analysis.scalar, split); - break; - case '\'': - writeSingleQuoted(analysis.scalar, split); - break; - case '>': - writeFolded(analysis.scalar, split); - break; - case '|': - writeLiteral(analysis.scalar); - break; - default: - throw new YAMLException("Unexpected style: " + style); - } - } - analysis = null; - style = null; + if (preparedTag == null) { + preparedTag = prepareTag(tag); } + writeIndicator(preparedTag, true, false, false); + preparedTag = null; + } + + private DumperOptions.ScalarStyle chooseScalarStyle() { + ScalarEvent ev = (ScalarEvent) event; + if (analysis == null) { + analysis = analyzeScalar(ev.getValue()); + } + if (!ev.isPlain() && ev.getScalarStyle() == DumperOptions.ScalarStyle.DOUBLE_QUOTED + || this.canonical) { + return DumperOptions.ScalarStyle.DOUBLE_QUOTED; + } + if (ev.isPlain() && ev.getImplicit().canOmitTagInPlainScalar()) { + if (!(simpleKeyContext && (analysis.isEmpty() || analysis.isMultiline())) + && ((flowLevel != 0 && analysis.isAllowFlowPlain()) + || (flowLevel == 0 && analysis.isAllowBlockPlain()))) { + return null; + } + } + if (!ev.isPlain() && (ev.getScalarStyle() == DumperOptions.ScalarStyle.LITERAL + || ev.getScalarStyle() == DumperOptions.ScalarStyle.FOLDED)) { + if (flowLevel == 0 && !simpleKeyContext && analysis.isAllowBlock()) { + return ev.getScalarStyle(); + } + } + if (ev.isPlain() || ev.getScalarStyle() == DumperOptions.ScalarStyle.SINGLE_QUOTED) { + if (analysis.isAllowSingleQuoted() && !(simpleKeyContext && analysis.isMultiline())) { + return DumperOptions.ScalarStyle.SINGLE_QUOTED; + } + } + return DumperOptions.ScalarStyle.DOUBLE_QUOTED; + } - // Analyzers. - - private String prepareVersion(Version version) { - if (version.major() != 1) { - throw new EmitterException("unsupported YAML version: " + version); - } - return version.getRepresentation(); + private void processScalar() throws IOException { + ScalarEvent ev = (ScalarEvent) event; + if (analysis == null) { + analysis = analyzeScalar(ev.getValue()); + } + if (style == null) { + style = chooseScalarStyle(); } + boolean split = !simpleKeyContext && splitLines; + if (style == null) { + writePlain(analysis.getScalar(), split); + } else { + switch (style) { + case DOUBLE_QUOTED: + writeDoubleQuoted(analysis.getScalar(), split); + break; + case SINGLE_QUOTED: + writeSingleQuoted(analysis.getScalar(), split); + break; + case FOLDED: + writeFolded(analysis.getScalar(), split); + break; + case LITERAL: + writeLiteral(analysis.getScalar()); + break; + default: + throw new YAMLException("Unexpected style: " + style); + } + } + analysis = null; + style = null; + } - private final static Pattern HANDLE_FORMAT = Pattern.compile("^![-_\\w]*!$"); + // Analyzers. - private String prepareTagHandle(String handle) { - if (handle.length() == 0) { - throw new EmitterException("tag handle must not be empty"); - } else if (handle.charAt(0) != '!' || handle.charAt(handle.length() - 1) != '!') { - throw new EmitterException("tag handle must start and end with '!': " + handle); - } else if (!"!".equals(handle) && !HANDLE_FORMAT.matcher(handle).matches()) { - throw new EmitterException("invalid character in the tag handle: " + handle); - } - return handle; + private String prepareVersion(Version version) { + if (version.major() != 1) { + throw new EmitterException("unsupported YAML version: " + version); + } + return version.getRepresentation(); + } + + private final static Pattern HANDLE_FORMAT = Pattern.compile("^![-_\\w]*!$"); + + private String prepareTagHandle(String handle) { + if (handle.length() == 0) { + throw new EmitterException("tag handle must not be empty"); + } else if (handle.charAt(0) != '!' || handle.charAt(handle.length() - 1) != '!') { + throw new EmitterException("tag handle must start and end with '!': " + handle); + } else if (!"!".equals(handle) && !HANDLE_FORMAT.matcher(handle).matches()) { + throw new EmitterException("invalid character in the tag handle: " + handle); } + return handle; + } - private String prepareTagPrefix(String prefix) { - if (prefix.length() == 0) { - throw new EmitterException("tag prefix must not be empty"); - } - StringBuilder chunks = new StringBuilder(); - int start = 0; - int end = 0; - if (prefix.charAt(0) == '!') { - end = 1; - } - while (end < prefix.length()) { - end++; - } - if (start < end) { - chunks.append(prefix.substring(start, end)); - } - return chunks.toString(); + private String prepareTagPrefix(String prefix) { + if (prefix.length() == 0) { + throw new EmitterException("tag prefix must not be empty"); + } + StringBuilder chunks = new StringBuilder(); + int start = 0; + int end = 0; + if (prefix.charAt(0) == '!') { + end = 1; + } + while (end < prefix.length()) { + end++; } + if (start < end) { + chunks.append(prefix, start, end); + } + return chunks.toString(); + } - private String prepareTag(String tag) { - if (tag.length() == 0) { - throw new EmitterException("tag must not be empty"); - } - if ("!".equals(tag)) { - return tag; - } - String handle = null; - String suffix = tag; - // shall the tag prefixes be sorted as in PyYAML? - for (String prefix : tagPrefixes.keySet()) { - if (tag.startsWith(prefix) && ("!".equals(prefix) || prefix.length() < tag.length())) { - handle = prefix; - } - } - if (handle != null) { - suffix = tag.substring(handle.length()); - handle = tagPrefixes.get(handle); - } + private String prepareTag(String tag) { + if (tag.length() == 0) { + throw new EmitterException("tag must not be empty"); + } + if ("!".equals(tag)) { + return tag; + } + String handle = null; + String suffix = tag; + // shall the tag prefixes be sorted as in PyYAML? + for (String prefix : tagPrefixes.keySet()) { + if (tag.startsWith(prefix) && ("!".equals(prefix) || prefix.length() < tag.length())) { + handle = prefix; + } + } + if (handle != null) { + suffix = tag.substring(handle.length()); + handle = tagPrefixes.get(handle); + } - int end = suffix.length(); - String suffixText = end > 0 ? suffix.substring(0, end) : ""; + int end = suffix.length(); + String suffixText = end > 0 ? suffix.substring(0, end) : ""; - if (handle != null) { - return handle + suffixText; - } - return "!<" + suffixText + ">"; + if (handle != null) { + return handle + suffixText; } + return "!<" + suffixText + ">"; + } - private final static Pattern ANCHOR_FORMAT = Pattern.compile("^[-_\\w]*$"); - - static String prepareAnchor(String anchor) { - if (anchor.length() == 0) { - throw new EmitterException("anchor must not be empty"); - } - if (!ANCHOR_FORMAT.matcher(anchor).matches()) { - throw new EmitterException("invalid character in the anchor: " + anchor); - } - return anchor; + static String prepareAnchor(String anchor) { + if (anchor.length() == 0) { + throw new EmitterException("anchor must not be empty"); } + for (Character invalid : INVALID_ANCHOR) { + if (anchor.indexOf(invalid) > -1) { + throw new EmitterException("Invalid character '" + invalid + "' in the anchor: " + anchor); + } + } + Matcher matcher = SPACES_PATTERN.matcher(anchor); + if (matcher.find()) { + throw new EmitterException("Anchor may not contain spaces: " + anchor); + } + return anchor; + } - private ScalarAnalysis analyzeScalar(String scalar) { - // Empty scalar is a special case. - if (scalar.length() == 0) { - return new ScalarAnalysis(scalar, true, false, false, true, true, false); - } - // Indicators and special characters. - boolean blockIndicators = false; - boolean flowIndicators = false; - boolean lineBreaks = false; - boolean specialCharacters = false; - - // Important whitespace combinations. - boolean leadingSpace = false; - boolean leadingBreak = false; - boolean trailingSpace = false; - boolean trailingBreak = false; - boolean breakSpace = false; - boolean spaceBreak = false; - - // Check document indicators. - if (scalar.startsWith("---") || scalar.startsWith("...")) { + private ScalarAnalysis analyzeScalar(String scalar) { + // Empty scalar is a special case. + if (scalar.length() == 0) { + return new ScalarAnalysis(scalar, true, false, false, true, true, false); + } + // Indicators and special characters. + boolean blockIndicators = false; + boolean flowIndicators = false; + boolean lineBreaks = false; + boolean specialCharacters = false; + + // Important whitespace combinations. + boolean leadingSpace = false; + boolean leadingBreak = false; + boolean trailingSpace = false; + boolean trailingBreak = false; + boolean breakSpace = false; + boolean spaceBreak = false; + + // Check document indicators. + if (scalar.startsWith("---") || scalar.startsWith("...")) { + blockIndicators = true; + flowIndicators = true; + } + // First character or preceded by a whitespace. + boolean preceededByWhitespace = true; + boolean followedByWhitespace = + scalar.length() == 1 || Constant.NULL_BL_T_LINEBR.has(scalar.codePointAt(1)); + // The previous character is a space. + boolean previousSpace = false; + + // The previous character is a break. + boolean previousBreak = false; + + int index = 0; + + while (index < scalar.length()) { + int c = scalar.codePointAt(index); + // Check for indicators. + if (index == 0) { + // Leading indicators are special characters. + if ("#,[]{}&*!|>'\"%@`".indexOf(c) != -1) { + flowIndicators = true; + blockIndicators = true; + } + if (c == '?' || c == ':') { + flowIndicators = true; + if (followedByWhitespace) { blockIndicators = true; - flowIndicators = true; + } } - // First character or preceded by a whitespace. - boolean preceededByWhitespace = true; - boolean followedByWhitespace = scalar.length() == 1 || Constant.NULL_BL_T_LINEBR.has(scalar.charAt(1)); - // The previous character is a space. - boolean previousSpace = false; - - // The previous character is a break. - boolean previousBreak = false; - - int index = 0; - - while (index < scalar.length()) { - char ch = scalar.charAt(index); - // Check for indicators. - if (index == 0) { - // Leading indicators are special characters. - if ("#,[]{}&*!|>\'\"%@`".indexOf(ch) != -1) { - flowIndicators = true; - blockIndicators = true; - } - if (ch == '?' || ch == ':') { - flowIndicators = true; - if (followedByWhitespace) { - blockIndicators = true; - } - } - if (ch == '-' && followedByWhitespace) { - flowIndicators = true; - blockIndicators = true; - } - } else { - // Some indicators cannot appear within a scalar as well. - if (",?[]{}".indexOf(ch) != -1) { - flowIndicators = true; - } - if (ch == ':') { - flowIndicators = true; - if (followedByWhitespace) { - blockIndicators = true; - } - } - if (ch == '#' && preceededByWhitespace) { - flowIndicators = true; - blockIndicators = true; - } - } - // Check for line breaks, special, and unicode characters. - boolean isLineBreak = Constant.LINEBR.has(ch); - if (isLineBreak) { - lineBreaks = true; - } - if (!(ch == '\n' || ('\u0020' <= ch && ch <= '\u007E'))) { - if ((ch == '\u0085' || ('\u00A0' <= ch && ch <= '\uD7FF') || ('\uE000' <= ch && ch <= '\uFFFD')) - && (ch != '\uFEFF')) { - // unicode is used - if (!this.allowUnicode) { - specialCharacters = true; - } - } else { - specialCharacters = true; - } - } - // Detect important whitespace combinations. - if (ch == ' ') { - if (index == 0) { - leadingSpace = true; - } - if (index == scalar.length() - 1) { - trailingSpace = true; - } - if (previousBreak) { - breakSpace = true; - } - previousSpace = true; - previousBreak = false; - } else if (isLineBreak) { - if (index == 0) { - leadingBreak = true; - } - if (index == scalar.length() - 1) { - trailingBreak = true; - } - if (previousSpace) { - spaceBreak = true; - } - previousSpace = false; - previousBreak = true; - } else { - previousSpace = false; - previousBreak = false; - } - - // Prepare for the next character. - index++; - preceededByWhitespace = Constant.NULL_BL_T.has(ch) || isLineBreak; - followedByWhitespace = index + 1 >= scalar.length() - || (Constant.NULL_BL_T.has(scalar.charAt(index + 1))) || isLineBreak; - } - // Let's decide what styles are allowed. - boolean allowFlowPlain = true; - boolean allowBlockPlain = true; - boolean allowSingleQuoted = true; - boolean allowBlock = true; - // Leading and trailing whitespaces are bad for plain scalars. - if (leadingSpace || leadingBreak || trailingSpace || trailingBreak) { - allowFlowPlain = allowBlockPlain = false; - } - // We do not permit trailing spaces for block scalars. - if (trailingSpace) { - allowBlock = false; - } - // Spaces at the beginning of a new line are only acceptable for block - // scalars. - if (breakSpace) { - allowFlowPlain = allowBlockPlain = allowSingleQuoted = false; - } - // Spaces followed by breaks, as well as special character are only - // allowed for double quoted scalars. - if (spaceBreak || specialCharacters) { - allowFlowPlain = allowBlockPlain = allowSingleQuoted = allowBlock = false; - } - // Although the plain scalar writer supports breaks, we never emit - // multiline plain scalars in the flow context. - if (lineBreaks) { - allowFlowPlain = false; - } - // Flow indicators are forbidden for flow plain scalars. - if (flowIndicators) { - allowFlowPlain = false; + if (c == '-' && followedByWhitespace) { + flowIndicators = true; + blockIndicators = true; } - // Block indicators are forbidden for block plain scalars. - if (blockIndicators) { - allowBlockPlain = false; + } else { + // Some indicators cannot appear within a scalar as well. + if (",?[]{}".indexOf(c) != -1) { + flowIndicators = true; } - - return new ScalarAnalysis(scalar, false, lineBreaks, allowFlowPlain, allowBlockPlain, - allowSingleQuoted, allowBlock); + if (c == ':') { + flowIndicators = true; + if (followedByWhitespace) { + blockIndicators = true; + } + } + if (c == '#' && preceededByWhitespace) { + flowIndicators = true; + blockIndicators = true; + } + } + // Check for line breaks, special, and unicode characters. + boolean isLineBreak = Constant.LINEBR.has(c); + if (isLineBreak) { + lineBreaks = true; + } + if (!(c == '\n' || (0x20 <= c && c <= 0x7E))) { + if (c == 0x85 || (c >= 0xA0 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) + || (c >= 0x10000 && c <= 0x10FFFF)) { + // unicode is used + if (!this.allowUnicode) { + specialCharacters = true; + } + } else { + specialCharacters = true; + } + } + // Detect important whitespace combinations. + if (c == ' ') { + if (index == 0) { + leadingSpace = true; + } + if (index == scalar.length() - 1) { + trailingSpace = true; + } + if (previousBreak) { + breakSpace = true; + } + previousSpace = true; + previousBreak = false; + } else if (isLineBreak) { + if (index == 0) { + leadingBreak = true; + } + if (index == scalar.length() - 1) { + trailingBreak = true; + } + if (previousSpace) { + spaceBreak = true; + } + previousSpace = false; + previousBreak = true; + } else { + previousSpace = false; + previousBreak = false; + } + + // Prepare for the next character. + index += Character.charCount(c); + preceededByWhitespace = Constant.NULL_BL_T.has(c) || isLineBreak; + followedByWhitespace = true; + if (index + 1 < scalar.length()) { + int nextIndex = index + Character.charCount(scalar.codePointAt(index)); + if (nextIndex < scalar.length()) { + followedByWhitespace = + (Constant.NULL_BL_T.has(scalar.codePointAt(nextIndex))) || isLineBreak; + } + } + } + // Let's decide what styles are allowed. + boolean allowFlowPlain = true; + boolean allowBlockPlain = true; + boolean allowSingleQuoted = true; + boolean allowBlock = true; + // Leading and trailing whitespaces are bad for plain scalars. + if (leadingSpace || leadingBreak || trailingSpace || trailingBreak) { + allowFlowPlain = allowBlockPlain = false; + } + // We do not permit trailing spaces for block scalars. + if (trailingSpace) { + allowBlock = false; + } + // Spaces at the beginning of a new line are only acceptable for block + // scalars. + if (breakSpace) { + allowFlowPlain = allowBlockPlain = allowSingleQuoted = false; + } + // Spaces followed by breaks, as well as special character are only + // allowed for double quoted scalars. + if (spaceBreak || specialCharacters) { + allowFlowPlain = allowBlockPlain = allowSingleQuoted = allowBlock = false; + } + // Although the plain scalar writer supports breaks, we never emit + // multiline plain scalars in the flow context. + if (lineBreaks) { + allowFlowPlain = false; + } + // Flow indicators are forbidden for flow plain scalars. + if (flowIndicators) { + allowFlowPlain = false; + } + // Block indicators are forbidden for block plain scalars. + if (blockIndicators) { + allowBlockPlain = false; } - // Writers. + return new ScalarAnalysis(scalar, false, lineBreaks, allowFlowPlain, allowBlockPlain, + allowSingleQuoted, allowBlock); + } - void flushStream() throws IOException { - stream.flush(); - } + // Writers. - void writeStreamStart() { - // BOM is written by Writer. - } + void flushStream() throws IOException { + stream.flush(); + } - void writeStreamEnd() throws IOException { - flushStream(); + void writeStreamStart() { + // BOM is written by Writer. + } + + void writeStreamEnd() throws IOException { + flushStream(); + } + + void writeIndicator(String indicator, boolean needWhitespace, boolean whitespace, + boolean indentation) throws IOException { + if (!this.whitespace && needWhitespace) { + this.column++; + stream.write(SPACE); + } + this.whitespace = whitespace; + this.indention = this.indention && indentation; + this.column += indicator.length(); + openEnded = false; + stream.write(indicator); + } + + void writeIndent() throws IOException { + int indent; + if (this.indent != null) { + indent = this.indent; + } else { + indent = 0; } - void writeIndicator(String indicator, boolean needWhitespace, boolean whitespace, - boolean indentation) throws IOException { - if (!this.whitespace && needWhitespace) { - this.column++; - stream.write(SPACE); - } - this.whitespace = whitespace; - this.indention = this.indention && indentation; - this.column += indicator.length(); - openEnded = false; - stream.write(indicator); + if (!this.indention || this.column > indent || (this.column == indent && !this.whitespace)) { + writeLineBreak(null); } - void writeIndent() throws IOException { - int indent; - if (this.indent != null) { - indent = this.indent; - } else { - indent = 0; - } + writeWhitespace(indent - this.column); + } - if (!this.indention || this.column > indent || (this.column == indent && !this.whitespace)) { + private void writeWhitespace(int length) throws IOException { + if (length <= 0) { + return; + } + this.whitespace = true; + char[] data = new char[length]; + for (int i = 0; i < data.length; i++) { + data[i] = ' '; + } + this.column += length; + stream.write(data); + } + + private void writeLineBreak(String data) throws IOException { + this.whitespace = true; + this.indention = true; + this.column = 0; + if (data == null) { + stream.write(this.bestLineBreak); + } else { + stream.write(data); + } + } + + void writeVersionDirective(String versionText) throws IOException { + stream.write("%YAML "); + stream.write(versionText); + writeLineBreak(null); + } + + void writeTagDirective(String handleText, String prefixText) throws IOException { + // XXX: not sure 4 invocations better then StringBuilders created by str + // + str + stream.write("%TAG "); + stream.write(handleText); + stream.write(SPACE); + stream.write(prefixText); + writeLineBreak(null); + } + + // Scalar streams. + private void writeSingleQuoted(String text, boolean split) throws IOException { + writeIndicator("'", true, false, false); + boolean spaces = false; + boolean breaks = false; + int start = 0, end = 0; + char ch; + while (end <= text.length()) { + ch = 0; + if (end < text.length()) { + ch = text.charAt(end); + } + if (spaces) { + if (ch == 0 || ch != ' ') { + if (start + 1 == end && this.column > this.bestWidth && split && start != 0 + && end != text.length()) { + writeIndent(); + } else { + int len = end - start; + this.column += len; + stream.write(text, start, len); + } + start = end; + } + } else if (breaks) { + if (ch == 0 || Constant.LINEBR.hasNo(ch)) { + if (text.charAt(start) == '\n') { writeLineBreak(null); - } - - writeWhitespace(indent - this.column); + } + String data = text.substring(start, end); + for (char br : data.toCharArray()) { + if (br == '\n') { + writeLineBreak(null); + } else { + writeLineBreak(String.valueOf(br)); + } + } + writeIndent(); + start = end; + } + } else { + if (Constant.LINEBR.has(ch, "\0 '")) { + if (start < end) { + int len = end - start; + this.column += len; + stream.write(text, start, len); + start = end; + } + } + } + if (ch == '\'') { + this.column += 2; + stream.write("''"); + start = end + 1; + } + if (ch != 0) { + spaces = ch == ' '; + breaks = Constant.LINEBR.has(ch); + } + end++; } + writeIndicator("'", false, false, false); + } + + private void writeDoubleQuoted(String text, boolean split) throws IOException { + writeIndicator("\"", true, false, false); + int start = 0; + int end = 0; + while (end <= text.length()) { + Character ch = null; + if (end < text.length()) { + ch = text.charAt(end); + } + if (ch == null || "\"\\\u0085\u2028\u2029\uFEFF".indexOf(ch) != -1 + || !('\u0020' <= ch && ch <= '\u007E')) { + if (start < end) { + int len = end - start; + this.column += len; + stream.write(text, start, len); + start = end; + } + if (ch != null) { + String data; + + if (ESCAPE_REPLACEMENTS.containsKey(ch)) { + data = "\\" + ESCAPE_REPLACEMENTS.get(ch); + } else { + int codePoint; + + if (Character.isHighSurrogate(ch) && end + 1 < text.length()) { + char ch2 = text.charAt(end + 1); + codePoint = Character.toCodePoint(ch, ch2); + } else { + codePoint = ch; + } + + if (this.allowUnicode && StreamReader.isPrintable(codePoint)) { + data = String.valueOf(Character.toChars(codePoint)); - private void writeWhitespace(int length) throws IOException { - if (length <= 0) { - return; + if (Character.charCount(codePoint) == 2) { + end++; + } + } else { + // if !allowUnicode or the character is not printable, + // we must encode it + if (ch <= '\u00FF') { + String s = "0" + Integer.toString(ch, 16); + data = "\\x" + s.substring(s.length() - 2); + } else if (Character.charCount(codePoint) == 2) { + end++; + String s = "000" + Long.toHexString(codePoint); + data = "\\U" + s.substring(s.length() - 8); + } else { + String s = "000" + Integer.toString(ch, 16); + data = "\\u" + s.substring(s.length() - 4); + } + } + } + + this.column += data.length(); + stream.write(data); + start = end + 1; + } + } + if ((0 < end && end < (text.length() - 1)) && (ch == ' ' || start >= end) + && (this.column + (end - start)) > this.bestWidth && split) { + String data; + if (start >= end) { + data = "\\"; + } else { + data = text.substring(start, end) + "\\"; } - this.whitespace = true; - char[] data = new char[length]; - for (int i = 0; i < data.length; i++) { - data[i] = ' '; + if (start < end) { + start = end; } - this.column += length; + this.column += data.length(); stream.write(data); + writeIndent(); + this.whitespace = false; + this.indention = false; + if (text.charAt(start) == ' ') { + data = "\\"; + this.column += data.length(); + stream.write(data); + } + } + end += 1; } - - private void writeLineBreak(String data) throws IOException { - this.whitespace = true; - this.indention = true; - this.column = 0; - if (data == null) { - stream.write(this.bestLineBreak); + writeIndicator("\"", false, false, false); + } + + private boolean writeCommentLines(List<CommentLine> commentLines) throws IOException { + boolean wroteComment = false; + if (emitComments) { + int indentColumns = 0; + boolean firstComment = true; + for (CommentLine commentLine : commentLines) { + if (commentLine.getCommentType() != CommentType.BLANK_LINE) { + if (firstComment) { + firstComment = false; + writeIndicator("#", commentLine.getCommentType() == CommentType.IN_LINE, false, false); + indentColumns = this.column > 0 ? this.column - 1 : 0; + } else { + writeWhitespace(indentColumns); + writeIndicator("#", false, false, false); + } + stream.write(commentLine.getValue()); + writeLineBreak(null); } else { - stream.write(data); + writeLineBreak(null); + writeIndent(); } + wroteComment = true; + } } + return wroteComment; + } - void writeVersionDirective(String versionText) throws IOException { - stream.write("%YAML "); - stream.write(versionText); - writeLineBreak(null); - } - - void writeTagDirective(String handleText, String prefixText) throws IOException { - // XXX: not sure 4 invocations better then StringBuilders created by str - // + str - stream.write("%TAG "); - stream.write(handleText); - stream.write(SPACE); - stream.write(prefixText); - writeLineBreak(null); - } - - // Scalar streams. - private void writeSingleQuoted(String text, boolean split) throws IOException { - writeIndicator("'", true, false, false); - boolean spaces = false; - boolean breaks = false; - int start = 0, end = 0; - char ch; - while (end <= text.length()) { - ch = 0; - if (end < text.length()) { - ch = text.charAt(end); - } - if (spaces) { - if (ch == 0 || ch != ' ') { - if (start + 1 == end && this.column > this.bestWidth && split && start != 0 - && end != text.length()) { - writeIndent(); - } else { - int len = end - start; - this.column += len; - stream.write(text, start, len); - } - start = end; - } - } else if (breaks) { - if (ch == 0 || Constant.LINEBR.hasNo(ch)) { - if (text.charAt(start) == '\n') { - writeLineBreak(null); - } - String data = text.substring(start, end); - for (char br : data.toCharArray()) { - if (br == '\n') { - writeLineBreak(null); - } else { - writeLineBreak(String.valueOf(br)); - } - } - writeIndent(); - start = end; - } - } else { - if (Constant.LINEBR.has(ch, "\0 \'")) { - if (start < end) { - int len = end - start; - this.column += len; - stream.write(text, start, len); - start = end; - } - } - } - if (ch == '\'') { - this.column += 2; - stream.write("''"); - start = end + 1; - } - if (ch != 0) { - spaces = ch == ' '; - breaks = Constant.LINEBR.has(ch); - } - end++; - } - writeIndicator("'", false, false, false); + private void writeBlockComment() throws IOException { + if (!blockCommentsCollector.isEmpty()) { + writeIndent(); + writeCommentLines(blockCommentsCollector.consume()); } + } - private void writeDoubleQuoted(String text, boolean split) throws IOException { - writeIndicator("\"", true, false, false); - int start = 0; - int end = 0; - while (end <= text.length()) { - Character ch = null; - if (end < text.length()) { - ch = text.charAt(end); - } - if (ch == null || "\"\\\u0085\u2028\u2029\uFEFF".indexOf(ch) != -1 - || !('\u0020' <= ch && ch <= '\u007E')) { - if (start < end) { - int len = end - start; - this.column += len; - stream.write(text, start, len); - start = end; - } - if (ch != null) { - String data; - if (ESCAPE_REPLACEMENTS.containsKey(ch)) { - data = "\\" + ESCAPE_REPLACEMENTS.get(ch); - } else if (!this.allowUnicode || !StreamReader.isPrintable(ch)) { - // if !allowUnicode or the character is not printable, - // we must encode it - if (ch <= '\u00FF') { - String s = "0" + Integer.toString(ch, 16); - data = "\\x" + s.substring(s.length() - 2); - } else if (ch >= '\uD800' && ch <= '\uDBFF') { - if (end + 1 < text.length()) { - Character ch2 = text.charAt(++end); - String s = "000" + Long.toHexString(Character.toCodePoint(ch, ch2)); - data = "\\U" + s.substring(s.length() - 8); - } else { - String s = "000" + Integer.toString(ch, 16); - data = "\\u" + s.substring(s.length() - 4); - } - } else { - String s = "000" + Integer.toString(ch, 16); - data = "\\u" + s.substring(s.length() - 4); - } - } else { - data = String.valueOf(ch); - } - this.column += data.length(); - stream.write(data); - start = end + 1; - } - } - if ((0 < end && end < (text.length() - 1)) && (ch == ' ' || start >= end) - && (this.column + (end - start)) > this.bestWidth && split) { - String data; - if (start >= end) { - data = "\\"; - } else { - data = text.substring(start, end) + "\\"; - } - if (start < end) { - start = end; - } - this.column += data.length(); - stream.write(data); - writeIndent(); - this.whitespace = false; - this.indention = false; - if (text.charAt(start) == ' ') { - data = "\\"; - this.column += data.length(); - stream.write(data); - } - } - end += 1; - } - writeIndicator("\"", false, false, false); - } + private boolean writeInlineComments() throws IOException { + return writeCommentLines(inlineCommentsCollector.consume()); + } - private String determineBlockHints(String text) { - StringBuilder hints = new StringBuilder(); - if (Constant.LINEBR.has(text.charAt(0), " ")) { - hints.append(bestIndent); - } - char ch1 = text.charAt(text.length() - 1); - if (Constant.LINEBR.hasNo(ch1)) { - hints.append("-"); - } else if (text.length() == 1 || Constant.LINEBR.has(text.charAt(text.length() - 2))) { - hints.append("+"); - } - return hints.toString(); + private String determineBlockHints(String text) { + StringBuilder hints = new StringBuilder(); + if (Constant.LINEBR.has(text.charAt(0), " ")) { + hints.append(bestIndent); } - - void writeFolded(String text, boolean split) throws IOException { - String hints = determineBlockHints(text); - writeIndicator(">" + hints, true, false, false); - if (hints.length() > 0 && (hints.charAt(hints.length() - 1) == '+')) { - openEnded = true; - } - writeLineBreak(null); - boolean leadingSpace = true; - boolean spaces = false; - boolean breaks = true; - int start = 0, end = 0; - while (end <= text.length()) { - char ch = 0; - if (end < text.length()) { - ch = text.charAt(end); - } - if (breaks) { - if (ch == 0 || Constant.LINEBR.hasNo(ch)) { - if (!leadingSpace && ch != 0 && ch != ' ' && text.charAt(start) == '\n') { - writeLineBreak(null); - } - leadingSpace = ch == ' '; - String data = text.substring(start, end); - for (char br : data.toCharArray()) { - if (br == '\n') { - writeLineBreak(null); - } else { - writeLineBreak(String.valueOf(br)); - } - } - if (ch != 0) { - writeIndent(); - } - start = end; - } - } else if (spaces) { - if (ch != ' ') { - if (start + 1 == end && this.column > this.bestWidth && split) { - writeIndent(); - } else { - int len = end - start; - this.column += len; - stream.write(text, start, len); - } - start = end; - } + char ch1 = text.charAt(text.length() - 1); + if (Constant.LINEBR.hasNo(ch1)) { + hints.append("-"); + } else if (text.length() == 1 || Constant.LINEBR.has(text.charAt(text.length() - 2))) { + hints.append("+"); + } + return hints.toString(); + } + + void writeFolded(String text, boolean split) throws IOException { + String hints = determineBlockHints(text); + writeIndicator(">" + hints, true, false, false); + if (hints.length() > 0 && (hints.charAt(hints.length() - 1) == '+')) { + openEnded = true; + } + if (!writeInlineComments()) { + writeLineBreak(null); + } + boolean leadingSpace = true; + boolean spaces = false; + boolean breaks = true; + int start = 0, end = 0; + while (end <= text.length()) { + char ch = 0; + if (end < text.length()) { + ch = text.charAt(end); + } + if (breaks) { + if (ch == 0 || Constant.LINEBR.hasNo(ch)) { + if (!leadingSpace && ch != 0 && ch != ' ' && text.charAt(start) == '\n') { + writeLineBreak(null); + } + leadingSpace = ch == ' '; + String data = text.substring(start, end); + for (char br : data.toCharArray()) { + if (br == '\n') { + writeLineBreak(null); } else { - if (Constant.LINEBR.has(ch, "\0 ")) { - int len = end - start; - this.column += len; - stream.write(text, start, len); - if (ch == 0) { - writeLineBreak(null); - } - start = end; - } + writeLineBreak(String.valueOf(br)); } - if (ch != 0) { - breaks = Constant.LINEBR.has(ch); - spaces = ch == ' '; - } - end++; + } + if (ch != 0) { + writeIndent(); + } + start = end; } + } else if (spaces) { + if (ch != ' ') { + if (start + 1 == end && this.column > this.bestWidth && split) { + writeIndent(); + } else { + int len = end - start; + this.column += len; + stream.write(text, start, len); + } + start = end; + } + } else { + if (Constant.LINEBR.has(ch, "\0 ")) { + int len = end - start; + this.column += len; + stream.write(text, start, len); + if (ch == 0) { + writeLineBreak(null); + } + start = end; + } + } + if (ch != 0) { + breaks = Constant.LINEBR.has(ch); + spaces = ch == ' '; + } + end++; } + } - void writeLiteral(String text) throws IOException { - String hints = determineBlockHints(text); - writeIndicator("|" + hints, true, false, false); - if (hints.length() > 0 && (hints.charAt(hints.length() - 1)) == '+') { - openEnded = true; - } - writeLineBreak(null); - boolean breaks = true; - int start = 0, end = 0; - while (end <= text.length()) { - char ch = 0; - if (end < text.length()) { - ch = text.charAt(end); - } - if (breaks) { - if (ch == 0 || Constant.LINEBR.hasNo(ch)) { - String data = text.substring(start, end); - for (char br : data.toCharArray()) { - if (br == '\n') { - writeLineBreak(null); - } else { - writeLineBreak(String.valueOf(br)); - } - } - if (ch != 0) { - writeIndent(); - } - start = end; - } + void writeLiteral(String text) throws IOException { + String hints = determineBlockHints(text); + writeIndicator("|" + hints, true, false, false); + if (hints.length() > 0 && (hints.charAt(hints.length() - 1)) == '+') { + openEnded = true; + } + if (!writeInlineComments()) { + writeLineBreak(null); + } + boolean breaks = true; + int start = 0, end = 0; + while (end <= text.length()) { + char ch = 0; + if (end < text.length()) { + ch = text.charAt(end); + } + if (breaks) { + if (ch == 0 || Constant.LINEBR.hasNo(ch)) { + String data = text.substring(start, end); + for (char br : data.toCharArray()) { + if (br == '\n') { + writeLineBreak(null); } else { - if (ch == 0 || Constant.LINEBR.has(ch)) { - stream.write(text, start, end - start); - if (ch == 0) { - writeLineBreak(null); - } - start = end; - } - } - if (ch != 0) { - breaks = Constant.LINEBR.has(ch); + writeLineBreak(String.valueOf(br)); } - end++; + } + if (ch != 0) { + writeIndent(); + } + start = end; } + } else { + if (ch == 0 || Constant.LINEBR.has(ch)) { + stream.write(text, start, end - start); + if (ch == 0) { + writeLineBreak(null); + } + start = end; + } + } + if (ch != 0) { + breaks = Constant.LINEBR.has(ch); + } + end++; } + } - void writePlain(String text, boolean split) throws IOException { - if (rootContext) { - openEnded = true; - } - if (text.length() == 0) { - return; - } - if (!this.whitespace) { - this.column++; - stream.write(SPACE); - } - this.whitespace = false; - this.indention = false; - boolean spaces = false; - boolean breaks = false; - int start = 0, end = 0; - while (end <= text.length()) { - char ch = 0; - if (end < text.length()) { - ch = text.charAt(end); - } - if (spaces) { - if (ch != ' ') { - if (start + 1 == end && this.column > this.bestWidth && split) { - writeIndent(); - this.whitespace = false; - this.indention = false; - } else { - int len = end - start; - this.column += len; - stream.write(text, start, len); - } - start = end; - } - } else if (breaks) { - if (Constant.LINEBR.hasNo(ch)) { - if (text.charAt(start) == '\n') { - writeLineBreak(null); - } - String data = text.substring(start, end); - for (char br : data.toCharArray()) { - if (br == '\n') { - writeLineBreak(null); - } else { - writeLineBreak(String.valueOf(br)); - } - } - writeIndent(); - this.whitespace = false; - this.indention = false; - start = end; - } + void writePlain(String text, boolean split) throws IOException { + if (rootContext) { + openEnded = true; + } + if (text.length() == 0) { + return; + } + if (!this.whitespace) { + this.column++; + stream.write(SPACE); + } + this.whitespace = false; + this.indention = false; + boolean spaces = false; + boolean breaks = false; + int start = 0, end = 0; + while (end <= text.length()) { + char ch = 0; + if (end < text.length()) { + ch = text.charAt(end); + } + if (spaces) { + if (ch != ' ') { + if (start + 1 == end && this.column > this.bestWidth && split) { + writeIndent(); + this.whitespace = false; + this.indention = false; + } else { + int len = end - start; + this.column += len; + stream.write(text, start, len); + } + start = end; + } + } else if (breaks) { + if (Constant.LINEBR.hasNo(ch)) { + if (text.charAt(start) == '\n') { + writeLineBreak(null); + } + String data = text.substring(start, end); + for (char br : data.toCharArray()) { + if (br == '\n') { + writeLineBreak(null); } else { - if (ch == 0 || Constant.LINEBR.has(ch)) { - int len = end - start; - this.column += len; - stream.write(text, start, len); - start = end; - } + writeLineBreak(String.valueOf(br)); } - if (ch != 0) { - spaces = ch == ' '; - breaks = Constant.LINEBR.has(ch); - } - end++; - } + } + writeIndent(); + this.whitespace = false; + this.indention = false; + start = end; + } + } else { + if (Constant.LINEBR.has(ch, "\0 ")) { + int len = end - start; + this.column += len; + stream.write(text, start, len); + start = end; + } + } + if (ch != 0) { + spaces = ch == ' '; + breaks = Constant.LINEBR.has(ch); + } + end++; } + } } diff --git a/src/main/java/org/yaml/snakeyaml/emitter/EmitterException.java b/src/main/java/org/yaml/snakeyaml/emitter/EmitterException.java index ed83fee5..b029f3be 100644 --- a/src/main/java/org/yaml/snakeyaml/emitter/EmitterException.java +++ b/src/main/java/org/yaml/snakeyaml/emitter/EmitterException.java @@ -1,26 +1,25 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; import org.yaml.snakeyaml.error.YAMLException; public class EmitterException extends YAMLException { - private static final long serialVersionUID = -8280070025452995908L; - public EmitterException(String msg) { - super(msg); - } + private static final long serialVersionUID = -8280070025452995908L; + + public EmitterException(String msg) { + super(msg); + } } diff --git a/src/main/java/org/yaml/snakeyaml/emitter/EmitterState.java b/src/main/java/org/yaml/snakeyaml/emitter/EmitterState.java index 8e6622e0..82ca1349 100755 --- a/src/main/java/org/yaml/snakeyaml/emitter/EmitterState.java +++ b/src/main/java/org/yaml/snakeyaml/emitter/EmitterState.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; @@ -21,5 +19,6 @@ import java.io.IOException; * Python's methods are first class object. Java needs a class. */ interface EmitterState { - void expect() throws IOException; -}
\ No newline at end of file + + void expect() throws IOException; +} diff --git a/src/main/java/org/yaml/snakeyaml/emitter/ScalarAnalysis.java b/src/main/java/org/yaml/snakeyaml/emitter/ScalarAnalysis.java index 99a0829a..f9a84614 100644 --- a/src/main/java/org/yaml/snakeyaml/emitter/ScalarAnalysis.java +++ b/src/main/java/org/yaml/snakeyaml/emitter/ScalarAnalysis.java @@ -1,37 +1,68 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; + +/** + * Accumulate information to choose the scalar style + */ public final class ScalarAnalysis { - public String scalar; - public boolean empty; - public boolean multiline; - public boolean allowFlowPlain; - public boolean allowBlockPlain; - public boolean allowSingleQuoted; - public boolean allowBlock; - - public ScalarAnalysis(String scalar, boolean empty, boolean multiline, boolean allowFlowPlain, - boolean allowBlockPlain, boolean allowSingleQuoted, boolean allowBlock) { - this.scalar = scalar; - this.empty = empty; - this.multiline = multiline; - this.allowFlowPlain = allowFlowPlain; - this.allowBlockPlain = allowBlockPlain; - this.allowSingleQuoted = allowSingleQuoted; - this.allowBlock = allowBlock; - } -}
\ No newline at end of file + + private final String scalar; + private final boolean empty; + private final boolean multiline; + private final boolean allowFlowPlain; + private final boolean allowBlockPlain; + private final boolean allowSingleQuoted; + private final boolean allowBlock; + + public ScalarAnalysis(String scalar, boolean empty, boolean multiline, boolean allowFlowPlain, + boolean allowBlockPlain, boolean allowSingleQuoted, boolean allowBlock) { + this.scalar = scalar; + this.empty = empty; + this.multiline = multiline; + this.allowFlowPlain = allowFlowPlain; + this.allowBlockPlain = allowBlockPlain; + this.allowSingleQuoted = allowSingleQuoted; + this.allowBlock = allowBlock; + } + + public String getScalar() { + return scalar; + } + + public boolean isEmpty() { + return empty; + } + + public boolean isMultiline() { + return multiline; + } + + public boolean isAllowFlowPlain() { + return allowFlowPlain; + } + + public boolean isAllowBlockPlain() { + return allowBlockPlain; + } + + public boolean isAllowSingleQuoted() { + return allowSingleQuoted; + } + + public boolean isAllowBlock() { + return allowBlock; + } +} diff --git a/src/main/java/org/yaml/snakeyaml/env/EnvScalarConstructor.java b/src/main/java/org/yaml/snakeyaml/env/EnvScalarConstructor.java new file mode 100644 index 00000000..566f6c51 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/env/EnvScalarConstructor.java @@ -0,0 +1,132 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.env; + +import java.util.Collection; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.constructor.AbstractConstruct; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.error.MissingEnvironmentVariableException; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.Tag; + +/** + * Construct scalar for format ${VARIABLE} replacing the template with the value from environment. + * It can also be used to create JavaBeans when the all the arguments are provided. + * + * @see <a href="https://bitbucket.org/snakeyaml/snakeyaml/wiki/Variable%20substitution">Variable + * substitution</a> + * @see <a href="https://docs.docker.com/compose/compose-file/#variable-substitution">Variable + * substitution</a> + */ +public class EnvScalarConstructor extends Constructor { + + public static final Tag ENV_TAG = new Tag("!ENV"); + // name must be a word -> \w+ + // value can be any non-space -> \S+ + public static final Pattern ENV_FORMAT = Pattern + .compile("^\\$\\{\\s*((?<name>\\w+)((?<separator>:?(-|\\?))(?<value>\\S+)?)?)\\s*\\}$"); + + /** + * For simple cases when no JavaBeans are needed + */ + public EnvScalarConstructor() { + this.yamlConstructors.put(ENV_TAG, new ConstructEnv()); + } + + /** + * Create EnvScalarConstructor which can create JavaBeans with variable substitution + * + * @param theRoot - the class (usually JavaBean) to be constructed + * @param moreTDs - collection of classes used by the root class + * @param loadingConfig - configuration + */ + public EnvScalarConstructor(TypeDescription theRoot, Collection<TypeDescription> moreTDs, + LoaderOptions loadingConfig) { + super(theRoot, moreTDs, loadingConfig); + this.yamlConstructors.put(ENV_TAG, new ConstructEnv()); + } + + private class ConstructEnv extends AbstractConstruct { + + public Object construct(Node node) { + String val = constructScalar((ScalarNode) node); + Matcher matcher = ENV_FORMAT.matcher(val); + matcher.matches(); + String name = matcher.group("name"); + String value = matcher.group("value"); + String separator = matcher.group("separator"); + return apply(name, separator, value != null ? value : "", getEnv(name)); + } + } + + /** + * Implement the logic for missing and unset variables + * + * @param name - variable name in the template + * @param separator - separator in the template, can be :-, -, :?, ? + * @param value - default value or the error in the template + * @param environment - the value from environment for the provided variable + * @return the value to apply in the template + */ + public String apply(String name, String separator, String value, String environment) { + if (environment != null && !environment.isEmpty()) { + return environment; + } + // variable is either unset or empty + if (separator != null) { + // there is a default value or error + if (separator.equals("?")) { + if (environment == null) { + throw new MissingEnvironmentVariableException( + "Missing mandatory variable " + name + ": " + value); + } + } + if (separator.equals(":?")) { + if (environment == null) { + throw new MissingEnvironmentVariableException( + "Missing mandatory variable " + name + ": " + value); + } + if (environment.isEmpty()) { + throw new MissingEnvironmentVariableException( + "Empty mandatory variable " + name + ": " + value); + } + } + if (separator.startsWith(":")) { + if (environment == null || environment.isEmpty()) { + return value; + } + } else { + if (environment == null) { + return value; + } + } + } + return ""; + } + + /** + * Get value of the environment variable + * + * @param key - the name of the variable + * @return value or null if not set + */ + public String getEnv(String key) { + return System.getenv(key); + } +} diff --git a/src/main/java/org/yaml/snakeyaml/error/Mark.java b/src/main/java/org/yaml/snakeyaml/error/Mark.java index 7e1d546e..367ee6bb 100644 --- a/src/main/java/org/yaml/snakeyaml/error/Mark.java +++ b/src/main/java/org/yaml/snakeyaml/error/Mark.java @@ -1,132 +1,161 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.error; +import java.io.Serializable; import org.yaml.snakeyaml.scanner.Constant; /** - * It's just a record and its only use is producing nice error messages. Parser - * does not use it for any other purposes. + * It's just a record and its only use is producing nice error messages. Parser does not use it for + * any other purposes. */ -public final class Mark { - private String name; - private int index; - private int line; - private int column; - private String buffer; - private int pointer; - - public Mark(String name, int index, int line, int column, String buffer, int pointer) { - super(); - this.name = name; - this.index = index; - this.line = line; - this.column = column; - this.buffer = buffer; - this.pointer = pointer; - } +public final class Mark implements Serializable { - private boolean isLineBreak(char ch) { - return Constant.NULL_OR_LINEBR.has(ch); - } + private final String name; + private final int index; + private final int line; + private final int column; + private final int[] buffer; + private final int pointer; - public String get_snippet(int indent, int max_length) { - if (buffer == null) { - return null; - } - float half = max_length / 2 - 1; - int start = pointer; - String head = ""; - while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) { - start -= 1; - if (pointer - start > half) { - head = " ... "; - start += 5; - break; - } - } - String tail = ""; - int end = pointer; - while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) { - end += 1; - if (end - pointer > half) { - tail = " ... "; - end -= 5; - break; - } - } - String snippet = buffer.substring(start, end); - StringBuilder result = new StringBuilder(); - for (int i = 0; i < indent; i++) { - result.append(" "); - } - result.append(head); - result.append(snippet); - result.append(tail); - result.append("\n"); - for (int i = 0; i < indent + pointer - start + head.length(); i++) { - result.append(" "); - } - result.append("^"); - return result.toString(); + private static int[] toCodePoints(char[] str) { + int[] codePoints = new int[Character.codePointCount(str, 0, str.length)]; + for (int i = 0, c = 0; i < str.length; c++) { + int cp = Character.codePointAt(str, i); + codePoints[c] = cp; + i += Character.charCount(cp); } + return codePoints; + } - public String get_snippet() { - return get_snippet(4, 75); - } + public Mark(String name, int index, int line, int column, char[] str, int pointer) { + this(name, index, line, column, toCodePoints(str), pointer); + } - @Override - public String toString() { - String snippet = get_snippet(); - StringBuilder where = new StringBuilder(" in "); - where.append(name); - where.append(", line "); - where.append(line + 1); - where.append(", column "); - where.append(column + 1); - if (snippet != null) { - where.append(":\n"); - where.append(snippet); - } - return where.toString(); - } + /* + * Existed in older versions but replaced with {@code char[]}-based constructor. Restored in v1.22 + * for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link Mark#Mark(String, int, int, int, char[], int)}. + */ + @Deprecated + public Mark(String name, int index, int line, int column, String buffer, int pointer) { + this(name, index, line, column, buffer.toCharArray(), pointer); + } - public String getName() { - return name; - } + public Mark(String name, int index, int line, int column, int[] buffer, int pointer) { + super(); + this.name = name; + this.index = index; + this.line = line; + this.column = column; + this.buffer = buffer; + this.pointer = pointer; + } - /** - * starts with 0 - */ - public int getLine() { - return line; - } + private boolean isLineBreak(int c) { + return Constant.NULL_OR_LINEBR.has(c); + } - /** - * starts with 0 - */ - public int getColumn() { - return column; + public String get_snippet(int indent, int max_length) { + float half = max_length / 2f - 1f; + int start = pointer; + String head = ""; + while ((start > 0) && !isLineBreak(buffer[start - 1])) { + start -= 1; + if (pointer - start > half) { + head = " ... "; + start += 5; + break; + } + } + String tail = ""; + int end = pointer; + while ((end < buffer.length) && !isLineBreak(buffer[end])) { + end += 1; + if (end - pointer > half) { + tail = " ... "; + end -= 5; + break; + } } - /** - * starts with 0 - */ - public int getIndex() { - return index; + StringBuilder result = new StringBuilder(); + for (int i = 0; i < indent; i++) { + result.append(" "); + } + result.append(head); + for (int i = start; i < end; i++) { + result.appendCodePoint(buffer[i]); } + result.append(tail); + result.append("\n"); + for (int i = 0; i < indent + pointer - start + head.length(); i++) { + result.append(" "); + } + result.append("^"); + return result.toString(); + } + + public String get_snippet() { + return get_snippet(4, 75); + } + + @Override + public String toString() { + String snippet = get_snippet(); + String builder = + " in " + name + ", line " + (line + 1) + ", column " + (column + 1) + ":\n" + snippet; + return builder; + } + + public String getName() { + return name; + } + + /** + * starts with 0 + * + * @return line number + */ + public int getLine() { + return line; + } + + /** + * starts with 0 + * + * @return column number + */ + public int getColumn() { + return column; + } + + /** + * starts with 0 + * + * @return character number + */ + public int getIndex() { + return index; + } + + public int[] getBuffer() { + return buffer; + } + public int getPointer() { + return pointer; + } } diff --git a/src/main/java/org/yaml/snakeyaml/error/MarkedYAMLException.java b/src/main/java/org/yaml/snakeyaml/error/MarkedYAMLException.java index 4e44ab9b..1e94902e 100644 --- a/src/main/java/org/yaml/snakeyaml/error/MarkedYAMLException.java +++ b/src/main/java/org/yaml/snakeyaml/error/MarkedYAMLException.java @@ -1,101 +1,99 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.error; public class MarkedYAMLException extends YAMLException { - private static final long serialVersionUID = -9119388488683035101L; - private String context; - private Mark contextMark; - private String problem; - private Mark problemMark; - private String note; + private static final long serialVersionUID = -9119388488683035101L; + private final String context; + private final Mark contextMark; + private final String problem; + private final Mark problemMark; + private final String note; - protected MarkedYAMLException(String context, Mark contextMark, String problem, - Mark problemMark, String note) { - this(context, contextMark, problem, problemMark, note, null); - } + protected MarkedYAMLException(String context, Mark contextMark, String problem, Mark problemMark, + String note) { + this(context, contextMark, problem, problemMark, note, null); + } - protected MarkedYAMLException(String context, Mark contextMark, String problem, - Mark problemMark, String note, Throwable cause) { - super(context + "; " + problem + "; " + problemMark, cause); - this.context = context; - this.contextMark = contextMark; - this.problem = problem; - this.problemMark = problemMark; - this.note = note; - } + protected MarkedYAMLException(String context, Mark contextMark, String problem, Mark problemMark, + String note, Throwable cause) { + super(context + "; " + problem + "; " + problemMark, cause); + this.context = context; + this.contextMark = contextMark; + this.problem = problem; + this.problemMark = problemMark; + this.note = note; + } - protected MarkedYAMLException(String context, Mark contextMark, String problem, Mark problemMark) { - this(context, contextMark, problem, problemMark, null, null); - } + protected MarkedYAMLException(String context, Mark contextMark, String problem, + Mark problemMark) { + this(context, contextMark, problem, problemMark, null, null); + } - protected MarkedYAMLException(String context, Mark contextMark, String problem, - Mark problemMark, Throwable cause) { - this(context, contextMark, problem, problemMark, null, cause); - } + protected MarkedYAMLException(String context, Mark contextMark, String problem, Mark problemMark, + Throwable cause) { + this(context, contextMark, problem, problemMark, null, cause); + } - @Override - public String getMessage() { - return toString(); - } + @Override + public String getMessage() { + return toString(); + } - @Override - public String toString() { - StringBuilder lines = new StringBuilder(); - if (context != null) { - lines.append(context); - lines.append("\n"); - } - if (contextMark != null - && (problem == null || problemMark == null - || contextMark.getName().equals(problemMark.getName()) - || (contextMark.getLine() != problemMark.getLine()) || (contextMark - .getColumn() != problemMark.getColumn()))) { - lines.append(contextMark.toString()); - lines.append("\n"); - } - if (problem != null) { - lines.append(problem); - lines.append("\n"); - } - if (problemMark != null) { - lines.append(problemMark.toString()); - lines.append("\n"); - } - if (note != null) { - lines.append(note); - lines.append("\n"); - } - return lines.toString(); + @Override + public String toString() { + StringBuilder lines = new StringBuilder(); + if (context != null) { + lines.append(context); + lines.append("\n"); } - - public String getContext() { - return context; + if (contextMark != null && (problem == null || problemMark == null + || contextMark.getName().equals(problemMark.getName()) + || (contextMark.getLine() != problemMark.getLine()) + || (contextMark.getColumn() != problemMark.getColumn()))) { + lines.append(contextMark); + lines.append("\n"); } - - public Mark getContextMark() { - return contextMark; + if (problem != null) { + lines.append(problem); + lines.append("\n"); } - - public String getProblem() { - return problem; + if (problemMark != null) { + lines.append(problemMark); + lines.append("\n"); } - - public Mark getProblemMark() { - return problemMark; + if (note != null) { + lines.append(note); + lines.append("\n"); } + return lines.toString(); + } + + public String getContext() { + return context; + } + + public Mark getContextMark() { + return contextMark; + } + + public String getProblem() { + return problem; + } + + public Mark getProblemMark() { + return problemMark; + } } diff --git a/src/main/java/org/yaml/snakeyaml/error/MissingEnvironmentVariableException.java b/src/main/java/org/yaml/snakeyaml/error/MissingEnvironmentVariableException.java new file mode 100644 index 00000000..382c949d --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/error/MissingEnvironmentVariableException.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.error; + +/** + * Indicate missing mandatory environment variable in the template Used by EnvScalarConstructor + */ +public class MissingEnvironmentVariableException extends YAMLException { + + public MissingEnvironmentVariableException(String message) { + super(message); + } +} diff --git a/src/main/java/org/yaml/snakeyaml/error/YAMLException.java b/src/main/java/org/yaml/snakeyaml/error/YAMLException.java index af7189b3..f712f229 100644 --- a/src/main/java/org/yaml/snakeyaml/error/YAMLException.java +++ b/src/main/java/org/yaml/snakeyaml/error/YAMLException.java @@ -1,32 +1,31 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.error; public class YAMLException extends RuntimeException { - private static final long serialVersionUID = -4738336175050337570L; - public YAMLException(String message) { - super(message); - } + private static final long serialVersionUID = -4738336175050337570L; - public YAMLException(Throwable cause) { - super(cause); - } + public YAMLException(String message) { + super(message); + } - public YAMLException(String message, Throwable cause) { - super(message, cause); - } + public YAMLException(Throwable cause) { + super(cause); + } + + public YAMLException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/AliasEvent.java b/src/main/java/org/yaml/snakeyaml/events/AliasEvent.java index e0dcf7f8..75f2fb4c 100644 --- a/src/main/java/org/yaml/snakeyaml/events/AliasEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/AliasEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -21,12 +19,16 @@ import org.yaml.snakeyaml.error.Mark; * Marks the inclusion of a previously anchored node. */ public final class AliasEvent extends NodeEvent { - public AliasEvent(String anchor, Mark startMark, Mark endMark) { - super(anchor, startMark, endMark); - } - @Override - public boolean is(Event.ID id) { - return ID.Alias == id; + public AliasEvent(String anchor, Mark startMark, Mark endMark) { + super(anchor, startMark, endMark); + if (anchor == null) { + throw new NullPointerException("anchor is not specified for alias"); } + } + + @Override + public Event.ID getEventId() { + return ID.Alias; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/CollectionEndEvent.java b/src/main/java/org/yaml/snakeyaml/events/CollectionEndEvent.java index b36f32c3..d9135b5e 100644 --- a/src/main/java/org/yaml/snakeyaml/events/CollectionEndEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/CollectionEndEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -22,7 +20,7 @@ import org.yaml.snakeyaml.error.Mark; */ public abstract class CollectionEndEvent extends Event { - public CollectionEndEvent(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public CollectionEndEvent(Mark startMark, Mark endMark) { + super(startMark, endMark); + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/CollectionStartEvent.java b/src/main/java/org/yaml/snakeyaml/events/CollectionStartEvent.java index 9a772996..e03e514a 100644 --- a/src/main/java/org/yaml/snakeyaml/events/CollectionStartEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/CollectionStartEvent.java @@ -1,73 +1,91 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** * Base class for the start events of the collection nodes. */ public abstract class CollectionStartEvent extends NodeEvent { - private final String tag; - // The implicit flag of a collection start event indicates if the tag may be - // omitted when the collection is emitted - private final boolean implicit; - // flag indicates if a collection is block or flow - private final Boolean flowStyle; - public CollectionStartEvent(String anchor, String tag, boolean implicit, Mark startMark, - Mark endMark, Boolean flowStyle) { - super(anchor, startMark, endMark); - this.tag = tag; - this.implicit = implicit; - this.flowStyle = flowStyle; - } + private final String tag; + // The implicit flag of a collection start event indicates if the tag may be + // omitted when the collection is emitted + private final boolean implicit; + // flag indicates if a collection is block or flow + private final DumperOptions.FlowStyle flowStyle; - /** - * Tag of this collection. - * - * @return The tag of this collection, or <code>null</code> if no explicit - * tag is available. - */ - public String getTag() { - return this.tag; + public CollectionStartEvent(String anchor, String tag, boolean implicit, Mark startMark, + Mark endMark, DumperOptions.FlowStyle flowStyle) { + super(anchor, startMark, endMark); + this.tag = tag; + this.implicit = implicit; + if (flowStyle == null) { + throw new NullPointerException("Flow style must be provided."); } + this.flowStyle = flowStyle; + } - /** - * <code>true</code> if the tag can be omitted while this collection is - * emitted. - * - * @return True if the tag can be omitted while this collection is emitted. - */ - public boolean getImplicit() { - return this.implicit; - } + /* + * Existed in older versions but replaced with {@link DumperOptions.FlowStyle}-based constructor. + * Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link + * CollectionStartEvent#CollectionStartEvent(String, String, boolean, Mark, Mark, + * org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public CollectionStartEvent(String anchor, String tag, boolean implicit, Mark startMark, + Mark endMark, Boolean flowStyle) { + this(anchor, tag, implicit, startMark, endMark, DumperOptions.FlowStyle.fromBoolean(flowStyle)); + } - /** - * <code>true</code> if this collection is in flow style, <code>false</code> - * for block style. - * - * @return If this collection is in flow style. - */ - public Boolean getFlowStyle() { - return this.flowStyle; - } + /** + * Tag of this collection. + * + * @return The tag of this collection, or <code>null</code> if no explicit tag is available. + */ + public String getTag() { + return this.tag; + } - @Override - protected String getArguments() { - return super.getArguments() + ", tag=" + tag + ", implicit=" + implicit; - } + /** + * <code>true</code> if the tag can be omitted while this collection is emitted. + * + * @return True if the tag can be omitted while this collection is emitted. + */ + public boolean getImplicit() { + return this.implicit; + } + + /** + * <code>true</code> if this collection is in flow style, <code>false</code> for block style. + * + * @return If this collection is in flow style. + */ + public DumperOptions.FlowStyle getFlowStyle() { + return this.flowStyle; + } + + @Override + protected String getArguments() { + return super.getArguments() + ", tag=" + tag + ", implicit=" + implicit; + } + + public boolean isFlow() { + return DumperOptions.FlowStyle.FLOW == flowStyle; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/CommentEvent.java b/src/main/java/org/yaml/snakeyaml/events/CommentEvent.java new file mode 100644 index 00000000..3b16e387 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/events/CommentEvent.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.events; + +import org.yaml.snakeyaml.comments.CommentType; +import org.yaml.snakeyaml.error.Mark; + +/** + * Marks a comment block value. + */ +public final class CommentEvent extends Event { + + private final CommentType type; + private final String value; + + public CommentEvent(CommentType type, String value, Mark startMark, Mark endMark) { + super(startMark, endMark); + if (type == null) { + throw new NullPointerException("Event Type must be provided."); + } + this.type = type; + if (value == null) { + throw new NullPointerException("Value must be provided."); + } + this.value = value; + } + + /** + * String representation of the value. + * <p> + * Without quotes and escaping. + * </p> + * + * @return Value a comment line string without the leading '#' or a blank line. + */ + public String getValue() { + return this.value; + } + + /** + * The comment type. + * + * @return the commentType. + */ + public CommentType getCommentType() { + return this.type; + } + + @Override + protected String getArguments() { + return super.getArguments() + "type=" + type + ", value=" + value; + } + + @Override + public Event.ID getEventId() { + return ID.Comment; + } + +} diff --git a/src/main/java/org/yaml/snakeyaml/events/DocumentEndEvent.java b/src/main/java/org/yaml/snakeyaml/events/DocumentEndEvent.java index 30fe439f..17cdf716 100644 --- a/src/main/java/org/yaml/snakeyaml/events/DocumentEndEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/DocumentEndEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -24,19 +22,20 @@ import org.yaml.snakeyaml.error.Mark; * </p> */ public final class DocumentEndEvent extends Event { - private final boolean explicit; - public DocumentEndEvent(Mark startMark, Mark endMark, boolean explicit) { - super(startMark, endMark); - this.explicit = explicit; - } + private final boolean explicit; - public boolean getExplicit() { - return explicit; - } + public DocumentEndEvent(Mark startMark, Mark endMark, boolean explicit) { + super(startMark, endMark); + this.explicit = explicit; + } - @Override - public boolean is(Event.ID id) { - return ID.DocumentEnd == id; - } + public boolean getExplicit() { + return explicit; + } + + @Override + public Event.ID getEventId() { + return ID.DocumentEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/DocumentStartEvent.java b/src/main/java/org/yaml/snakeyaml/events/DocumentStartEvent.java index fa24cdfb..0eab4322 100644 --- a/src/main/java/org/yaml/snakeyaml/events/DocumentStartEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/DocumentStartEvent.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; import java.util.Map; - import org.yaml.snakeyaml.DumperOptions.Version; import org.yaml.snakeyaml.error.Mark; @@ -27,50 +24,45 @@ import org.yaml.snakeyaml.error.Mark; * </p> */ public final class DocumentStartEvent extends Event { - private final boolean explicit; - private final Version version; - private final Map<String, String> tags; - public DocumentStartEvent(Mark startMark, Mark endMark, boolean explicit, Version version, - Map<String, String> tags) { - super(startMark, endMark); - this.explicit = explicit; - this.version = version; - // TODO enforce not null - // if (tags == null) { - // throw new NullPointerException("Tags must be provided."); - // } - this.tags = tags; - } + private final boolean explicit; + private final Version version; + private final Map<String, String> tags; + + public DocumentStartEvent(Mark startMark, Mark endMark, boolean explicit, Version version, + Map<String, String> tags) { + super(startMark, endMark); + this.explicit = explicit; + this.version = version; + this.tags = tags; + } - public boolean getExplicit() { - return explicit; - } + public boolean getExplicit() { + return explicit; + } - /** - * YAML version the document conforms to. - * - * @return <code>null</code>if the document has no explicit - * <code>%YAML</code> directive. Otherwise an array with two - * components, the major and minor part of the version (in this - * order). - */ - public Version getVersion() { - return version; - } + /** + * YAML version the document conforms to. + * + * @return <code>null</code>if the document has no explicit <code>%YAML</code> directive. + * Otherwise an array with two components, the major and minor part of the version (in + * this order). + */ + public Version getVersion() { + return version; + } - /** - * Tag shorthands as defined by the <code>%TAG</code> directive. - * - * @return Mapping of 'handles' to 'prefixes' (the handles include the '!' - * characters). - */ - public Map<String, String> getTags() { - return tags; - } + /** + * Tag shorthands as defined by the <code>%TAG</code> directive. + * + * @return Mapping of 'handles' to 'prefixes' (the handles include the '!' characters). + */ + public Map<String, String> getTags() { + return tags; + } - @Override - public boolean is(Event.ID id) { - return ID.DocumentStart == id; - } + @Override + public Event.ID getEventId() { + return ID.DocumentStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/Event.java b/src/main/java/org/yaml/snakeyaml/events/Event.java index 4ebfa921..62c85b6e 100644 --- a/src/main/java/org/yaml/snakeyaml/events/Event.java +++ b/src/main/java/org/yaml/snakeyaml/events/Event.java @@ -1,77 +1,94 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; import org.yaml.snakeyaml.error.Mark; /** - * Basic unit of output from a {@link org.yaml.snakeyaml.parser.Parser} or input - * of a {@link org.yaml.snakeyaml.emitter.Emitter}. + * Basic unit of output from a {@link org.yaml.snakeyaml.parser.Parser} or input of a + * {@link org.yaml.snakeyaml.emitter.Emitter}. */ public abstract class Event { - public enum ID { - Alias, DocumentEnd, DocumentStart, MappingEnd, MappingStart, Scalar, SequenceEnd, SequenceStart, StreamEnd, StreamStart - } - private final Mark startMark; - private final Mark endMark; + public enum ID { + Alias, Comment, DocumentEnd, DocumentStart, MappingEnd, MappingStart, Scalar, SequenceEnd, SequenceStart, StreamEnd, StreamStart + } - public Event(Mark startMark, Mark endMark) { - this.startMark = startMark; - this.endMark = endMark; - } + private final Mark startMark; + private final Mark endMark; - public String toString() { - return "<" + this.getClass().getName() + "(" + getArguments() + ")>"; - } + public Event(Mark startMark, Mark endMark) { + this.startMark = startMark; + this.endMark = endMark; + } - public Mark getStartMark() { - return startMark; - } + public String toString() { + return "<" + this.getClass().getName() + "(" + getArguments() + ")>"; + } - public Mark getEndMark() { - return endMark; - } + public Mark getStartMark() { + return startMark; + } - /** - * @see "__repr__ for Event in PyYAML" - */ - protected String getArguments() { - return ""; - } + public Mark getEndMark() { + return endMark; + } - public abstract boolean is(Event.ID id); + /** + * Generate human readable representation of the Event + * + * @see "__repr__ for Event in PyYAML" + * @return representation fore humans + */ + protected String getArguments() { + return ""; + } - /* - * for tests only - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof Event) { - return toString().equals(obj.toString()); - } else { - return false; - } - } + /** + * Check if the Event is of the provided kind + * + * @param id - the Event.ID enum + * @return true then this Event of the provided type + */ + public boolean is(Event.ID id) { + return getEventId() == id; + } - /* - * for tests only - */ - @Override - public int hashCode() { - return toString().hashCode(); + /** + * Get the type (kind) if this Event + * + * @return the ID of this Event + */ + public abstract Event.ID getEventId(); + + /* + * for tests only + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Event) { + return toString().equals(obj.toString()); + } else { + return false; } + } + + /* + * for tests only + */ + @Override + public int hashCode() { + return toString().hashCode(); + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/ImplicitTuple.java b/src/main/java/org/yaml/snakeyaml/events/ImplicitTuple.java index 86a99acc..55b7dfc9 100644 --- a/src/main/java/org/yaml/snakeyaml/events/ImplicitTuple.java +++ b/src/main/java/org/yaml/snakeyaml/events/ImplicitTuple.java @@ -1,58 +1,54 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; /** - * The implicit flag of a scalar event is a pair of boolean values that indicate - * if the tag may be omitted when the scalar is emitted in a plain and non-plain - * style correspondingly. - * + * The implicit flag of a scalar event is a pair of boolean values that indicate if the tag may be + * omitted when the scalar is emitted in a plain and non-plain style correspondingly. + * * @see <a href="http://pyyaml.org/wiki/PyYAMLDocumentation#Events">Events</a> */ public class ImplicitTuple { - private final boolean plain; - private final boolean nonPlain; - public ImplicitTuple(boolean plain, boolean nonplain) { - this.plain = plain; - this.nonPlain = nonplain; - } + private final boolean plain; + private final boolean nonPlain; + + public ImplicitTuple(boolean plain, boolean nonplain) { + this.plain = plain; + this.nonPlain = nonplain; + } - /** - * @return true when tag may be omitted when the scalar is emitted in a - * plain style. - */ - public boolean canOmitTagInPlainScalar() { - return plain; - } + /** + * @return true when tag may be omitted when the scalar is emitted in a plain style. + */ + public boolean canOmitTagInPlainScalar() { + return plain; + } - /** - * @return true when tag may be omitted when the scalar is emitted in a - * non-plain style. - */ - public boolean canOmitTagInNonPlainScalar() { - return nonPlain; - } + /** + * @return true when tag may be omitted when the scalar is emitted in a non-plain style. + */ + public boolean canOmitTagInNonPlainScalar() { + return nonPlain; + } - public boolean bothFalse() { - return !plain && !nonPlain; - } + public boolean bothFalse() { + return !plain && !nonPlain; + } - @Override - public String toString() { - return "implicit=[" + plain + ", " + nonPlain + "]"; - } + @Override + public String toString() { + return "implicit=[" + plain + ", " + nonPlain + "]"; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/MappingEndEvent.java b/src/main/java/org/yaml/snakeyaml/events/MappingEndEvent.java index 618c9163..bfa684fb 100644 --- a/src/main/java/org/yaml/snakeyaml/events/MappingEndEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/MappingEndEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -19,17 +17,17 @@ import org.yaml.snakeyaml.error.Mark; /** * Marks the end of a mapping node. - * + * * @see MappingStartEvent */ public final class MappingEndEvent extends CollectionEndEvent { - public MappingEndEvent(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public MappingEndEvent(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public boolean is(Event.ID id) { - return ID.MappingEnd == id; - } + @Override + public Event.ID getEventId() { + return ID.MappingEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/MappingStartEvent.java b/src/main/java/org/yaml/snakeyaml/events/MappingStartEvent.java index 412e4d54..fab822ef 100644 --- a/src/main/java/org/yaml/snakeyaml/events/MappingStartEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/MappingStartEvent.java @@ -1,44 +1,57 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** * Marks the beginning of a mapping node. * <p> * This event is followed by a number of key value pairs. <br> - * The pairs are not in any particular order. However, the value always directly - * follows the corresponding key. <br> + * The pairs are not in any particular order. However, the value always directly follows the + * corresponding key. <br> * After the key value pairs follows a {@link MappingEndEvent}. * </p> * <p> * There must be an even number of node events between the start and end event. * </p> - * + * * @see MappingEndEvent */ public final class MappingStartEvent extends CollectionStartEvent { - public MappingStartEvent(String anchor, String tag, boolean implicit, Mark startMark, - Mark endMark, Boolean flowStyle) { - super(anchor, tag, implicit, startMark, endMark, flowStyle); - } - @Override - public boolean is(Event.ID id) { - return ID.MappingStart == id; - } + public MappingStartEvent(String anchor, String tag, boolean implicit, Mark startMark, + Mark endMark, DumperOptions.FlowStyle flowStyle) { + super(anchor, tag, implicit, startMark, endMark, flowStyle); + } + + /* + * Existed in older versions but replaced with {@link DumperOptions.FlowStyle}-based constructor. + * Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link MappingStartEvent#CollectionStartEvent(String, + * String, boolean, Mark, Mark, org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public MappingStartEvent(String anchor, String tag, boolean implicit, Mark startMark, + Mark endMark, Boolean flowStyle) { + this(anchor, tag, implicit, startMark, endMark, DumperOptions.FlowStyle.fromBoolean(flowStyle)); + } + + @Override + public Event.ID getEventId() { + return ID.MappingStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/NodeEvent.java b/src/main/java/org/yaml/snakeyaml/events/NodeEvent.java index f0af48b9..4db308e6 100644 --- a/src/main/java/org/yaml/snakeyaml/events/NodeEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/NodeEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -22,28 +20,27 @@ import org.yaml.snakeyaml.error.Mark; */ public abstract class NodeEvent extends Event { - private final String anchor; + private final String anchor; - public NodeEvent(String anchor, Mark startMark, Mark endMark) { - super(startMark, endMark); - this.anchor = anchor; - } + public NodeEvent(String anchor, Mark startMark, Mark endMark) { + super(startMark, endMark); + this.anchor = anchor; + } - /** - * Node anchor by which this node might later be referenced by a - * {@link AliasEvent}. - * <p> - * Note that {@link AliasEvent}s are by it self <code>NodeEvent</code>s and - * use this property to indicate the referenced anchor. - * - * @return Anchor of this node or <code>null</code> if no anchor is defined. - */ - public String getAnchor() { - return this.anchor; - } + /** + * Node anchor by which this node might later be referenced by a {@link AliasEvent}. + * <p> + * Note that {@link AliasEvent}s are by it self <code>NodeEvent</code>s and use this property to + * indicate the referenced anchor. + * + * @return Anchor of this node or <code>null</code> if no anchor is defined. + */ + public String getAnchor() { + return this.anchor; + } - @Override - protected String getArguments() { - return "anchor=" + anchor; - } + @Override + protected String getArguments() { + return "anchor=" + anchor; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/ScalarEvent.java b/src/main/java/org/yaml/snakeyaml/events/ScalarEvent.java index 7f07a62b..ed2ea0cc 100644 --- a/src/main/java/org/yaml/snakeyaml/events/ScalarEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/ScalarEvent.java @@ -1,101 +1,132 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** * Marks a scalar value. */ public final class ScalarEvent extends NodeEvent { - private final String tag; - // style flag of a scalar event indicates the style of the scalar. Possible - // values are None, '', '\'', '"', '|', '>' - private final Character style; - private final String value; - // The implicit flag of a scalar event is a pair of boolean values that - // indicate if the tag may be omitted when the scalar is emitted in a plain - // and non-plain style correspondingly. - private final ImplicitTuple implicit; - public ScalarEvent(String anchor, String tag, ImplicitTuple implicit, String value, - Mark startMark, Mark endMark, Character style) { - super(anchor, startMark, endMark); - this.tag = tag; - this.implicit = implicit; - this.value = value; - this.style = style; - } + private final String tag; + // style flag of a scalar event indicates the style of the scalar. Possible + // values are None, '', '\'', '"', '|', '>' + private final DumperOptions.ScalarStyle style; + private final String value; + // The implicit flag of a scalar event is a pair of boolean values that + // indicate if the tag may be omitted when the scalar is emitted in a plain + // and non-plain style correspondingly. + private final ImplicitTuple implicit; - /** - * Tag of this scalar. - * - * @return The tag of this scalar, or <code>null</code> if no explicit tag - * is available. - */ - public String getTag() { - return this.tag; + public ScalarEvent(String anchor, String tag, ImplicitTuple implicit, String value, + Mark startMark, Mark endMark, DumperOptions.ScalarStyle style) { + super(anchor, startMark, endMark); + this.tag = tag; + this.implicit = implicit; + if (value == null) { + throw new NullPointerException("Value must be provided."); } - - /** - * Style of the scalar. - * <dl> - * <dt>null</dt> - * <dd>Flow Style - Plain</dd> - * <dt>'\''</dt> - * <dd>Flow Style - Single-Quoted</dd> - * <dt>'"'</dt> - * <dd>Flow Style - Double-Quoted</dd> - * <dt>'|'</dt> - * <dd>Block Style - Literal</dd> - * <dt>'>'</dt> - * <dd>Block Style - Folded</dd> - * </dl> - * - * @see <a href="http://yaml.org/spec/1.1/#id864487">Kind/Style - * Combinations</a> - * @return Style of the scalar. - */ - public Character getStyle() { - return this.style; + this.value = value; + if (style == null) { + throw new NullPointerException("Style must be provided."); } + this.style = style; + } - /** - * String representation of the value. - * <p> - * Without quotes and escaping. - * </p> - * - * @return Value as Unicode string. - */ - public String getValue() { - return this.value; - } + /* + * Existed in older versions but replaced with {@link DumperOptions.ScalarStyle}-based + * constructor. Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link ScalarEvent#ScalarEvent(String, String, + * ImplicitTuple, String, Mark, Mark, org.yaml.snakeyaml.DumperOptions.ScalarStyle) }. + */ + @Deprecated + public ScalarEvent(String anchor, String tag, ImplicitTuple implicit, String value, + Mark startMark, Mark endMark, Character style) { + this(anchor, tag, implicit, value, startMark, endMark, + DumperOptions.ScalarStyle.createStyle(style)); + } - public ImplicitTuple getImplicit() { - return this.implicit; - } + /** + * Tag of this scalar. + * + * @return The tag of this scalar, or <code>null</code> if no explicit tag is available. + */ + public String getTag() { + return this.tag; + } - @Override - protected String getArguments() { - return super.getArguments() + ", tag=" + tag + ", " + implicit + ", value=" + value; - } + /** + * Style of the scalar. + * <dl> + * <dt>null</dt> + * <dd>Flow Style - Plain</dd> + * <dt>'\''</dt> + * <dd>Flow Style - Single-Quoted</dd> + * <dt>'"'</dt> + * <dd>Flow Style - Double-Quoted</dd> + * <dt>'|'</dt> + * <dd>Block Style - Literal</dd> + * <dt>'>'</dt> + * <dd>Block Style - Folded</dd> + * </dl> + * + * @see <a href="http://yaml.org/spec/1.1/#id864487">Kind/Style Combinations</a> + * @return Style of the scalar. + */ + public DumperOptions.ScalarStyle getScalarStyle() { + return this.style; + } - @Override - public boolean is(Event.ID id) { - return ID.Scalar == id; - } + /** + * @deprecated use getScalarStyle() instead + * @return char which is a value behind ScalarStyle + */ + @Deprecated + public Character getStyle() { + return this.style.getChar(); + } + + /** + * String representation of the value. + * <p> + * Without quotes and escaping. + * </p> + * + * @return Value as Unicode string. + */ + public String getValue() { + return this.value; + } + + public ImplicitTuple getImplicit() { + return this.implicit; + } + + @Override + protected String getArguments() { + return super.getArguments() + ", tag=" + tag + ", " + implicit + ", value=" + value; + } + + @Override + public Event.ID getEventId() { + return ID.Scalar; + } + + public boolean isPlain() { + return style == DumperOptions.ScalarStyle.PLAIN; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/SequenceEndEvent.java b/src/main/java/org/yaml/snakeyaml/events/SequenceEndEvent.java index a6a61275..dc1b610b 100644 --- a/src/main/java/org/yaml/snakeyaml/events/SequenceEndEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/SequenceEndEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -19,17 +17,17 @@ import org.yaml.snakeyaml.error.Mark; /** * Marks the end of a sequence. - * + * * @see SequenceStartEvent */ public final class SequenceEndEvent extends CollectionEndEvent { - public SequenceEndEvent(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public SequenceEndEvent(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public boolean is(Event.ID id) { - return ID.SequenceEnd == id; - } + @Override + public Event.ID getEventId() { + return ID.SequenceEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/SequenceStartEvent.java b/src/main/java/org/yaml/snakeyaml/events/SequenceStartEvent.java index eb7b910f..944f2e46 100644 --- a/src/main/java/org/yaml/snakeyaml/events/SequenceStartEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/SequenceStartEvent.java @@ -1,39 +1,51 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** * Marks the beginning of a sequence node. * <p> - * This event is followed by the elements contained in the sequence, and a - * {@link SequenceEndEvent}. + * This event is followed by the elements contained in the sequence, and a {@link SequenceEndEvent}. * </p> - * + * * @see SequenceEndEvent */ public final class SequenceStartEvent extends CollectionStartEvent { - public SequenceStartEvent(String anchor, String tag, boolean implicit, Mark startMark, - Mark endMark, Boolean flowStyle) { - super(anchor, tag, implicit, startMark, endMark, flowStyle); - } - @Override - public boolean is(Event.ID id) { - return ID.SequenceStart == id; - } + public SequenceStartEvent(String anchor, String tag, boolean implicit, Mark startMark, + Mark endMark, DumperOptions.FlowStyle flowStyle) { + super(anchor, tag, implicit, startMark, endMark, flowStyle); + } + + /* + * Existed in older versions but replaced with {@link DumperOptions.SequenceStyle}-based + * constructor. Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link SequenceStartEvent#SequenceStartEvent(String, + * String, boolean, Mark, Mark, org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public SequenceStartEvent(String anchor, String tag, boolean implicit, Mark startMark, + Mark endMark, Boolean flowStyle) { + this(anchor, tag, implicit, startMark, endMark, DumperOptions.FlowStyle.fromBoolean(flowStyle)); + } + + @Override + public Event.ID getEventId() { + return ID.SequenceStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/StreamEndEvent.java b/src/main/java/org/yaml/snakeyaml/events/StreamEndEvent.java index 1389c6b6..6dbb02a4 100644 --- a/src/main/java/org/yaml/snakeyaml/events/StreamEndEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/StreamEndEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -20,21 +18,21 @@ import org.yaml.snakeyaml.error.Mark; /** * Marks the end of a stream that might have contained multiple documents. * <p> - * This event is the last event that a parser emits. Together with - * {@link StreamStartEvent} (which is the first event a parser emits) they mark - * the beginning and the end of a stream of documents. + * This event is the last event that a parser emits. Together with {@link StreamStartEvent} (which + * is the first event a parser emits) they mark the beginning and the end of a stream of documents. * </p> * <p> * See {@link Event} for an exemplary output. * </p> */ public final class StreamEndEvent extends Event { - public StreamEndEvent(Mark startMark, Mark endMark) { - super(startMark, endMark); - } - @Override - public boolean is(Event.ID id) { - return ID.StreamEnd == id; - } + public StreamEndEvent(Mark startMark, Mark endMark) { + super(startMark, endMark); + } + + @Override + public Event.ID getEventId() { + return ID.StreamEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/events/StreamStartEvent.java b/src/main/java/org/yaml/snakeyaml/events/StreamStartEvent.java index 42e6c763..08dededf 100644 --- a/src/main/java/org/yaml/snakeyaml/events/StreamStartEvent.java +++ b/src/main/java/org/yaml/snakeyaml/events/StreamStartEvent.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; @@ -20,9 +18,8 @@ import org.yaml.snakeyaml.error.Mark; /** * Marks the start of a stream that might contain multiple documents. * <p> - * This event is the first event that a parser emits. Together with - * {@link StreamEndEvent} (which is the last event a parser emits) they mark the - * beginning and the end of a stream of documents. + * This event is the first event that a parser emits. Together with {@link StreamEndEvent} (which is + * the last event a parser emits) they mark the beginning and the end of a stream of documents. * </p> * <p> * See {@link Event} for an exemplary output. @@ -30,12 +27,12 @@ import org.yaml.snakeyaml.error.Mark; */ public final class StreamStartEvent extends Event { - public StreamStartEvent(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public StreamStartEvent(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public boolean is(Event.ID id) { - return ID.StreamStart == id; - } + @Override + public Event.ID getEventId() { + return ID.StreamStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java index ec8f1b69..1a722bd1 100644 --- a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java +++ b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java @@ -1,21 +1,18 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; -import java.beans.IntrospectionException; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -23,7 +20,6 @@ import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.yaml.snakeyaml.constructor.Construct; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.error.YAMLException; @@ -38,199 +34,200 @@ import org.yaml.snakeyaml.nodes.SequenceNode; * Construct a custom Java instance out of a compact object notation format. */ public class CompactConstructor extends Constructor { - private static final Pattern GUESS_COMPACT = Pattern - .compile("\\p{Alpha}.*\\s*\\((?:,?\\s*(?:(?:\\w*)|(?:\\p{Alpha}\\w*\\s*=.+))\\s*)+\\)"); - private static final Pattern FIRST_PATTERN = Pattern.compile("(\\p{Alpha}.*)(\\s*)\\((.*?)\\)"); - private static final Pattern PROPERTY_NAME_PATTERN = Pattern - .compile("\\s*(\\p{Alpha}\\w*)\\s*=(.+)"); - private Construct compactConstruct; - - protected Object constructCompactFormat(ScalarNode node, CompactData data) { - try { - Object obj = createInstance(node, data); - Map<String, Object> properties = new HashMap<String, Object>(data.getProperties()); - setProperties(obj, properties); - return obj; - } catch (Exception e) { - throw new YAMLException(e); - } + + private static final Pattern GUESS_COMPACT = Pattern + .compile("\\p{Alpha}.*\\s*\\((?:,?\\s*(?:(?:\\w*)|(?:\\p{Alpha}\\w*\\s*=.+))\\s*)+\\)"); + private static final Pattern FIRST_PATTERN = Pattern.compile("(\\p{Alpha}.*)(\\s*)\\((.*?)\\)"); + private static final Pattern PROPERTY_NAME_PATTERN = + Pattern.compile("\\s*(\\p{Alpha}\\w*)\\s*=(.+)"); + private Construct compactConstruct; + + protected Object constructCompactFormat(ScalarNode node, CompactData data) { + try { + Object obj = createInstance(node, data); + Map<String, Object> properties = new HashMap<String, Object>(data.getProperties()); + setProperties(obj, properties); + return obj; + } catch (Exception e) { + throw new YAMLException(e); + } + } + + protected Object createInstance(ScalarNode node, CompactData data) throws Exception { + Class<?> clazz = getClassForName(data.getPrefix()); + Class<?>[] args = new Class[data.getArguments().size()]; + for (int i = 0; i < args.length; i++) { + // assume all the arguments are Strings + args[i] = String.class; } + java.lang.reflect.Constructor<?> c = clazz.getDeclaredConstructor(args); + c.setAccessible(true); + return c.newInstance(data.getArguments().toArray()); - protected Object createInstance(ScalarNode node, CompactData data) throws Exception { - Class<?> clazz = getClassForName(data.getPrefix()); - Class<?>[] args = new Class[data.getArguments().size()]; - for (int i = 0; i < args.length; i++) { - // assume all the arguments are Strings - args[i] = String.class; - } - java.lang.reflect.Constructor<?> c = clazz.getDeclaredConstructor(args); - c.setAccessible(true); - return c.newInstance(data.getArguments().toArray()); + } + protected void setProperties(Object bean, Map<String, Object> data) throws Exception { + if (data == null) { + throw new NullPointerException("Data for Compact Object Notation cannot be null."); } - - protected void setProperties(Object bean, Map<String, Object> data) throws Exception { - if (data == null) { - throw new NullPointerException("Data for Compact Object Notation cannot be null."); - } - for (Map.Entry<String, Object> entry : data.entrySet()) { - String key = entry.getKey(); - Property property = getPropertyUtils().getProperty(bean.getClass(), key); - try { - property.set(bean, entry.getValue()); - } catch (IllegalArgumentException e) { - throw new YAMLException("Cannot set property='" + key + "' with value='" - + data.get(key) + "' (" + data.get(key).getClass() + ") in " + bean); - } - } + for (Map.Entry<String, Object> entry : data.entrySet()) { + String key = entry.getKey(); + Property property = getPropertyUtils().getProperty(bean.getClass(), key); + try { + property.set(bean, entry.getValue()); + } catch (IllegalArgumentException e) { + throw new YAMLException("Cannot set property='" + key + "' with value='" + data.get(key) + + "' (" + data.get(key).getClass() + ") in " + bean); + } } + } - public CompactData getCompactData(String scalar) { - if (!scalar.endsWith(")")) { - return null; - } - if (scalar.indexOf('(') < 0) { + public CompactData getCompactData(String scalar) { + if (!scalar.endsWith(")")) { + return null; + } + if (scalar.indexOf('(') < 0) { + return null; + } + Matcher m = FIRST_PATTERN.matcher(scalar); + if (m.matches()) { + String tag = m.group(1).trim(); + String content = m.group(3); + CompactData data = new CompactData(tag); + if (content.length() == 0) { + return data; + } + String[] names = content.split("\\s*,\\s*"); + for (int i = 0; i < names.length; i++) { + String section = names[i]; + if (section.indexOf('=') < 0) { + data.getArguments().add(section); + } else { + Matcher sm = PROPERTY_NAME_PATTERN.matcher(section); + if (sm.matches()) { + String name = sm.group(1); + String value = sm.group(2).trim(); + data.getProperties().put(name, value); + } else { return null; + } } - Matcher m = FIRST_PATTERN.matcher(scalar); - if (m.matches()) { - String tag = m.group(1).trim(); - String content = m.group(3); - CompactData data = new CompactData(tag); - if (content.length() == 0) - return data; - String[] names = content.split("\\s*,\\s*"); - for (int i = 0; i < names.length; i++) { - String section = names[i]; - if (section.indexOf('=') < 0) { - data.getArguments().add(section); - } else { - Matcher sm = PROPERTY_NAME_PATTERN.matcher(section); - if (sm.matches()) { - String name = sm.group(1); - String value = sm.group(2).trim(); - data.getProperties().put(name, value); - } else { - return null; - } - } - } - return data; - } - return null; + } + return data; } + return null; + } - private Construct getCompactConstruct() { - if (compactConstruct == null) { - compactConstruct = createCompactConstruct(); + private Construct getCompactConstruct() { + if (compactConstruct == null) { + compactConstruct = createCompactConstruct(); + } + return compactConstruct; + } + + protected Construct createCompactConstruct() { + return new ConstructCompactObject(); + } + + @Override + protected Construct getConstructor(Node node) { + if (node instanceof MappingNode) { + MappingNode mnode = (MappingNode) node; + List<NodeTuple> list = mnode.getValue(); + if (list.size() == 1) { + NodeTuple tuple = list.get(0); + Node key = tuple.getKeyNode(); + if (key instanceof ScalarNode) { + ScalarNode scalar = (ScalarNode) key; + if (GUESS_COMPACT.matcher(scalar.getValue()).matches()) { + return getCompactConstruct(); + } } - return compactConstruct; + } + } else if (node instanceof ScalarNode) { + ScalarNode scalar = (ScalarNode) node; + if (GUESS_COMPACT.matcher(scalar.getValue()).matches()) { + return getCompactConstruct(); + } } + return super.getConstructor(node); + } - protected Construct createCompactConstruct() { - return new ConstructCompactObject(); - } + public class ConstructCompactObject extends ConstructMapping { @Override - protected Construct getConstructor(Node node) { - if (node instanceof MappingNode) { - MappingNode mnode = (MappingNode) node; - List<NodeTuple> list = mnode.getValue(); - if (list.size() == 1) { - NodeTuple tuple = list.get(0); - Node key = tuple.getKeyNode(); - if (key instanceof ScalarNode) { - ScalarNode scalar = (ScalarNode) key; - if (GUESS_COMPACT.matcher(scalar.getValue()).matches()) { - return getCompactConstruct(); - } - } - } - } else if (node instanceof ScalarNode) { - ScalarNode scalar = (ScalarNode) node; - if (GUESS_COMPACT.matcher(scalar.getValue()).matches()) { - return getCompactConstruct(); - } - } - return super.getConstructor(node); + public void construct2ndStep(Node node, Object object) { + // Compact Object Notation may contain only one entry + MappingNode mnode = (MappingNode) node; + NodeTuple nodeTuple = mnode.getValue().iterator().next(); + + Node valueNode = nodeTuple.getValueNode(); + + if (valueNode instanceof MappingNode) { + valueNode.setType(object.getClass()); + constructJavaBean2ndStep((MappingNode) valueNode, object); + } else { + // value is a list + applySequence(object, constructSequence((SequenceNode) valueNode)); + } } - public class ConstructCompactObject extends ConstructMapping { - - @Override - public void construct2ndStep(Node node, Object object) { - // Compact Object Notation may contain only one entry - MappingNode mnode = (MappingNode) node; - NodeTuple nodeTuple = mnode.getValue().iterator().next(); - - Node valueNode = nodeTuple.getValueNode(); - - if (valueNode instanceof MappingNode) { - valueNode.setType(object.getClass()); - constructJavaBean2ndStep((MappingNode) valueNode, object); - } else { - // value is a list - applySequence(object, constructSequence((SequenceNode) valueNode)); - } - } - - /* - * MappingNode and ScalarNode end up here only they assumed to be a - * compact object's representation (@see getConstructor(Node) above) - */ - public Object construct(Node node) { - ScalarNode tmpNode = null; - if (node instanceof MappingNode) { - // Compact Object Notation may contain only one entry - MappingNode mnode = (MappingNode) node; - NodeTuple nodeTuple = mnode.getValue().iterator().next(); - node.setTwoStepsConstruction(true); - tmpNode = (ScalarNode) nodeTuple.getKeyNode(); - // return constructScalar((ScalarNode) keyNode); - } else { - tmpNode = (ScalarNode) node; - } - - CompactData data = getCompactData(tmpNode.getValue()); - if (data == null) { // TODO: Should we throw an exception here ? - return constructScalar(tmpNode); - } - return constructCompactFormat(tmpNode, data); - } + /* + * MappingNode and ScalarNode end up here only they assumed to be a compact object's + * representation (@see getConstructor(Node) above) + */ + public Object construct(Node node) { + ScalarNode tmpNode; + if (node instanceof MappingNode) { + // Compact Object Notation may contain only one entry + MappingNode mnode = (MappingNode) node; + NodeTuple nodeTuple = mnode.getValue().iterator().next(); + node.setTwoStepsConstruction(true); + tmpNode = (ScalarNode) nodeTuple.getKeyNode(); + // return constructScalar((ScalarNode) keyNode); + } else { + tmpNode = (ScalarNode) node; + } + + CompactData data = getCompactData(tmpNode.getValue()); + if (data == null) { // TODO: Should we throw an exception here ? + return constructScalar(tmpNode); + } + return constructCompactFormat(tmpNode, data); } - - protected void applySequence(Object bean, List<?> value) { - try { - Property property = getPropertyUtils().getProperty(bean.getClass(), - getSequencePropertyName(bean.getClass())); - property.set(bean, value); - } catch (Exception e) { - throw new YAMLException(e); - } + } + + protected void applySequence(Object bean, List<?> value) { + try { + Property property = + getPropertyUtils().getProperty(bean.getClass(), getSequencePropertyName(bean.getClass())); + property.set(bean, value); + } catch (Exception e) { + throw new YAMLException(e); } - - /** - * Provide the name of the property which is used when the entries form a - * sequence. The property must be a List. - * - * @throws IntrospectionException - */ - protected String getSequencePropertyName(Class<?> bean) throws IntrospectionException { - Set<Property> properties = getPropertyUtils().getProperties(bean); - for (Iterator<Property> iterator = properties.iterator(); iterator.hasNext();) { - Property property = iterator.next(); - if (!List.class.isAssignableFrom(property.getType())) { - iterator.remove(); - } - } - if (properties.size() == 0) { - throw new YAMLException("No list property found in " + bean); - } else if (properties.size() > 1) { - throw new YAMLException( - "Many list properties found in " - + bean - + "; Please override getSequencePropertyName() to specify which property to use."); - } - return properties.iterator().next().getName(); + } + + /** + * Provide the name of the property which is used when the entries form a sequence. The property + * must be a List. + * + * @param bean the class to provide exactly one List property + * @return name of the List property + */ + protected String getSequencePropertyName(Class<?> bean) { + Set<Property> properties = getPropertyUtils().getProperties(bean); + for (Iterator<Property> iterator = properties.iterator(); iterator.hasNext();) { + Property property = iterator.next(); + if (!List.class.isAssignableFrom(property.getType())) { + iterator.remove(); + } + } + if (properties.size() == 0) { + throw new YAMLException("No list property found in " + bean); + } else if (properties.size() > 1) { + throw new YAMLException("Many list properties found in " + bean + + "; Please override getSequencePropertyName() to specify which property to use."); } + return properties.iterator().next().getName(); + } } diff --git a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactData.java b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactData.java index c2da7c46..13126d80 100644 --- a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactData.java +++ b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactData.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; @@ -21,28 +19,29 @@ import java.util.List; import java.util.Map; public class CompactData { - private String prefix; - private List<String> arguments = new ArrayList<String>(); - private Map<String, String> properties = new HashMap<String, String>(); - - public CompactData(String prefix) { - this.prefix = prefix; - } - - public String getPrefix() { - return prefix; - } - - public Map<String, String> getProperties() { - return properties; - } - - public List<String> getArguments() { - return arguments; - } - - @Override - public String toString() { - return "CompactData: " + prefix + " " + properties; - } -}
\ No newline at end of file + + private final String prefix; + private final List<String> arguments = new ArrayList<String>(); + private final Map<String, String> properties = new HashMap<String, String>(); + + public CompactData(String prefix) { + this.prefix = prefix; + } + + public String getPrefix() { + return prefix; + } + + public Map<String, String> getProperties() { + return properties; + } + + public List<String> getArguments() { + return arguments; + } + + @Override + public String toString() { + return "CompactData: " + prefix + " " + properties; + } +} diff --git a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructor.java b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructor.java index e58c3add..e6b1a31a 100644 --- a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructor.java +++ b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructor.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; public class PackageCompactConstructor extends CompactConstructor { - private String packageName; - public PackageCompactConstructor(String packageName) { - this.packageName = packageName; - } + private final String packageName; + + public PackageCompactConstructor(String packageName) { + this.packageName = packageName; + } - @Override - protected Class<?> getClassForName(String name) throws ClassNotFoundException { - if (name.indexOf('.') < 0) { - try { - Class<?> clazz = Class.forName(packageName + "." + name); - return clazz; - } catch (ClassNotFoundException e) { - // use super implementation - } - } - return super.getClassForName(name); + @Override + protected Class<?> getClassForName(String name) throws ClassNotFoundException { + if (name.indexOf('.') < 0) { + try { + Class<?> clazz = Class.forName(packageName + "." + name); + return clazz; + } catch (ClassNotFoundException e) { + // use super implementation + } } + return super.getClassForName(name); + } } diff --git a/src/main/java/org/yaml/snakeyaml/external/biz/base64Coder/Base64Coder.java b/src/main/java/org/yaml/snakeyaml/external/biz/base64Coder/Base64Coder.java index 65923b65..db43b474 100644 --- a/src/main/java/org/yaml/snakeyaml/external/biz/base64Coder/Base64Coder.java +++ b/src/main/java/org/yaml/snakeyaml/external/biz/base64Coder/Base64Coder.java @@ -4,11 +4,11 @@ // This module is multi-licensed and may be used under the terms // of any of the following licenses: // -// EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal -// LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html -// GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html -// AL, Apache License, V2.0 or later, http://www.apache.org/licenses -// BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php +// EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal +// LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html +// GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html +// AL, Apache License, V2.0 or later, http://www.apache.org/licenses +// BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php // // Please contact the author if you need another license. // This module is provided "as is", without warranties of any kind. @@ -17,289 +17,265 @@ package org.yaml.snakeyaml.external.biz.base64Coder; /** * A Base64 encoder/decoder. - * + * * <p> - * This class is used to encode and decode data in Base64 format as described in - * RFC 1521. - * + * This class is used to encode and decode data in Base64 format as described in RFC 1521. + * * <p> - * Project home page: <a - * href="http://www.source-code.biz/base64coder/java/">www. + * Project home page: <a href="http://www.source-code.biz/base64coder/java/">www. * source-code.biz/base64coder/java</a><br> * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br> * Multi-licensed: EPL / LGPL / GPL / AL / BSD. */ public class Base64Coder { - // The line separator string of the operating system. - private static final String systemLineSeparator = System.getProperty("line.separator"); + // The line separator string of the operating system. + private static final String systemLineSeparator = System.getProperty("line.separator"); - // Mapping table from 6-bit nibbles to Base64 characters. - private static char[] map1 = new char[64]; - static { - int i = 0; - for (char c = 'A'; c <= 'Z'; c++) - map1[i++] = c; - for (char c = 'a'; c <= 'z'; c++) - map1[i++] = c; - for (char c = '0'; c <= '9'; c++) - map1[i++] = c; - map1[i++] = '+'; - map1[i++] = '/'; - } + // Mapping table from 6-bit nibbles to Base64 characters. + private static final char[] map1 = new char[64]; - // Mapping table from Base64 characters to 6-bit nibbles. - private static byte[] map2 = new byte[128]; - static { - for (int i = 0; i < map2.length; i++) - map2[i] = -1; - for (int i = 0; i < 64; i++) - map2[map1[i]] = (byte) i; + static { + int i = 0; + for (char c = 'A'; c <= 'Z'; c++) { + map1[i++] = c; } - - /** - * Encodes a string into Base64 format. No blanks or line breaks are - * inserted. - * - * @param s - * A String to be encoded. - * @return A String containing the Base64 encoded data. - */ - public static String encodeString(String s) { - return new String(encode(s.getBytes())); + for (char c = 'a'; c <= 'z'; c++) { + map1[i++] = c; } - - /** - * Encodes a byte array into Base 64 format and breaks the output into lines - * of 76 characters. This method is compatible with - * <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>. - * - * @param in - * An array containing the data bytes to be encoded. - * @return A String containing the Base64 encoded data, broken into lines. - */ - public static String encodeLines(byte[] in) { - return encodeLines(in, 0, in.length, 76, systemLineSeparator); + for (char c = '0'; c <= '9'; c++) { + map1[i++] = c; } + map1[i++] = '+'; + map1[i++] = '/'; + } - /** - * Encodes a byte array into Base 64 format and breaks the output into - * lines. - * - * @param in - * An array containing the data bytes to be encoded. - * @param iOff - * Offset of the first byte in <code>in</code> to be processed. - * @param iLen - * Number of bytes to be processed in <code>in</code>, starting - * at <code>iOff</code>. - * @param lineLen - * Line length for the output data. Should be a multiple of 4. - * @param lineSeparator - * The line separator to be used to separate the output lines. - * @return A String containing the Base64 encoded data, broken into lines. - */ - public static String encodeLines(byte[] in, int iOff, int iLen, int lineLen, - String lineSeparator) { - int blockLen = (lineLen * 3) / 4; - if (blockLen <= 0) - throw new IllegalArgumentException(); - int lines = (iLen + blockLen - 1) / blockLen; - int bufLen = ((iLen + 2) / 3) * 4 + lines * lineSeparator.length(); - StringBuilder buf = new StringBuilder(bufLen); - int ip = 0; - while (ip < iLen) { - int l = Math.min(iLen - ip, blockLen); - buf.append(encode(in, iOff + ip, l)); - buf.append(lineSeparator); - ip += l; - } - return buf.toString(); - } + // Mapping table from Base64 characters to 6-bit nibbles. + private static final byte[] map2 = new byte[128]; - /** - * Encodes a byte array into Base64 format. No blanks or line breaks are - * inserted in the output. - * - * @param in - * An array containing the data bytes to be encoded. - * @return A character array containing the Base64 encoded data. - */ - public static char[] encode(byte[] in) { - return encode(in, 0, in.length); + static { + for (int i = 0; i < map2.length; i++) { + map2[i] = -1; } - - /** - * Encodes a byte array into Base64 format. No blanks or line breaks are - * inserted in the output. - * - * @param in - * An array containing the data bytes to be encoded. - * @param iLen - * Number of bytes to process in <code>in</code>. - * @return A character array containing the Base64 encoded data. - */ - public static char[] encode(byte[] in, int iLen) { - return encode(in, 0, iLen); + for (int i = 0; i < 64; i++) { + map2[map1[i]] = (byte) i; } + } - /** - * Encodes a byte array into Base64 format. No blanks or line breaks are - * inserted in the output. - * - * @param in - * An array containing the data bytes to be encoded. - * @param iOff - * Offset of the first byte in <code>in</code> to be processed. - * @param iLen - * Number of bytes to process in <code>in</code>, starting at - * <code>iOff</code>. - * @return A character array containing the Base64 encoded data. - */ - public static char[] encode(byte[] in, int iOff, int iLen) { - int oDataLen = (iLen * 4 + 2) / 3; // output length without padding - int oLen = ((iLen + 2) / 3) * 4; // output length including padding - char[] out = new char[oLen]; - int ip = iOff; - int iEnd = iOff + iLen; - int op = 0; - while (ip < iEnd) { - int i0 = in[ip++] & 0xff; - int i1 = ip < iEnd ? in[ip++] & 0xff : 0; - int i2 = ip < iEnd ? in[ip++] & 0xff : 0; - int o0 = i0 >>> 2; - int o1 = ((i0 & 3) << 4) | (i1 >>> 4); - int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); - int o3 = i2 & 0x3F; - out[op++] = map1[o0]; - out[op++] = map1[o1]; - out[op] = op < oDataLen ? map1[o2] : '='; - op++; - out[op] = op < oDataLen ? map1[o3] : '='; - op++; - } - return out; - } + /** + * Encodes a string into Base64 format. No blanks or line breaks are inserted. + * + * @param s A String to be encoded. + * @return A String containing the Base64 encoded data. + */ + public static String encodeString(String s) { + return new String(encode(s.getBytes())); + } - /** - * Decodes a string from Base64 format. No blanks or line breaks are allowed - * within the Base64 encoded input data. - * - * @param s - * A Base64 String to be decoded. - * @return A String containing the decoded data. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static String decodeString(String s) { - return new String(decode(s)); - } + /** + * Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters. + * This method is compatible with <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>. + * + * @param in An array containing the data bytes to be encoded. + * @return A String containing the Base64 encoded data, broken into lines. + */ + public static String encodeLines(byte[] in) { + return encodeLines(in, 0, in.length, 76, systemLineSeparator); + } - /** - * Decodes a byte array from Base64 format and ignores line separators, tabs - * and blanks. CR, LF, Tab and Space characters are ignored in the input - * data. This method is compatible with - * <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>. - * - * @param s - * A Base64 String to be decoded. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decodeLines(String s) { - char[] buf = new char[s.length()]; - int p = 0; - for (int ip = 0; ip < s.length(); ip++) { - char c = s.charAt(ip); - if (c != ' ' && c != '\r' && c != '\n' && c != '\t') - buf[p++] = c; - } - return decode(buf, 0, p); + /** + * Encodes a byte array into Base 64 format and breaks the output into lines. + * + * @param in An array containing the data bytes to be encoded. + * @param iOff Offset of the first byte in <code>in</code> to be processed. + * @param iLen Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>. + * @param lineLen Line length for the output data. Should be a multiple of 4. + * @param lineSeparator The line separator to be used to separate the output lines. + * @return A String containing the Base64 encoded data, broken into lines. + */ + public static String encodeLines(byte[] in, int iOff, int iLen, int lineLen, + String lineSeparator) { + int blockLen = (lineLen * 3) / 4; + if (blockLen <= 0) { + throw new IllegalArgumentException(); } - - /** - * Decodes a byte array from Base64 format. No blanks or line breaks are - * allowed within the Base64 encoded input data. - * - * @param s - * A Base64 String to be decoded. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decode(String s) { - return decode(s.toCharArray()); + int lines = (iLen + blockLen - 1) / blockLen; + int bufLen = ((iLen + 2) / 3) * 4 + lines * lineSeparator.length(); + StringBuilder buf = new StringBuilder(bufLen); + int ip = 0; + while (ip < iLen) { + int l = Math.min(iLen - ip, blockLen); + buf.append(encode(in, iOff + ip, l)); + buf.append(lineSeparator); + ip += l; } + return buf.toString(); + } - /** - * Decodes a byte array from Base64 format. No blanks or line breaks are - * allowed within the Base64 encoded input data. - * - * @param in - * A character array containing the Base64 encoded data. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decode(char[] in) { - return decode(in, 0, in.length); + /** + * Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. + * + * @param in An array containing the data bytes to be encoded. + * @return A character array containing the Base64 encoded data. + */ + public static char[] encode(byte[] in) { + return encode(in, 0, in.length); + } + + /** + * Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. + * + * @param in An array containing the data bytes to be encoded. + * @param iLen Number of bytes to process in <code>in</code>. + * @return A character array containing the Base64 encoded data. + */ + public static char[] encode(byte[] in, int iLen) { + return encode(in, 0, iLen); + } + + /** + * Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. + * + * @param in An array containing the data bytes to be encoded. + * @param iOff Offset of the first byte in <code>in</code> to be processed. + * @param iLen Number of bytes to process in <code>in</code>, starting at <code>iOff</code>. + * @return A character array containing the Base64 encoded data. + */ + public static char[] encode(byte[] in, int iOff, int iLen) { + int oDataLen = (iLen * 4 + 2) / 3; // output length without padding + int oLen = ((iLen + 2) / 3) * 4; // output length including padding + char[] out = new char[oLen]; + int ip = iOff; + int iEnd = iOff + iLen; + int op = 0; + while (ip < iEnd) { + int i0 = in[ip++] & 0xff; + int i1 = ip < iEnd ? in[ip++] & 0xff : 0; + int i2 = ip < iEnd ? in[ip++] & 0xff : 0; + int o0 = i0 >>> 2; + int o1 = ((i0 & 3) << 4) | (i1 >>> 4); + int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); + int o3 = i2 & 0x3F; + out[op++] = map1[o0]; + out[op++] = map1[o1]; + out[op] = op < oDataLen ? map1[o2] : '='; + op++; + out[op] = op < oDataLen ? map1[o3] : '='; + op++; } + return out; + } - /** - * Decodes a byte array from Base64 format. No blanks or line breaks are - * allowed within the Base64 encoded input data. - * - * @param in - * A character array containing the Base64 encoded data. - * @param iOff - * Offset of the first character in <code>in</code> to be - * processed. - * @param iLen - * Number of characters to process in <code>in</code>, starting - * at <code>iOff</code>. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decode(char[] in, int iOff, int iLen) { - if (iLen % 4 != 0) - throw new IllegalArgumentException( - "Length of Base64 encoded input string is not a multiple of 4."); - while (iLen > 0 && in[iOff + iLen - 1] == '=') - iLen--; - int oLen = (iLen * 3) / 4; - byte[] out = new byte[oLen]; - int ip = iOff; - int iEnd = iOff + iLen; - int op = 0; - while (ip < iEnd) { - int i0 = in[ip++]; - int i1 = in[ip++]; - int i2 = ip < iEnd ? in[ip++] : 'A'; - int i3 = ip < iEnd ? in[ip++] : 'A'; - if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) - throw new IllegalArgumentException("Illegal character in Base64 encoded data."); - int b0 = map2[i0]; - int b1 = map2[i1]; - int b2 = map2[i2]; - int b3 = map2[i3]; - if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) - throw new IllegalArgumentException("Illegal character in Base64 encoded data."); - int o0 = (b0 << 2) | (b1 >>> 4); - int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); - int o2 = ((b2 & 3) << 6) | b3; - out[op++] = (byte) o0; - if (op < oLen) - out[op++] = (byte) o1; - if (op < oLen) - out[op++] = (byte) o2; - } - return out; + /** + * Decodes a string from Base64 format. No blanks or line breaks are allowed within the Base64 + * encoded input data. + * + * @param s A Base64 String to be decoded. + * @return A String containing the decoded data. + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. + */ + public static String decodeString(String s) { + return new String(decode(s)); + } + + /** + * Decodes a byte array from Base64 format and ignores line separators, tabs and blanks. CR, LF, + * Tab and Space characters are ignored in the input data. This method is compatible with + * <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>. + * + * @param s A Base64 String to be decoded. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. + */ + public static byte[] decodeLines(String s) { + char[] buf = new char[s.length()]; + int p = 0; + for (int ip = 0; ip < s.length(); ip++) { + char c = s.charAt(ip); + if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { + buf[p++] = c; + } } + return decode(buf, 0, p); + } + + /** + * Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 + * encoded input data. + * + * @param s A Base64 String to be decoded. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. + */ + public static byte[] decode(String s) { + return decode(s.toCharArray()); + } - // Dummy constructor. - private Base64Coder() { + /** + * Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 + * encoded input data. + * + * @param in A character array containing the Base64 encoded data. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. + */ + public static byte[] decode(char[] in) { + return decode(in, 0, in.length); + } + + /** + * Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 + * encoded input data. + * + * @param in A character array containing the Base64 encoded data. + * @param iOff Offset of the first character in <code>in</code> to be processed. + * @param iLen Number of characters to process in <code>in</code>, starting at <code>iOff</code>. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. + */ + public static byte[] decode(char[] in, int iOff, int iLen) { + if (iLen % 4 != 0) { + throw new IllegalArgumentException( + "Length of Base64 encoded input string is not a multiple of 4."); + } + while (iLen > 0 && in[iOff + iLen - 1] == '=') { + iLen--; } + int oLen = (iLen * 3) / 4; + byte[] out = new byte[oLen]; + int ip = iOff; + int iEnd = iOff + iLen; + int op = 0; + while (ip < iEnd) { + int i0 = in[ip++]; + int i1 = in[ip++]; + int i2 = ip < iEnd ? in[ip++] : 'A'; + int i3 = ip < iEnd ? in[ip++] : 'A'; + if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) { + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + } + int b0 = map2[i0]; + int b1 = map2[i1]; + int b2 = map2[i2]; + int b3 = map2[i3]; + if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) { + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + } + int o0 = (b0 << 2) | (b1 >>> 4); + int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); + int o2 = ((b2 & 3) << 6) | b3; + out[op++] = (byte) o0; + if (op < oLen) { + out[op++] = (byte) o1; + } + if (op < oLen) { + out[op++] = (byte) o2; + } + } + return out; + } + + // Dummy constructor. + private Base64Coder() {} } // end class Base64Coder diff --git a/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/Escaper.java b/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/Escaper.java index c26e3cb6..a94f6154 100644 --- a/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/Escaper.java +++ b/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/Escaper.java @@ -1,97 +1,82 @@ -/* Copyright (c) 2008 Google Inc. +/* + * Copyright (c) 2008 Google Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.external.com.google.gdata.util.common.base; /** - * An object that converts literal text into a format safe for inclusion in a - * particular context (such as an XML document). Typically (but not always), the - * inverse process of "unescaping" the text is performed automatically by the - * relevant parser. - * + * An object that converts literal text into a format safe for inclusion in a particular context + * (such as an XML document). Typically (but not always), the inverse process of "unescaping" the + * text is performed automatically by the relevant parser. + * * <p> - * For example, an XML escaper would convert the literal string - * {@code "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} - * from being confused with an XML tag. When the resulting XML document is - * parsed, the parser API will return this text as the original literal string - * {@code "Foo<Bar>"}. - * + * For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into + * {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the + * resulting XML document is parsed, the parser API will return this text as the original literal + * string {@code "Foo<Bar>"}. + * * <p> - * An {@code Escaper} instance is required to be stateless, and safe when used - * concurrently by multiple threads. - * + * An {@code Escaper} instance is required to be stateless, and safe when used concurrently by + * multiple threads. + * * <p> - * Several popular escapers are defined as constants in the class - * {@link CharEscapers}. To create your own escapers, use - * {@link CharEscaperBuilder}, or extend {@link CharEscaper} or + * Several popular escapers are defined as constants in the class {@link CharEscapers}. To create + * your own escapers, use {@link CharEscaperBuilder}, or extend {@link CharEscaper} or * {@code UnicodeEscaper}. - * - * */ public interface Escaper { - /** - * Returns the escaped form of a given literal string. - * - * <p> - * Note that this method may treat input characters differently depending on - * the specific escaper implementation. - * <ul> - * <li>{@link UnicodeEscaper} handles <a - * href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly, - * including surrogate character pairs. If the input is badly formed the - * escaper should throw {@link IllegalArgumentException}. - * <li>{@link CharEscaper} handles Java characters independently and does - * not verify the input for well formed characters. A CharEscaper should not - * be used in situations where input is not guaranteed to be restricted to - * the Basic Multilingual Plane (BMP). - * </ul> - * - * @param string - * the literal string to be escaped - * @return the escaped form of {@code string} - * @throws NullPointerException - * if {@code string} is null - * @throws IllegalArgumentException - * if {@code string} contains badly formed UTF-16 or cannot be - * escaped for any other reason - */ - public String escape(String string); - /** - * Returns an {@code Appendable} instance which automatically escapes all - * text appended to it before passing the resulting text to an underlying - * {@code Appendable}. - * - * <p> - * Note that this method may treat input characters differently depending on - * the specific escaper implementation. - * <ul> - * <li>{@link UnicodeEscaper} handles <a - * href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly, - * including surrogate character pairs. If the input is badly formed the - * escaper should throw {@link IllegalArgumentException}. - * <li>{@link CharEscaper} handles Java characters independently and does - * not verify the input for well formed characters. A CharEscaper should not - * be used in situations where input is not guaranteed to be restricted to - * the Basic Multilingual Plane (BMP). - * </ul> - * - * @param out - * the underlying {@code Appendable} to append escaped output to - * @return an {@code Appendable} which passes text to {@code out} after - * escaping it. - */ - public Appendable escape(Appendable out); + /** + * Returns the escaped form of a given literal string. + * + * <p> + * Note that this method may treat input characters differently depending on the specific escaper + * implementation. + * <ul> + * <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> + * correctly, including surrogate character pairs. If the input is badly formed the escaper should + * throw {@link IllegalArgumentException}. + * <li>{@link CharEscaper} handles Java characters independently and does not verify the input for + * well formed characters. A CharEscaper should not be used in situations where input is not + * guaranteed to be restricted to the Basic Multilingual Plane (BMP). + * </ul> + * + * @param string the literal string to be escaped + * @return the escaped form of {@code string} + * @throws NullPointerException if {@code string} is null + * @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be + * escaped for any other reason + */ + String escape(String string); + + /** + * Returns an {@code Appendable} instance which automatically escapes all text appended to it + * before passing the resulting text to an underlying {@code Appendable}. + * + * <p> + * Note that this method may treat input characters differently depending on the specific escaper + * implementation. + * <ul> + * <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> + * correctly, including surrogate character pairs. If the input is badly formed the escaper should + * throw {@link IllegalArgumentException}. + * <li>{@link CharEscaper} handles Java characters independently and does not verify the input for + * well formed characters. A CharEscaper should not be used in situations where input is not + * guaranteed to be restricted to the Basic Multilingual Plane (BMP). + * </ul> + * + * @param out the underlying {@code Appendable} to append escaped output to + * @return an {@code Appendable} which passes text to {@code out} after escaping it. + */ + Appendable escape(Appendable out); } diff --git a/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/PercentEscaper.java b/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/PercentEscaper.java index 5e2f902d..f115a2cc 100644 --- a/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/PercentEscaper.java +++ b/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/PercentEscaper.java @@ -1,281 +1,267 @@ -/* Copyright (c) 2008 Google Inc. +/* + * Copyright (c) 2008 Google Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.external.com.google.gdata.util.common.base; /** - * A {@code UnicodeEscaper} that escapes some set of Java characters using the - * URI percent encoding scheme. The set of safe characters (those which remain - * unescaped) can be specified on construction. - * + * A {@code UnicodeEscaper} that escapes some set of Java characters using the URI percent encoding + * scheme. The set of safe characters (those which remain unescaped) can be specified on + * construction. + * * <p> - * For details on escaping URIs for use in web pages, see section 2.4 of <a - * href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. - * + * For details on escaping URIs for use in web pages, see section 2.4 of + * <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. + * * <p> - * In most cases this class should not need to be used directly. If you have no - * special requirements for escaping your URIs, you should use either - * {@link CharEscapers#uriEscaper()} or {@link CharEscapers#uriEscaper(boolean)}. - * + * In most cases this class should not need to be used directly. If you have no special requirements + * for escaping your URIs, you should use either {@link CharEscapers#uriEscaper()} or + * {@link CharEscapers#uriEscaper(boolean)}. + * * <p> * When encoding a String, the following rules apply: * <ul> - * <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" - * through "9" remain the same. + * <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the + * same. * <li>Any additionally specified safe characters remain the same. - * <li>If {@code plusForSpace} was specified, the space character " " is - * converted into a plus sign "+". - * <li>All other characters are converted into one or more bytes using UTF-8 - * encoding and each byte is then represented by the 3-character string "%XY", - * where "XY" is the two-digit, uppercase, hexadecimal representation of the - * byte value. + * <li>If {@code plusForSpace} was specified, the space character " " is converted into a plus sign + * "+". + * <li>All other characters are converted into one or more bytes using UTF-8 encoding and each byte + * is then represented by the 3-character string "%XY", where "XY" is the two-digit, uppercase, + * hexadecimal representation of the byte value. * </ul> - * + * * <p> - * RFC 2396 specifies the set of unreserved characters as "-", "_", ".", "!", - * "~", "*", "'", "(" and ")". It goes on to state: - * + * RFC 2396 specifies the set of unreserved characters as "-", "_", ".", "!", "~", "*", "'", "(" and + * ")". It goes on to state: + * * <p> - * <i>Unreserved characters can be escaped without changing the semantics of the - * URI, but this should not be done unless the URI is being used in a context - * that does not allow the unescaped character to appear.</i> - * + * <i>Unreserved characters can be escaped without changing the semantics of the URI, but this + * should not be done unless the URI is being used in a context that does not allow the unescaped + * character to appear.</i> + * * <p> - * For performance reasons the only currently supported character encoding of - * this class is UTF-8. - * + * For performance reasons the only currently supported character encoding of this class is UTF-8. + * * <p> - * <b>Note</b>: This escaper produces uppercase hexidecimal sequences. From <a - * href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br> - * <i>"URI producers and normalizers should use uppercase hexadecimal digits for - * all percent-encodings."</i> - * - * + * <b>Note</b>: This escaper produces uppercase hexidecimal sequences. From + * <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br> + * <i>"URI producers and normalizers should use uppercase hexadecimal digits for all + * percent-encodings."</i> */ public class PercentEscaper extends UnicodeEscaper { - /** - * A string of safe characters that mimics the behavior of - * {@link java.net.URLEncoder}. - * - */ - public static final String SAFECHARS_URLENCODER = "-_.*"; - /** - * A string of characters that do not need to be encoded when used in URI - * path segments, as specified in RFC 3986. Note that some of these - * characters do need to be escaped when used in other parts of the URI. - */ - public static final String SAFEPATHCHARS_URLENCODER = "-_.!~*'()@:$&,;="; + /** + * A string of safe characters that mimics the behavior of {@link java.net.URLEncoder}. + */ + public static final String SAFECHARS_URLENCODER = "-_.*"; - /** - * A string of characters that do not need to be encoded when used in URI - * query strings, as specified in RFC 3986. Note that some of these - * characters do need to be escaped when used in other parts of the URI. - */ - public static final String SAFEQUERYSTRINGCHARS_URLENCODER = "-_.!~*'()@:$,;/?:"; + /** + * A string of characters that do not need to be encoded when used in URI path segments, as + * specified in RFC 3986. Note that some of these characters do need to be escaped when used in + * other parts of the URI. + */ + public static final String SAFEPATHCHARS_URLENCODER = "-_.!~*'()@:$&,;="; - // In some uri escapers spaces are escaped to '+' - private static final char[] URI_ESCAPED_SPACE = { '+' }; + /** + * A string of characters that do not need to be encoded when used in URI query strings, as + * specified in RFC 3986. Note that some of these characters do need to be escaped when used in + * other parts of the URI. + */ + public static final String SAFEQUERYSTRINGCHARS_URLENCODER = "-_.!~*'()@:$,;/?:"; - private static final char[] UPPER_HEX_DIGITS = "0123456789ABCDEF".toCharArray(); + // In some uri escapers spaces are escaped to '+' + private static final char[] URI_ESCAPED_SPACE = {'+'}; - /** - * If true we should convert space to the {@code +} character. - */ - private final boolean plusForSpace; + private static final char[] UPPER_HEX_DIGITS = "0123456789ABCDEF".toCharArray(); - /** - * An array of flags where for any {@code char c} if {@code safeOctets[c]} - * is true then {@code c} should remain unmodified in the output. If - * {@code c > safeOctets.length} then it should be escaped. - */ - private final boolean[] safeOctets; + /** + * If true we should convert space to the {@code +} character. + */ + private final boolean plusForSpace; - /** - * Constructs a URI escaper with the specified safe characters and optional - * handling of the space character. - * - * @param safeChars - * a non null string specifying additional safe characters for - * this escaper (the ranges 0..9, a..z and A..Z are always safe - * and should not be specified here) - * @param plusForSpace - * true if ASCII space should be escaped to {@code +} rather than - * {@code %20} - * @throws IllegalArgumentException - * if any of the parameters were invalid - */ - public PercentEscaper(String safeChars, boolean plusForSpace) { - // Avoid any misunderstandings about the behavior of this escaper - if (safeChars.matches(".*[0-9A-Za-z].*")) { - throw new IllegalArgumentException( - "Alphanumeric characters are always 'safe' and should not be " - + "explicitly specified"); - } - // Avoid ambiguous parameters. Safe characters are never modified so if - // space is a safe character then setting plusForSpace is meaningless. - if (plusForSpace && safeChars.contains(" ")) { - throw new IllegalArgumentException( - "plusForSpace cannot be specified when space is a 'safe' character"); - } - if (safeChars.contains("%")) { - throw new IllegalArgumentException("The '%' character cannot be specified as 'safe'"); - } - this.plusForSpace = plusForSpace; - this.safeOctets = createSafeOctets(safeChars); + /** + * An array of flags where for any {@code char c} if {@code safeOctets[c]} is true then {@code c} + * should remain unmodified in the output. If {@code c > safeOctets.length} then it should be + * escaped. + */ + private final boolean[] safeOctets; + + /** + * Constructs a URI escaper with the specified safe characters and optional handling of the space + * character. + * + * @param safeChars a non null string specifying additional safe characters for this escaper (the + * ranges 0..9, a..z and A..Z are always safe and should not be specified here) + * @param plusForSpace true if ASCII space should be escaped to {@code +} rather than {@code %20} + * @throws IllegalArgumentException if any of the parameters were invalid + */ + public PercentEscaper(String safeChars, boolean plusForSpace) { + // Avoid any misunderstandings about the behavior of this escaper + if (safeChars.matches(".*[0-9A-Za-z].*")) { + throw new IllegalArgumentException( + "Alphanumeric characters are always 'safe' and should not be " + "explicitly specified"); + } + // Avoid ambiguous parameters. Safe characters are never modified so if + // space is a safe character then setting plusForSpace is meaningless. + if (plusForSpace && safeChars.contains(" ")) { + throw new IllegalArgumentException( + "plusForSpace cannot be specified when space is a 'safe' character"); } + if (safeChars.contains("%")) { + throw new IllegalArgumentException("The '%' character cannot be specified as 'safe'"); + } + this.plusForSpace = plusForSpace; + this.safeOctets = createSafeOctets(safeChars); + } - /** - * Creates a boolean[] with entries corresponding to the character values - * for 0-9, A-Z, a-z and those specified in safeChars set to true. The array - * is as small as is required to hold the given character information. - */ - private static boolean[] createSafeOctets(String safeChars) { - int maxChar = 'z'; - char[] safeCharArray = safeChars.toCharArray(); - for (char c : safeCharArray) { - maxChar = Math.max(c, maxChar); - } - boolean[] octets = new boolean[maxChar + 1]; - for (int c = '0'; c <= '9'; c++) { - octets[c] = true; - } - for (int c = 'A'; c <= 'Z'; c++) { - octets[c] = true; - } - for (int c = 'a'; c <= 'z'; c++) { - octets[c] = true; - } - for (char c : safeCharArray) { - octets[c] = true; - } - return octets; + /** + * Creates a boolean[] with entries corresponding to the character values for 0-9, A-Z, a-z and + * those specified in safeChars set to true. The array is as small as is required to hold the + * given character information. + */ + private static boolean[] createSafeOctets(String safeChars) { + int maxChar = 'z'; + char[] safeCharArray = safeChars.toCharArray(); + for (char c : safeCharArray) { + maxChar = Math.max(c, maxChar); + } + boolean[] octets = new boolean[maxChar + 1]; + for (int c = '0'; c <= '9'; c++) { + octets[c] = true; + } + for (int c = 'A'; c <= 'Z'; c++) { + octets[c] = true; + } + for (int c = 'a'; c <= 'z'; c++) { + octets[c] = true; + } + for (char c : safeCharArray) { + octets[c] = true; } + return octets; + } - /* - * Overridden for performance. For unescaped strings this improved the - * performance of the uri escaper from ~760ns to ~400ns as measured by - * {@link CharEscapersBenchmark}. - */ - @Override - protected int nextEscapeIndex(CharSequence csq, int index, int end) { - for (; index < end; index++) { - char c = csq.charAt(index); - if (c >= safeOctets.length || !safeOctets[c]) { - break; - } - } - return index; + /* + * Overridden for performance. For unescaped strings this improved the performance of the uri + * escaper from ~760ns to ~400ns as measured by {@link CharEscapersBenchmark}. + */ + @Override + protected int nextEscapeIndex(CharSequence csq, int index, int end) { + for (; index < end; index++) { + char c = csq.charAt(index); + if (c >= safeOctets.length || !safeOctets[c]) { + break; + } } + return index; + } - /* - * Overridden for performance. For unescaped strings this improved the - * performance of the uri escaper from ~400ns to ~170ns as measured by - * {@link CharEscapersBenchmark}. - */ - @Override - public String escape(String s) { - int slen = s.length(); - for (int index = 0; index < slen; index++) { - char c = s.charAt(index); - if (c >= safeOctets.length || !safeOctets[c]) { - return escapeSlow(s, index); - } - } - return s; + /* + * Overridden for performance. For unescaped strings this improved the performance of the uri + * escaper from ~400ns to ~170ns as measured by {@link CharEscapersBenchmark}. + */ + @Override + public String escape(String s) { + int slen = s.length(); + for (int index = 0; index < slen; index++) { + char c = s.charAt(index); + if (c >= safeOctets.length || !safeOctets[c]) { + return escapeSlow(s, index); + } } + return s; + } - /** - * Escapes the given Unicode code point in UTF-8. - */ - @Override - protected char[] escape(int cp) { - // We should never get negative values here but if we do it will throw - // an - // IndexOutOfBoundsException, so at least it will get spotted. - if (cp < safeOctets.length && safeOctets[cp]) { - return null; - } else if (cp == ' ' && plusForSpace) { - return URI_ESCAPED_SPACE; - } else if (cp <= 0x7F) { - // Single byte UTF-8 characters - // Start with "%--" and fill in the blanks - char[] dest = new char[3]; - dest[0] = '%'; - dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; - dest[1] = UPPER_HEX_DIGITS[cp >>> 4]; - return dest; - } else if (cp <= 0x7ff) { - // Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff] - // Start with "%--%--" and fill in the blanks - char[] dest = new char[6]; - dest[0] = '%'; - dest[3] = '%'; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[1] = UPPER_HEX_DIGITS[0xC | cp]; - return dest; - } else if (cp <= 0xffff) { - // Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff] - // Start with "%E-%--%--" and fill in the blanks - char[] dest = new char[9]; - dest[0] = '%'; - dest[1] = 'E'; - dest[3] = '%'; - dest[6] = '%'; - dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp]; - return dest; - } else if (cp <= 0x10ffff) { - char[] dest = new char[12]; - // Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff] - // Start with "%F-%--%--%--" and fill in the blanks - dest[0] = '%'; - dest[1] = 'F'; - dest[3] = '%'; - dest[6] = '%'; - dest[9] = '%'; - dest[11] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp & 0x7]; - return dest; - } else { - // If this ever happens it is due to bug in UnicodeEscaper, not bad - // input. - throw new IllegalArgumentException("Invalid unicode character value " + cp); - } + /** + * Escapes the given Unicode code point in UTF-8. + */ + @Override + protected char[] escape(int cp) { + // We should never get negative values here but if we do it will throw + // an + // IndexOutOfBoundsException, so at least it will get spotted. + if (cp < safeOctets.length && safeOctets[cp]) { + return null; + } else if (cp == ' ' && plusForSpace) { + return URI_ESCAPED_SPACE; + } else if (cp <= 0x7F) { + // Single byte UTF-8 characters + // Start with "%--" and fill in the blanks + char[] dest = new char[3]; + dest[0] = '%'; + dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; + dest[1] = UPPER_HEX_DIGITS[cp >>> 4]; + return dest; + } else if (cp <= 0x7ff) { + // Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff] + // Start with "%--%--" and fill in the blanks + char[] dest = new char[6]; + dest[0] = '%'; + dest[3] = '%'; + dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[1] = UPPER_HEX_DIGITS[0xC | cp]; + return dest; + } else if (cp <= 0xffff) { + // Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff] + // Start with "%E-%--%--" and fill in the blanks + char[] dest = new char[9]; + dest[0] = '%'; + dest[1] = 'E'; + dest[3] = '%'; + dest[6] = '%'; + dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[2] = UPPER_HEX_DIGITS[cp]; + return dest; + } else if (cp <= 0x10ffff) { + char[] dest = new char[12]; + // Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff] + // Start with "%F-%--%--%--" and fill in the blanks + dest[0] = '%'; + dest[1] = 'F'; + dest[3] = '%'; + dest[6] = '%'; + dest[9] = '%'; + dest[11] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; + cp >>>= 4; + dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; + cp >>>= 2; + dest[2] = UPPER_HEX_DIGITS[cp & 0x7]; + return dest; + } else { + // If this ever happens it is due to bug in UnicodeEscaper, not bad + // input. + throw new IllegalArgumentException("Invalid unicode character value " + cp); } + } } diff --git a/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/UnicodeEscaper.java b/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/UnicodeEscaper.java index 54031850..00230df8 100644 --- a/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/UnicodeEscaper.java +++ b/src/main/java/org/yaml/snakeyaml/external/com/google/gdata/util/common/base/UnicodeEscaper.java @@ -1,16 +1,15 @@ -/* Copyright (c) 2008 Google Inc. +/* + * Copyright (c) 2008 Google Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.external.com.google.gdata.util.common.base; @@ -18,489 +17,446 @@ package org.yaml.snakeyaml.external.com.google.gdata.util.common.base; import java.io.IOException; /** - * An {@link Escaper} that converts literal text into a format safe for - * inclusion in a particular context (such as an XML document). Typically (but - * not always), the inverse process of "unescaping" the text is performed - * automatically by the relevant parser. - * + * An {@link Escaper} that converts literal text into a format safe for inclusion in a particular + * context (such as an XML document). Typically (but not always), the inverse process of + * "unescaping" the text is performed automatically by the relevant parser. + * * <p> - * For example, an XML escaper would convert the literal string - * {@code "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} - * from being confused with an XML tag. When the resulting XML document is - * parsed, the parser API will return this text as the original literal string - * {@code "Foo<Bar>"}. - * + * For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into + * {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the + * resulting XML document is parsed, the parser API will return this text as the original literal + * string {@code "Foo<Bar>"}. + * * <p> - * <b>Note:</b> This class is similar to {@link CharEscaper} but with one very - * important difference. A CharEscaper can only process Java <a - * href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in isolation - * and may not cope when it encounters surrogate pairs. This class facilitates - * the correct escaping of all Unicode characters. - * + * <b>Note:</b> This class is similar to {@link CharEscaper} but with one very important difference. + * A CharEscaper can only process Java <a href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> + * characters in isolation and may not cope when it encounters surrogate pairs. This class + * facilitates the correct escaping of all Unicode characters. + * * <p> - * As there are important reasons, including potential security issues, to - * handle Unicode correctly if you are considering implementing a new escaper - * you should favor using UnicodeEscaper wherever possible. - * + * As there are important reasons, including potential security issues, to handle Unicode correctly + * if you are considering implementing a new escaper you should favor using UnicodeEscaper wherever + * possible. + * * <p> - * A {@code UnicodeEscaper} instance is required to be stateless, and safe when - * used concurrently by multiple threads. - * + * A {@code UnicodeEscaper} instance is required to be stateless, and safe when used concurrently by + * multiple threads. + * * <p> - * Several popular escapers are defined as constants in the class - * {@link CharEscapers}. To create your own escapers extend this class and - * implement the {@link #escape(int)} method. - * - * + * Several popular escapers are defined as constants in the class {@link CharEscapers}. To create + * your own escapers extend this class and implement the {@link #escape(int)} method. */ public abstract class UnicodeEscaper implements Escaper { - /** The amount of padding (chars) to use when growing the escape buffer. */ - private static final int DEST_PAD = 32; - /** - * Returns the escaped form of the given Unicode code point, or {@code null} - * if this code point does not need to be escaped. When called as part of an - * escaping operation, the given code point is guaranteed to be in the range - * {@code 0 <= cp <= Character#MAX_CODE_POINT}. - * - * <p> - * If an empty array is returned, this effectively strips the input - * character from the resulting text. - * - * <p> - * If the character does not need to be escaped, this method should return - * {@code null}, rather than an array containing the character - * representation of the code point. This enables the escaping algorithm to - * perform more efficiently. - * - * <p> - * If the implementation of this method cannot correctly handle a particular - * code point then it should either throw an appropriate runtime exception - * or return a suitable replacement character. It must never silently - * discard invalid input as this may constitute a security risk. - * - * @param cp - * the Unicode code point to escape if necessary - * @return the replacement characters, or {@code null} if no escaping was - * needed - */ - protected abstract char[] escape(int cp); + /** + * The amount of padding (chars) to use when growing the escape buffer. + */ + private static final int DEST_PAD = 32; - /** - * Scans a sub-sequence of characters from a given {@link CharSequence}, - * returning the index of the next character that requires escaping. - * - * <p> - * <b>Note:</b> When implementing an escaper, it is a good idea to override - * this method for efficiency. The base class implementation determines - * successive Unicode code points and invokes {@link #escape(int)} for each - * of them. If the semantics of your escaper are such that code points in - * the supplementary range are either all escaped or all unescaped, this - * method can be implemented more efficiently using - * {@link CharSequence#charAt(int)}. - * - * <p> - * Note however that if your escaper does not escape characters in the - * supplementary range, you should either continue to validate the - * correctness of any surrogate characters encountered or provide a clear - * warning to users that your escaper does not validate its input. - * - * <p> - * See {@link PercentEscaper} for an example. - * - * @param csq - * a sequence of characters - * @param start - * the index of the first character to be scanned - * @param end - * the index immediately after the last character to be scanned - * @throws IllegalArgumentException - * if the scanned sub-sequence of {@code csq} contains invalid - * surrogate pairs - */ - protected int nextEscapeIndex(CharSequence csq, int start, int end) { - int index = start; - while (index < end) { - int cp = codePointAt(csq, index, end); - if (cp < 0 || escape(cp) != null) { - break; - } - index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; - } - return index; - } + /** + * Returns the escaped form of the given Unicode code point, or {@code null} if this code point + * does not need to be escaped. When called as part of an escaping operation, the given code point + * is guaranteed to be in the range {@code 0 <= cp <= Character#MAX_CODE_POINT}. + * + * <p> + * If an empty array is returned, this effectively strips the input character from the resulting + * text. + * + * <p> + * If the character does not need to be escaped, this method should return {@code null}, rather + * than an array containing the character representation of the code point. This enables the + * escaping algorithm to perform more efficiently. + * + * <p> + * If the implementation of this method cannot correctly handle a particular code point then it + * should either throw an appropriate runtime exception or return a suitable replacement + * character. It must never silently discard invalid input as this may constitute a security risk. + * + * @param cp the Unicode code point to escape if necessary + * @return the replacement characters, or {@code null} if no escaping was needed + */ + protected abstract char[] escape(int cp); - /** - * Returns the escaped form of a given literal string. - * - * <p> - * If you are escaping input in arbitrary successive chunks, then it is not - * generally safe to use this method. If an input string ends with an - * unmatched high surrogate character, then this method will throw - * {@link IllegalArgumentException}. You should either ensure your input is - * valid <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before - * calling this method or use an escaped {@link Appendable} (as returned by - * {@link #escape(Appendable)}) which can cope with arbitrarily split input. - * - * <p> - * <b>Note:</b> When implementing an escaper it is a good idea to override - * this method for efficiency by inlining the implementation of - * {@link #nextEscapeIndex(CharSequence, int, int)} directly. Doing this for - * {@link PercentEscaper} more than doubled the performance for unescaped - * strings (as measured by {@link CharEscapersBenchmark}). - * - * @param string - * the literal string to be escaped - * @return the escaped form of {@code string} - * @throws NullPointerException - * if {@code string} is null - * @throws IllegalArgumentException - * if invalid surrogate characters are encountered - */ - public String escape(String string) { - int end = string.length(); - int index = nextEscapeIndex(string, 0, end); - return index == end ? string : escapeSlow(string, index); + /** + * Scans a sub-sequence of characters from a given {@link CharSequence}, returning the index of + * the next character that requires escaping. + * + * <p> + * <b>Note:</b> When implementing an escaper, it is a good idea to override this method for + * efficiency. The base class implementation determines successive Unicode code points and invokes + * {@link #escape(int)} for each of them. If the semantics of your escaper are such that code + * points in the supplementary range are either all escaped or all unescaped, this method can be + * implemented more efficiently using {@link CharSequence#charAt(int)}. + * + * <p> + * Note however that if your escaper does not escape characters in the supplementary range, you + * should either continue to validate the correctness of any surrogate characters encountered or + * provide a clear warning to users that your escaper does not validate its input. + * + * <p> + * See {@link PercentEscaper} for an example. + * + * @param csq a sequence of characters + * @param start the index of the first character to be scanned + * @param end the index immediately after the last character to be scanned + * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} contains invalid + * surrogate pairs + */ + protected int nextEscapeIndex(CharSequence csq, int start, int end) { + int index = start; + while (index < end) { + int cp = codePointAt(csq, index, end); + if (cp < 0 || escape(cp) != null) { + break; + } + index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; } + return index; + } - /** - * Returns the escaped form of a given literal string, starting at the given - * index. This method is called by the {@link #escape(String)} method when - * it discovers that escaping is required. It is protected to allow - * subclasses to override the fastpath escaping function to inline their - * escaping test. See {@link CharEscaperBuilder} for an example usage. - * - * <p> - * This method is not reentrant and may only be invoked by the top level - * {@link #escape(String)} method. - * - * @param s - * the literal string to be escaped - * @param index - * the index to start escaping from - * @return the escaped form of {@code string} - * @throws NullPointerException - * if {@code string} is null - * @throws IllegalArgumentException - * if invalid surrogate characters are encountered - */ - protected final String escapeSlow(String s, int index) { - int end = s.length(); + /** + * Returns the escaped form of a given literal string. + * + * <p> + * If you are escaping input in arbitrary successive chunks, then it is not generally safe to use + * this method. If an input string ends with an unmatched high surrogate character, then this + * method will throw {@link IllegalArgumentException}. You should either ensure your input is + * valid <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before calling this method or + * use an escaped {@link Appendable} (as returned by {@link #escape(Appendable)}) which can cope + * with arbitrarily split input. + * + * <p> + * <b>Note:</b> When implementing an escaper it is a good idea to override this method for + * efficiency by inlining the implementation of {@link #nextEscapeIndex(CharSequence, int, int)} + * directly. Doing this for {@link PercentEscaper} more than doubled the performance for unescaped + * strings (as measured by {@link CharEscapersBenchmark}). + * + * @param string the literal string to be escaped + * @return the escaped form of {@code string} + * @throws NullPointerException if {@code string} is null + * @throws IllegalArgumentException if invalid surrogate characters are encountered + */ + public String escape(String string) { + int end = string.length(); + int index = nextEscapeIndex(string, 0, end); + return index == end ? string : escapeSlow(string, index); + } - // Get a destination buffer and setup some loop variables. - char[] dest = DEST_TL.get(); - int destIndex = 0; - int unescapedChunkStart = 0; + /** + * Returns the escaped form of a given literal string, starting at the given index. This method is + * called by the {@link #escape(String)} method when it discovers that escaping is required. It is + * protected to allow subclasses to override the fastpath escaping function to inline their + * escaping test. See {@link CharEscaperBuilder} for an example usage. + * + * <p> + * This method is not reentrant and may only be invoked by the top level {@link #escape(String)} + * method. + * + * @param s the literal string to be escaped + * @param index the index to start escaping from + * @return the escaped form of {@code string} + * @throws NullPointerException if {@code string} is null + * @throws IllegalArgumentException if invalid surrogate characters are encountered + */ + protected final String escapeSlow(String s, int index) { + int end = s.length(); - while (index < end) { - int cp = codePointAt(s, index, end); - if (cp < 0) { - throw new IllegalArgumentException("Trailing high surrogate at end of input"); - } - char[] escaped = escape(cp); - if (escaped != null) { - int charsSkipped = index - unescapedChunkStart; + // Get a destination buffer and setup some loop variables. + char[] dest = DEST_TL.get(); + int destIndex = 0; + int unescapedChunkStart = 0; - // This is the size needed to add the replacement, not the full - // size needed by the string. We only regrow when we absolutely - // must. - int sizeNeeded = destIndex + charsSkipped + escaped.length; - if (dest.length < sizeNeeded) { - int destLength = sizeNeeded + (end - index) + DEST_PAD; - dest = growBuffer(dest, destIndex, destLength); - } - // If we have skipped any characters, we need to copy them now. - if (charsSkipped > 0) { - s.getChars(unescapedChunkStart, index, dest, destIndex); - destIndex += charsSkipped; - } - if (escaped.length > 0) { - System.arraycopy(escaped, 0, dest, destIndex, escaped.length); - destIndex += escaped.length; - } - } - unescapedChunkStart = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); - index = nextEscapeIndex(s, unescapedChunkStart, end); - } + while (index < end) { + int cp = codePointAt(s, index, end); + if (cp < 0) { + throw new IllegalArgumentException("Trailing high surrogate at end of input"); + } + char[] escaped = escape(cp); + if (escaped != null) { + int charsSkipped = index - unescapedChunkStart; - // Process trailing unescaped characters - no need to account for - // escaped - // length or padding the allocation. - int charsSkipped = end - unescapedChunkStart; + // This is the size needed to add the replacement, not the full + // size needed by the string. We only regrow when we absolutely + // must. + int sizeNeeded = destIndex + charsSkipped + escaped.length; + if (dest.length < sizeNeeded) { + int destLength = sizeNeeded + (end - index) + DEST_PAD; + dest = growBuffer(dest, destIndex, destLength); + } + // If we have skipped any characters, we need to copy them now. if (charsSkipped > 0) { - int endIndex = destIndex + charsSkipped; - if (dest.length < endIndex) { - dest = growBuffer(dest, destIndex, endIndex); - } - s.getChars(unescapedChunkStart, end, dest, destIndex); - destIndex = endIndex; + s.getChars(unescapedChunkStart, index, dest, destIndex); + destIndex += charsSkipped; } - return new String(dest, 0, destIndex); + if (escaped.length > 0) { + System.arraycopy(escaped, 0, dest, destIndex, escaped.length); + destIndex += escaped.length; + } + } + unescapedChunkStart = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); + index = nextEscapeIndex(s, unescapedChunkStart, end); } - /** - * Returns an {@code Appendable} instance which automatically escapes all - * text appended to it before passing the resulting text to an underlying - * {@code Appendable}. - * - * <p> - * Unlike {@link #escape(String)} it is permitted to append arbitrarily - * split input to this Appendable, including input that is split over a - * surrogate pair. In this case the pending high surrogate character will - * not be processed until the corresponding low surrogate is appended. This - * means that a trailing high surrogate character at the end of the input - * cannot be detected and will be silently ignored. This is unavoidable - * since the Appendable interface has no {@code close()} method, and it is - * impossible to determine when the last characters have been appended. - * - * <p> - * The methods of the returned object will propagate any exceptions thrown - * by the underlying {@code Appendable}. - * - * <p> - * For well formed <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> - * the escaping behavior is identical to that of {@link #escape(String)} and - * the following code is equivalent to (but much slower than) - * {@code escaper.escape(string)}: - * - * <pre> - * { - * @code - * StringBuilder sb = new StringBuilder(); - * escaper.escape(sb).append(string); - * return sb.toString(); - * } - * </pre> - * - * @param out - * the underlying {@code Appendable} to append escaped output to - * @return an {@code Appendable} which passes text to {@code out} after - * escaping it - * @throws NullPointerException - * if {@code out} is null - * @throws IllegalArgumentException - * if invalid surrogate characters are encountered - * - */ - public Appendable escape(final Appendable out) { - assert out != null; + // Process trailing unescaped characters - no need to account for + // escaped + // length or padding the allocation. + int charsSkipped = end - unescapedChunkStart; + if (charsSkipped > 0) { + int endIndex = destIndex + charsSkipped; + if (dest.length < endIndex) { + dest = growBuffer(dest, destIndex, endIndex); + } + s.getChars(unescapedChunkStart, end, dest, destIndex); + destIndex = endIndex; + } + return new String(dest, 0, destIndex); + } - return new Appendable() { - int pendingHighSurrogate = -1; - char[] decodedChars = new char[2]; + /** + * Returns an {@code Appendable} instance which automatically escapes all text appended to it + * before passing the resulting text to an underlying {@code Appendable}. + * + * <p> + * Unlike {@link #escape(String)} it is permitted to append arbitrarily split input to this + * Appendable, including input that is split over a surrogate pair. In this case the pending high + * surrogate character will not be processed until the corresponding low surrogate is appended. + * This means that a trailing high surrogate character at the end of the input cannot be detected + * and will be silently ignored. This is unavoidable since the Appendable interface has no + * {@code close()} method, and it is impossible to determine when the last characters have been + * appended. + * + * <p> + * The methods of the returned object will propagate any exceptions thrown by the underlying + * {@code Appendable}. + * + * <p> + * For well formed <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> the escaping behavior + * is identical to that of {@link #escape(String)} and the following code is equivalent to (but + * much slower than) {@code escaper.escape(string)}: + * + * <pre> + * { + * @code + * StringBuilder sb = new StringBuilder(); + * escaper.escape(sb).append(string); + * return sb.toString(); + * } + * </pre> + * + * @param out the underlying {@code Appendable} to append escaped output to + * @return an {@code Appendable} which passes text to {@code out} after escaping it + * @throws NullPointerException if {@code out} is null + * @throws IllegalArgumentException if invalid surrogate characters are encountered + */ + public Appendable escape(final Appendable out) { + assert out != null; - public Appendable append(CharSequence csq) throws IOException { - return append(csq, 0, csq.length()); - } + return new Appendable() { + int pendingHighSurrogate = -1; + final char[] decodedChars = new char[2]; - public Appendable append(CharSequence csq, int start, int end) throws IOException { - int index = start; - if (index < end) { - // This is a little subtle: index must never reference the - // middle of a - // surrogate pair but unescapedChunkStart can. The first - // time we enter - // the loop below it is possible that index != - // unescapedChunkStart. - int unescapedChunkStart = index; - if (pendingHighSurrogate != -1) { - // Our last append operation ended halfway through a - // surrogate pair - // so we have to do some extra work first. - char c = csq.charAt(index++); - if (!Character.isLowSurrogate(c)) { - throw new IllegalArgumentException( - "Expected low surrogate character but got " + c); - } - char[] escaped = escape(Character.toCodePoint((char) pendingHighSurrogate, - c)); - if (escaped != null) { - // Emit the escaped character and adjust - // unescapedChunkStart to - // skip the low surrogate we have consumed. - outputChars(escaped, escaped.length); - unescapedChunkStart += 1; - } else { - // Emit pending high surrogate (unescaped) but do - // not modify - // unescapedChunkStart as we must still emit the low - // surrogate. - out.append((char) pendingHighSurrogate); - } - pendingHighSurrogate = -1; - } - while (true) { - // Find and append the next subsequence of unescaped - // characters. - index = nextEscapeIndex(csq, index, end); - if (index > unescapedChunkStart) { - out.append(csq, unescapedChunkStart, index); - } - if (index == end) { - break; - } - // If we are not finished, calculate the next code - // point. - int cp = codePointAt(csq, index, end); - if (cp < 0) { - // Our sequence ended half way through a surrogate - // pair so just - // record the state and exit. - pendingHighSurrogate = -cp; - break; - } - // Escape the code point and output the characters. - char[] escaped = escape(cp); - if (escaped != null) { - outputChars(escaped, escaped.length); - } else { - // This shouldn't really happen if nextEscapeIndex - // is correct but - // we should cope with false positives. - int len = Character.toChars(cp, decodedChars, 0); - outputChars(decodedChars, len); - } - // Update our index past the escaped character and - // continue. - index += (Character.isSupplementaryCodePoint(cp) ? 2 : 1); - unescapedChunkStart = index; - } - } - return this; - } + public Appendable append(CharSequence csq) throws IOException { + return append(csq, 0, csq.length()); + } - public Appendable append(char c) throws IOException { - if (pendingHighSurrogate != -1) { - // Our last append operation ended halfway through a - // surrogate pair - // so we have to do some extra work first. - if (!Character.isLowSurrogate(c)) { - throw new IllegalArgumentException( - "Expected low surrogate character but got '" + c + "' with value " - + (int) c); - } - char[] escaped = escape(Character.toCodePoint((char) pendingHighSurrogate, c)); - if (escaped != null) { - outputChars(escaped, escaped.length); - } else { - out.append((char) pendingHighSurrogate); - out.append(c); - } - pendingHighSurrogate = -1; - } else if (Character.isHighSurrogate(c)) { - // This is the start of a (split) surrogate pair. - pendingHighSurrogate = c; - } else { - if (Character.isLowSurrogate(c)) { - throw new IllegalArgumentException("Unexpected low surrogate character '" - + c + "' with value " + (int) c); - } - // This is a normal (non surrogate) char. - char[] escaped = escape(c); - if (escaped != null) { - outputChars(escaped, escaped.length); - } else { - out.append(c); - } - } - return this; + public Appendable append(CharSequence csq, int start, int end) throws IOException { + int index = start; + if (index < end) { + // This is a little subtle: index must never reference the + // middle of a + // surrogate pair but unescapedChunkStart can. The first + // time we enter + // the loop below it is possible that index != + // unescapedChunkStart. + int unescapedChunkStart = index; + if (pendingHighSurrogate != -1) { + // Our last append operation ended halfway through a + // surrogate pair + // so we have to do some extra work first. + char c = csq.charAt(index++); + if (!Character.isLowSurrogate(c)) { + throw new IllegalArgumentException("Expected low surrogate character but got " + c); } - - private void outputChars(char[] chars, int len) throws IOException { - for (int n = 0; n < len; n++) { - out.append(chars[n]); - } + char[] escaped = escape(Character.toCodePoint((char) pendingHighSurrogate, c)); + if (escaped != null) { + // Emit the escaped character and adjust + // unescapedChunkStart to + // skip the low surrogate we have consumed. + outputChars(escaped, escaped.length); + unescapedChunkStart += 1; + } else { + // Emit pending high surrogate (unescaped) but do + // not modify + // unescapedChunkStart as we must still emit the low + // surrogate. + out.append((char) pendingHighSurrogate); } - }; - } - - /** - * Returns the Unicode code point of the character at the given index. - * - * <p> - * Unlike {@link Character#codePointAt(CharSequence, int)} or - * {@link String#codePointAt(int)} this method will never fail silently when - * encountering an invalid surrogate pair. - * - * <p> - * The behaviour of this method is as follows: - * <ol> - * <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. - * <li><b>If the character at the specified index is not a surrogate, it is - * returned.</b> - * <li>If the first character was a high surrogate value, then an attempt is - * made to read the next character. - * <ol> - * <li><b>If the end of the sequence was reached, the negated value of the - * trailing high surrogate is returned.</b> - * <li><b>If the next character was a valid low surrogate, the code point - * value of the high/low surrogate pair is returned.</b> - * <li>If the next character was not a low surrogate value, then - * {@link IllegalArgumentException} is thrown. - * </ol> - * <li>If the first character was a low surrogate value, - * {@link IllegalArgumentException} is thrown. - * </ol> - * - * @param seq - * the sequence of characters from which to decode the code point - * @param index - * the index of the first character to decode - * @param end - * the index beyond the last valid character to decode - * @return the Unicode code point for the given index or the negated value - * of the trailing high surrogate character at the end of the - * sequence - */ - protected static final int codePointAt(CharSequence seq, int index, int end) { - if (index < end) { - char c1 = seq.charAt(index++); - if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { - // Fast path (first test is probably all we need to do) - return c1; - } else if (c1 <= Character.MAX_HIGH_SURROGATE) { - // If the high surrogate was the last character, return its - // inverse - if (index == end) { - return -c1; - } - // Otherwise look for the low surrogate following it - char c2 = seq.charAt(index); - if (Character.isLowSurrogate(c2)) { - return Character.toCodePoint(c1, c2); - } - throw new IllegalArgumentException("Expected low surrogate but got char '" + c2 - + "' with value " + (int) c2 + " at index " + index); + pendingHighSurrogate = -1; + } + while (true) { + // Find and append the next subsequence of unescaped + // characters. + index = nextEscapeIndex(csq, index, end); + if (index > unescapedChunkStart) { + out.append(csq, unescapedChunkStart, index); + } + if (index == end) { + break; + } + // If we are not finished, calculate the next code + // point. + int cp = codePointAt(csq, index, end); + if (cp < 0) { + // Our sequence ended half way through a surrogate + // pair so just + // record the state and exit. + pendingHighSurrogate = -cp; + break; + } + // Escape the code point and output the characters. + char[] escaped = escape(cp); + if (escaped != null) { + outputChars(escaped, escaped.length); } else { - throw new IllegalArgumentException("Unexpected low surrogate character '" + c1 - + "' with value " + (int) c1 + " at index " + (index - 1)); + // This shouldn't really happen if nextEscapeIndex + // is correct but + // we should cope with false positives. + int len = Character.toChars(cp, decodedChars, 0); + outputChars(decodedChars, len); } + // Update our index past the escaped character and + // continue. + index += (Character.isSupplementaryCodePoint(cp) ? 2 : 1); + unescapedChunkStart = index; + } } - throw new IndexOutOfBoundsException("Index exceeds specified range"); - } + return this; + } - /** - * Helper method to grow the character buffer as needed, this only happens - * once in a while so it's ok if it's in a method call. If the index passed - * in is 0 then no copying will be done. - */ - private static final char[] growBuffer(char[] dest, int index, int size) { - char[] copy = new char[size]; - if (index > 0) { - System.arraycopy(dest, 0, copy, 0, index); + public Appendable append(char c) throws IOException { + if (pendingHighSurrogate != -1) { + // Our last append operation ended halfway through a + // surrogate pair + // so we have to do some extra work first. + if (!Character.isLowSurrogate(c)) { + throw new IllegalArgumentException( + "Expected low surrogate character but got '" + c + "' with value " + (int) c); + } + char[] escaped = escape(Character.toCodePoint((char) pendingHighSurrogate, c)); + if (escaped != null) { + outputChars(escaped, escaped.length); + } else { + out.append((char) pendingHighSurrogate); + out.append(c); + } + pendingHighSurrogate = -1; + } else if (Character.isHighSurrogate(c)) { + // This is the start of a (split) surrogate pair. + pendingHighSurrogate = c; + } else { + if (Character.isLowSurrogate(c)) { + throw new IllegalArgumentException( + "Unexpected low surrogate character '" + c + "' with value " + (int) c); + } + // This is a normal (non surrogate) char. + char[] escaped = escape(c); + if (escaped != null) { + outputChars(escaped, escaped.length); + } else { + out.append(c); + } } - return copy; - } + return this; + } - /** - * A thread-local destination buffer to keep us from creating new buffers. - * The starting size is 1024 characters. If we grow past this we don't put - * it back in the threadlocal, we just keep going and grow as needed. - */ - private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() { - @Override - protected char[] initialValue() { - return new char[1024]; + private void outputChars(char[] chars, int len) throws IOException { + for (int n = 0; n < len; n++) { + out.append(chars[n]); } + } }; + } + + /** + * Returns the Unicode code point of the character at the given index. + * + * <p> + * Unlike {@link Character#codePointAt(CharSequence, int)} or {@link String#codePointAt(int)} this + * method will never fail silently when encountering an invalid surrogate pair. + * + * <p> + * The behaviour of this method is as follows: + * <ol> + * <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. + * <li><b>If the character at the specified index is not a surrogate, it is returned.</b> + * <li>If the first character was a high surrogate value, then an attempt is made to read the next + * character. + * <ol> + * <li><b>If the end of the sequence was reached, the negated value of the trailing high surrogate + * is returned.</b> + * <li><b>If the next character was a valid low surrogate, the code point value of the high/low + * surrogate pair is returned.</b> + * <li>If the next character was not a low surrogate value, then {@link IllegalArgumentException} + * is thrown. + * </ol> + * <li>If the first character was a low surrogate value, {@link IllegalArgumentException} is + * thrown. + * </ol> + * + * @param seq the sequence of characters from which to decode the code point + * @param index the index of the first character to decode + * @param end the index beyond the last valid character to decode + * @return the Unicode code point for the given index or the negated value of the trailing high + * surrogate character at the end of the sequence + */ + protected static final int codePointAt(CharSequence seq, int index, int end) { + if (index < end) { + char c1 = seq.charAt(index++); + if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { + // Fast path (first test is probably all we need to do) + return c1; + } else if (c1 <= Character.MAX_HIGH_SURROGATE) { + // If the high surrogate was the last character, return its + // inverse + if (index == end) { + return -c1; + } + // Otherwise look for the low surrogate following it + char c2 = seq.charAt(index); + if (Character.isLowSurrogate(c2)) { + return Character.toCodePoint(c1, c2); + } + throw new IllegalArgumentException("Expected low surrogate but got char '" + c2 + + "' with value " + (int) c2 + " at index " + index); + } else { + throw new IllegalArgumentException("Unexpected low surrogate character '" + c1 + + "' with value " + (int) c1 + " at index " + (index - 1)); + } + } + throw new IndexOutOfBoundsException("Index exceeds specified range"); + } + + /** + * Helper method to grow the character buffer as needed, this only happens once in a while so it's + * ok if it's in a method call. If the index passed in is 0 then no copying will be done. + */ + private static final char[] growBuffer(char[] dest, int index, int size) { + char[] copy = new char[size]; + if (index > 0) { + System.arraycopy(dest, 0, copy, 0, index); + } + return copy; + } + + /** + * A thread-local destination buffer to keep us from creating new buffers. The starting size is + * 1024 characters. If we grow past this we don't put it back in the threadlocal, we just keep + * going and grow as needed. + */ + private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() { + @Override + protected char[] initialValue() { + return new char[1024]; + } + }; } diff --git a/src/main/java/org/yaml/snakeyaml/introspector/BeanAccess.java b/src/main/java/org/yaml/snakeyaml/introspector/BeanAccess.java index 696fec73..04454673 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/BeanAccess.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/BeanAccess.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.introspector; @@ -19,12 +17,12 @@ package org.yaml.snakeyaml.introspector; * Control instance variables. */ public enum BeanAccess { - /** use JavaBean properties and public fields */ - DEFAULT, + /** use JavaBean properties and public fields */ + DEFAULT, - /** use all declared fields (including inherited) */ - FIELD, + /** use all declared fields (including inherited) */ + FIELD, - /** reserved */ - PROPERTY; -}
\ No newline at end of file + /** reserved */ + PROPERTY +} diff --git a/src/main/java/org/yaml/snakeyaml/introspector/FieldProperty.java b/src/main/java/org/yaml/snakeyaml/introspector/FieldProperty.java index 9bc38aac..6d064174 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/FieldProperty.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/FieldProperty.java @@ -1,52 +1,64 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.introspector; +import java.lang.annotation.Annotation; import java.lang.reflect.Field; - +import java.util.List; import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.util.ArrayUtils; /** * <p> - * A <code>FieldProperty</code> is a <code>Property</code> which is accessed as - * a field, without going through accessor methods (setX, getX). The field may - * have any scope (public, package, protected, private). + * A <code>FieldProperty</code> is a <code>Property</code> which is accessed as a field, without + * going through accessor methods (setX, getX). The field may have any scope (public, package, + * protected, private). * </p> */ public class FieldProperty extends GenericProperty { - private final Field field; - public FieldProperty(Field field) { - super(field.getName(), field.getType(), field.getGenericType()); - this.field = field; - field.setAccessible(true); - } + private final Field field; - @Override - public void set(Object object, Object value) throws Exception { - field.set(object, value); - } + public FieldProperty(Field field) { + super(field.getName(), field.getType(), field.getGenericType()); + this.field = field; + field.setAccessible(true); + } + + @Override + public void set(Object object, Object value) throws Exception { + field.set(object, value); + } - @Override - public Object get(Object object) { - try { - return field.get(object); - } catch (Exception e) { - throw new YAMLException("Unable to access field " + field.getName() + " on object " - + object + " : " + e); - } + @Override + public Object get(Object object) { + try { + return field.get(object); + } catch (Exception e) { + throw new YAMLException( + "Unable to access field " + field.getName() + " on object " + object + " : " + e); } -}
\ No newline at end of file + } + + @Override + public List<Annotation> getAnnotations() { + return ArrayUtils.toUnmodifiableList(field.getAnnotations()); + } + + @Override + public <A extends Annotation> A getAnnotation(Class<A> annotationType) { + return field.getAnnotation(annotationType); + } + +} diff --git a/src/main/java/org/yaml/snakeyaml/introspector/GenericProperty.java b/src/main/java/org/yaml/snakeyaml/introspector/GenericProperty.java index 30981601..7fff2b5e 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/GenericProperty.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/GenericProperty.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.introspector; @@ -20,63 +18,62 @@ import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -abstract public class GenericProperty extends Property { +public abstract class GenericProperty extends Property { - private Type genType; + private final Type genType; - public GenericProperty(String name, Class<?> aClass, Type aType) { - super(name, aClass); - genType = aType; - actualClassesChecked = aType == null; - } + public GenericProperty(String name, Class<?> aClass, Type aType) { + super(name, aClass); + genType = aType; + actualClassesChecked = aType == null; + } - private boolean actualClassesChecked; - private Class<?>[] actualClasses; + private boolean actualClassesChecked; + private Class<?>[] actualClasses; - public Class<?>[] getActualTypeArguments() { // should we synchronize here ? - if (!actualClassesChecked) { - if (genType instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) genType; - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - if (actualTypeArguments.length > 0) { - actualClasses = new Class<?>[actualTypeArguments.length]; - for (int i = 0; i < actualTypeArguments.length; i++) { - if (actualTypeArguments[i] instanceof Class<?>) { - actualClasses[i] = (Class<?>) actualTypeArguments[i]; - } else if (actualTypeArguments[i] instanceof ParameterizedType) { - actualClasses[i] = (Class<?>) ((ParameterizedType) actualTypeArguments[i]) - .getRawType(); - } else if (actualTypeArguments[i] instanceof GenericArrayType) { - Type componentType = ((GenericArrayType) actualTypeArguments[i]) - .getGenericComponentType(); - if (componentType instanceof Class<?>) { - actualClasses[i] = Array.newInstance((Class<?>) componentType, 0) - .getClass(); - } else { - actualClasses = null; - break; - } - } else { - actualClasses = null; - break; - } - } - } - } else if (genType instanceof GenericArrayType) { - Type componentType = ((GenericArrayType) genType).getGenericComponentType(); - if (componentType instanceof Class<?>) { - actualClasses = new Class<?>[] { (Class<?>) componentType }; - } - } else if (genType instanceof Class<?>) {// XXX this check is only - // required for IcedTea6 - Class<?> classType = (Class<?>) genType; - if (classType.isArray()) { - actualClasses = new Class<?>[1]; - actualClasses[0] = getType().getComponentType(); - } + public Class<?>[] getActualTypeArguments() { // should we synchronize here ? + if (!actualClassesChecked) { + if (genType instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) genType; + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + if (actualTypeArguments.length > 0) { + actualClasses = new Class<?>[actualTypeArguments.length]; + for (int i = 0; i < actualTypeArguments.length; i++) { + if (actualTypeArguments[i] instanceof Class<?>) { + actualClasses[i] = (Class<?>) actualTypeArguments[i]; + } else if (actualTypeArguments[i] instanceof ParameterizedType) { + actualClasses[i] = + (Class<?>) ((ParameterizedType) actualTypeArguments[i]).getRawType(); + } else if (actualTypeArguments[i] instanceof GenericArrayType) { + Type componentType = + ((GenericArrayType) actualTypeArguments[i]).getGenericComponentType(); + if (componentType instanceof Class<?>) { + actualClasses[i] = Array.newInstance((Class<?>) componentType, 0).getClass(); + } else { + actualClasses = null; + break; + } + } else { + actualClasses = null; + break; } - actualClassesChecked = true; + } + } + } else if (genType instanceof GenericArrayType) { + Type componentType = ((GenericArrayType) genType).getGenericComponentType(); + if (componentType instanceof Class<?>) { + actualClasses = new Class<?>[] {(Class<?>) componentType}; + } + } else if (genType instanceof Class<?>) {// XXX this check is only + // required for IcedTea6 + Class<?> classType = (Class<?>) genType; + if (classType.isArray()) { + actualClasses = new Class<?>[1]; + actualClasses[0] = getType().getComponentType(); } - return actualClasses; + } + actualClassesChecked = true; } + return actualClasses; + } } diff --git a/src/main/java/org/yaml/snakeyaml/introspector/MethodProperty.java b/src/main/java/org/yaml/snakeyaml/introspector/MethodProperty.java index fc6e00d5..c27fa139 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/MethodProperty.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/MethodProperty.java @@ -1,71 +1,137 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.introspector; import java.beans.PropertyDescriptor; - +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.List; import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.util.ArrayUtils; /** * <p> - * A <code>MethodProperty</code> is a <code>Property</code> which is accessed - * through accessor methods (setX, getX). It is possible to have a - * <code>MethodProperty</code> which has only setter, only getter, or both. It - * is not possible to have a <code>MethodProperty</code> which has neither + * A <code>MethodProperty</code> is a <code>Property</code> which is accessed through accessor + * methods (setX, getX). It is possible to have a <code>MethodProperty</code> which has only setter, + * only getter, or both. It is not possible to have a <code>MethodProperty</code> which has neither * setter nor getter. * </p> */ public class MethodProperty extends GenericProperty { - private final PropertyDescriptor property; - private final boolean readable; - private final boolean writable; + private final PropertyDescriptor property; + private final boolean readable; + private final boolean writable; + + private static Type discoverGenericType(PropertyDescriptor property) { + Method readMethod = property.getReadMethod(); + if (readMethod != null) { + return readMethod.getGenericReturnType(); + } - public MethodProperty(PropertyDescriptor property) { - super(property.getName(), property.getPropertyType(), - property.getReadMethod() == null ? null : property.getReadMethod() - .getGenericReturnType()); - this.property = property; - this.readable = property.getReadMethod() != null; - this.writable = property.getWriteMethod() != null; + Method writeMethod = property.getWriteMethod(); + if (writeMethod != null) { + Type[] paramTypes = writeMethod.getGenericParameterTypes(); + if (paramTypes.length > 0) { + return paramTypes[0]; + } } + /* + * This actually may happen if PropertyDescriptor is of type IndexedPropertyDescriptor and it + * has only IndexedGetter/Setter. ATM we simply skip type discovery. + */ + return null; + } + + public MethodProperty(PropertyDescriptor property) { + super(property.getName(), property.getPropertyType(), + MethodProperty.discoverGenericType(property)); + this.property = property; + this.readable = property.getReadMethod() != null; + this.writable = property.getWriteMethod() != null; + } - @Override - public void set(Object object, Object value) throws Exception { - property.getWriteMethod().invoke(object, value); + @Override + public void set(Object object, Object value) throws Exception { + if (!writable) { + throw new YAMLException( + "No writable property '" + getName() + "' on class: " + object.getClass().getName()); } + property.getWriteMethod().invoke(object, value); + } - @Override - public Object get(Object object) { - try { - property.getReadMethod().setAccessible(true);// issue 50 - return property.getReadMethod().invoke(object); - } catch (Exception e) { - throw new YAMLException("Unable to find getter for property '" + property.getName() - + "' on object " + object + ":" + e); - } + @Override + public Object get(Object object) { + try { + property.getReadMethod().setAccessible(true);// issue 50 + return property.getReadMethod().invoke(object); + } catch (Exception e) { + throw new YAMLException("Unable to find getter for property '" + property.getName() + + "' on object " + object + ":" + e); } + } - @Override - public boolean isWritable() { - return writable; + /** + * Returns the annotations that are present on read and write methods of this property or empty + * {@code List} if there're no annotations. + * + * @return the annotations that are present on this property or empty {@code List} if there're no + * annotations + */ + @Override + public List<Annotation> getAnnotations() { + List<Annotation> annotations; + if (isReadable() && isWritable()) { + annotations = ArrayUtils.toUnmodifiableCompositeList( + property.getReadMethod().getAnnotations(), property.getWriteMethod().getAnnotations()); + } else if (isReadable()) { + annotations = ArrayUtils.toUnmodifiableList(property.getReadMethod().getAnnotations()); + } else { + annotations = ArrayUtils.toUnmodifiableList(property.getWriteMethod().getAnnotations()); } + return annotations; + } - @Override - public boolean isReadable() { - return readable; + /** + * Returns property's annotation for the given type or {@code null} if it's not present. If the + * annotation is present on both read and write methods, the annotation on read method takes + * precedence. + * + * @param annotationType the type of the annotation to be returned + * @return property's annotation for the given type or {@code null} if it's not present + */ + @Override + public <A extends Annotation> A getAnnotation(Class<A> annotationType) { + A annotation = null; + if (isReadable()) { + annotation = property.getReadMethod().getAnnotation(annotationType); } -}
\ No newline at end of file + if (annotation == null && isWritable()) { + annotation = property.getWriteMethod().getAnnotation(annotationType); + } + return annotation; + } + + @Override + public boolean isWritable() { + return writable; + } + + @Override + public boolean isReadable() { + return readable; + } + +} diff --git a/src/main/java/org/yaml/snakeyaml/introspector/MissingProperty.java b/src/main/java/org/yaml/snakeyaml/introspector/MissingProperty.java index b16a1c27..97d7233c 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/MissingProperty.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/MissingProperty.java @@ -1,44 +1,56 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.introspector; +import java.lang.annotation.Annotation; +import java.util.Collections; +import java.util.List; + /** - * A property that does not map to a real property; this is used when {@link - * PropertyUtils.setSkipMissingProperties(boolean)} is set to true. + * A property that does not map to a real property; this is used when + * {@link PropertyUtils}.setSkipMissingProperties(boolean) is set to true. */ public class MissingProperty extends Property { - public MissingProperty(String name) { - super(name, Object.class); - } - - @Override - public Class<?>[] getActualTypeArguments() { - return new Class[0]; - } - - /** - * Setter does nothing. - */ - @Override - public void set(Object object, Object value) throws Exception { - } - - @Override - public Object get(Object object) { - return object; - } + public MissingProperty(String name) { + super(name, Object.class); + } + + @Override + public Class<?>[] getActualTypeArguments() { + return new Class[0]; + } + + /** + * Setter does nothing. + */ + @Override + public void set(Object object, Object value) throws Exception {} + + @Override + public Object get(Object object) { + return object; + } + + @Override + public List<Annotation> getAnnotations() { + return Collections.emptyList(); + } + + @Override + public <A extends Annotation> A getAnnotation(Class<A> annotationType) { + return null; + } + } diff --git a/src/main/java/org/yaml/snakeyaml/introspector/Property.java b/src/main/java/org/yaml/snakeyaml/introspector/Property.java index 286ca0e3..a65d8505 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/Property.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/Property.java @@ -1,85 +1,104 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.introspector; +import java.lang.annotation.Annotation; +import java.util.List; + /** * <p> - * A <code>Property</code> represents a single member variable of a class, - * possibly including its accessor methods (getX, setX). The name stored in this - * class is the actual name of the property as given for the class, not an - * alias. + * A <code>Property</code> represents a single member variable of a class, possibly including its + * accessor methods (getX, setX). The name stored in this class is the actual name of the property + * as given for the class, not an alias. * </p> - * + * * <p> - * Objects of this class have a total ordering which defaults to ordering based - * on the name of the property. + * Objects of this class have a total ordering which defaults to ordering based on the name of the + * property. * </p> */ public abstract class Property implements Comparable<Property> { - private final String name; - private final Class<?> type; + private final String name; + private final Class<?> type; - public Property(String name, Class<?> type) { - this.name = name; - this.type = type; - } + public Property(String name, Class<?> type) { + this.name = name; + this.type = type; + } - public Class<?> getType() { - return type; - } + public Class<?> getType() { + return type; + } - abstract public Class<?>[] getActualTypeArguments(); + public abstract Class<?>[] getActualTypeArguments(); - public String getName() { - return name; - } + public String getName() { + return name; + } - @Override - public String toString() { - return getName() + " of " + getType(); - } + @Override + public String toString() { + return getName() + " of " + getType(); + } - public int compareTo(Property o) { - return name.compareTo(o.name); - } + public int compareTo(Property o) { + return getName().compareTo(o.getName()); + } - public boolean isWritable() { - return true; - } + public boolean isWritable() { + return true; + } - public boolean isReadable() { - return true; - } + public boolean isReadable() { + return true; + } - abstract public void set(Object object, Object value) throws Exception; + public abstract void set(Object object, Object value) throws Exception; - abstract public Object get(Object object); + public abstract Object get(Object object); - @Override - public int hashCode() { - return name.hashCode() + type.hashCode(); - } + /** + * Returns the annotations that are present on this property or empty {@code List} if there're no + * annotations. + * + * @return the annotations that are present on this property or empty {@code List} if there're no + * annotations + */ + public abstract List<Annotation> getAnnotations(); + + /** + * Returns property's annotation for the given type or {@code null} if it's not present. + * + * @param annotationType the type of the annotation to be returned + * @param <A> class of the annotation + * + * @return property's annotation for the given type or {@code null} if it's not present + */ + public abstract <A extends Annotation> A getAnnotation(Class<A> annotationType); + + @Override + public int hashCode() { + return getName().hashCode() + getType().hashCode(); + } - @Override - public boolean equals(Object other) { - if (other instanceof Property) { - Property p = (Property) other; - return name.equals(p.getName()) && type.equals(p.getType()); - } - return false; + @Override + public boolean equals(Object other) { + if (other instanceof Property) { + Property p = (Property) other; + return getName().equals(p.getName()) && getType().equals(p.getType()); } -}
\ No newline at end of file + return false; + } +} diff --git a/src/main/java/org/yaml/snakeyaml/introspector/PropertySubstitute.java b/src/main/java/org/yaml/snakeyaml/introspector/PropertySubstitute.java new file mode 100644 index 00000000..162df62a --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/introspector/PropertySubstitute.java @@ -0,0 +1,253 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.introspector; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.yaml.snakeyaml.error.YAMLException; + +// TODO: decide priorities for get/set Read/Field/Delegate Write/Field/Delegate - is FIELD on the +// correct place ? +public class PropertySubstitute extends Property { + + private static final Logger log = + Logger.getLogger(PropertySubstitute.class.getPackage().getName()); + + protected Class<?> targetType; + private final String readMethod; + private final String writeMethod; + private transient Method read; + private transient Method write; + private Field field; + protected Class<?>[] parameters; + private Property delegate; + private boolean filler; + + public PropertySubstitute(String name, Class<?> type, String readMethod, String writeMethod, + Class<?>... params) { + super(name, type); + this.readMethod = readMethod; + this.writeMethod = writeMethod; + setActualTypeArguments(params); + this.filler = false; + } + + public PropertySubstitute(String name, Class<?> type, Class<?>... params) { + this(name, type, null, null, params); + } + + @Override + public Class<?>[] getActualTypeArguments() { + if (parameters == null && delegate != null) { + return delegate.getActualTypeArguments(); + } + return parameters; + } + + public void setActualTypeArguments(Class<?>... args) { + if (args != null && args.length > 0) { + parameters = args; + } else { + parameters = null; + } + } + + @Override + public void set(Object object, Object value) throws Exception { + if (write != null) { + if (!filler) { + write.invoke(object, value); + } else if (value != null) { + if (value instanceof Collection<?>) { + Collection<?> collection = (Collection<?>) value; + for (Object val : collection) { + write.invoke(object, val); + } + } else if (value instanceof Map<?, ?>) { + Map<?, ?> map = (Map<?, ?>) value; + for (Entry<?, ?> entry : map.entrySet()) { + write.invoke(object, entry.getKey(), entry.getValue()); + } + } else if (value.getClass().isArray()) { + // TODO: maybe arrays need 2 fillers like SET(index, value) add ADD(value) + int len = Array.getLength(value); + for (int i = 0; i < len; i++) { + write.invoke(object, Array.get(value, i)); + } + } + } + } else if (field != null) { + field.set(object, value); + } else if (delegate != null) { + delegate.set(object, value); + } else { + log.warning("No setter/delegate for '" + getName() + "' on object " + object); + } + // TODO: maybe throw YAMLException here + } + + @Override + public Object get(Object object) { + try { + if (read != null) { + return read.invoke(object); + } else if (field != null) { + return field.get(object); + } + } catch (Exception e) { + throw new YAMLException( + "Unable to find getter for property '" + getName() + "' on object " + object + ":" + e); + } + + if (delegate != null) { + return delegate.get(object); + } + throw new YAMLException( + "No getter or delegate for property '" + getName() + "' on object " + object); + } + + @Override + public List<Annotation> getAnnotations() { + Annotation[] annotations = null; + if (read != null) { + annotations = read.getAnnotations(); + } else if (field != null) { + annotations = field.getAnnotations(); + } + return annotations != null ? Arrays.asList(annotations) : delegate.getAnnotations(); + } + + @Override + public <A extends Annotation> A getAnnotation(Class<A> annotationType) { + A annotation; + if (read != null) { + annotation = read.getAnnotation(annotationType); + } else if (field != null) { + annotation = field.getAnnotation(annotationType); + } else { + annotation = delegate.getAnnotation(annotationType); + } + return annotation; + } + + public void setTargetType(Class<?> targetType) { + if (this.targetType != targetType) { + this.targetType = targetType; + + final String name = getName(); + for (Class<?> c = targetType; c != null; c = c.getSuperclass()) { + for (Field f : c.getDeclaredFields()) { + if (f.getName().equals(name)) { + int modifiers = f.getModifiers(); + if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { + f.setAccessible(true); + field = f; + } + break; + } + } + } + if (field == null && log.isLoggable(Level.FINE)) { + log.fine(String.format("Failed to find field for %s.%s", targetType.getName(), getName())); + } + + // Retrieve needed info + if (readMethod != null) { + read = discoverMethod(targetType, readMethod); + } + if (writeMethod != null) { + filler = false; + write = discoverMethod(targetType, writeMethod, getType()); + if (write == null && parameters != null) { + filler = true; + write = discoverMethod(targetType, writeMethod, parameters); + } + } + } + } + + private Method discoverMethod(Class<?> type, String name, Class<?>... params) { + for (Class<?> c = type; c != null; c = c.getSuperclass()) { + for (Method method : c.getDeclaredMethods()) { + if (name.equals(method.getName())) { + Class<?>[] parameterTypes = method.getParameterTypes(); + if (parameterTypes.length != params.length) { + continue; + } + boolean found = true; + for (int i = 0; i < parameterTypes.length; i++) { + if (!parameterTypes[i].isAssignableFrom(params[i])) { + found = false; + } + } + if (found) { + method.setAccessible(true); + return method; + } + } + } + } + if (log.isLoggable(Level.FINE)) { + log.fine(String.format("Failed to find [%s(%d args)] for %s.%s", name, params.length, + targetType.getName(), getName())); + } + return null; + } + + @Override + public String getName() { + final String n = super.getName(); + if (n != null) { + return n; + } + return delegate != null ? delegate.getName() : null; + } + + @Override + public Class<?> getType() { + final Class<?> t = super.getType(); + if (t != null) { + return t; + } + return delegate != null ? delegate.getType() : null; + } + + @Override + public boolean isReadable() { + return (read != null) || (field != null) || (delegate != null && delegate.isReadable()); + } + + @Override + public boolean isWritable() { + return (write != null) || (field != null) || (delegate != null && delegate.isWritable()); + } + + public void setDelegate(Property delegate) { + this.delegate = delegate; + if (writeMethod != null && write == null && !filler) { + filler = true; + write = discoverMethod(targetType, writeMethod, getActualTypeArguments()); + } + } +} diff --git a/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java b/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java index 92519d90..8afc5761 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java @@ -1,20 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.introspector; +import java.beans.FeatureDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; @@ -27,140 +26,174 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; - import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.util.PlatformFeatureDetector; public class PropertyUtils { - private final Map<Class<?>, Map<String, Property>> propertiesCache = new HashMap<Class<?>, Map<String, Property>>(); - private final Map<Class<?>, Set<Property>> readableProperties = new HashMap<Class<?>, Set<Property>>(); - private BeanAccess beanAccess = BeanAccess.DEFAULT; - private boolean allowReadOnlyProperties = false; - private boolean skipMissingProperties = false; + private final Map<Class<?>, Map<String, Property>> propertiesCache = + new HashMap<Class<?>, Map<String, Property>>(); + private final Map<Class<?>, Set<Property>> readableProperties = + new HashMap<Class<?>, Set<Property>>(); + private BeanAccess beanAccess = BeanAccess.DEFAULT; + private boolean allowReadOnlyProperties = false; + private boolean skipMissingProperties = false; - protected Map<String, Property> getPropertiesMap(Class<?> type, BeanAccess bAccess) - throws IntrospectionException { - if (propertiesCache.containsKey(type)) { - return propertiesCache.get(type); - } + private final PlatformFeatureDetector platformFeatureDetector; - Map<String, Property> properties = new LinkedHashMap<String, Property>(); - boolean inaccessableFieldsExist = false; - switch (bAccess) { - case FIELD: - for (Class<?> c = type; c != null; c = c.getSuperclass()) { - for (Field field : c.getDeclaredFields()) { - int modifiers = field.getModifiers(); - if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) - && !properties.containsKey(field.getName())) { - properties.put(field.getName(), new FieldProperty(field)); - } - } - } - break; - default: - // add JavaBean properties - for (PropertyDescriptor property : Introspector.getBeanInfo(type) - .getPropertyDescriptors()) { - Method readMethod = property.getReadMethod(); - if (readMethod == null || !readMethod.getName().equals("getClass")) { - properties.put(property.getName(), new MethodProperty(property)); - } - } + public PropertyUtils() { + this(new PlatformFeatureDetector()); + } - // add public fields - for (Class<?> c = type; c != null; c = c.getSuperclass()) { - for (Field field : c.getDeclaredFields()) { - int modifiers = field.getModifiers(); - if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { - if (Modifier.isPublic(modifiers)) { - properties.put(field.getName(), new FieldProperty(field)); - } else { - inaccessableFieldsExist = true; - } - } - } - } - break; - } - if (properties.isEmpty() && inaccessableFieldsExist) { - throw new YAMLException("No JavaBean properties found in " + type.getName()); - } - propertiesCache.put(type, properties); - return properties; + PropertyUtils(PlatformFeatureDetector platformFeatureDetector) { + this.platformFeatureDetector = platformFeatureDetector; + + /* + * Android lacks much of java.beans (including the Introspector class, used here), because + * java.beans classes tend to rely on java.awt, which isn't supported in the Android SDK. That + * means we have to fall back on FIELD access only when SnakeYAML is running on the Android + * Runtime. + */ + if (platformFeatureDetector.isRunningOnAndroid()) { + beanAccess = BeanAccess.FIELD; } + } - public Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException { - return getProperties(type, beanAccess); + protected Map<String, Property> getPropertiesMap(Class<?> type, BeanAccess bAccess) { + if (propertiesCache.containsKey(type)) { + return propertiesCache.get(type); } - public Set<Property> getProperties(Class<? extends Object> type, BeanAccess bAccess) - throws IntrospectionException { - if (readableProperties.containsKey(type)) { - return readableProperties.get(type); + Map<String, Property> properties = new LinkedHashMap<String, Property>(); + boolean inaccessableFieldsExist = false; + if (bAccess == BeanAccess.FIELD) { + for (Class<?> c = type; c != null; c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + int modifiers = field.getModifiers(); + if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) + && !properties.containsKey(field.getName())) { + properties.put(field.getName(), new FieldProperty(field)); + } } - Set<Property> properties = createPropertySet(type, bAccess); - readableProperties.put(type, properties); - return properties; - } + } + } else {// add JavaBean properties + try { + for (PropertyDescriptor property : Introspector.getBeanInfo(type) + .getPropertyDescriptors()) { + Method readMethod = property.getReadMethod(); + if ((readMethod == null || !readMethod.getName().equals("getClass")) + && !isTransient(property)) { + properties.put(property.getName(), new MethodProperty(property)); + } + } + } catch (IntrospectionException e) { + throw new YAMLException(e); + } - protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) - throws IntrospectionException { - Set<Property> properties = new TreeSet<Property>(); - Collection<Property> props = getPropertiesMap(type, bAccess).values(); - for (Property property : props) { - if (property.isReadable() && (allowReadOnlyProperties || property.isWritable())) { - properties.add(property); + // add public fields + for (Class<?> c = type; c != null; c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + int modifiers = field.getModifiers(); + if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { + if (Modifier.isPublic(modifiers)) { + properties.put(field.getName(), new FieldProperty(field)); + } else { + inaccessableFieldsExist = true; } + } } - return properties; + } + } + if (properties.isEmpty() && inaccessableFieldsExist) { + throw new YAMLException("No JavaBean properties found in " + type.getName()); } + propertiesCache.put(type, properties); + return properties; + } + + private static final String TRANSIENT = "transient"; + + private boolean isTransient(FeatureDescriptor fd) { + return Boolean.TRUE.equals(fd.getValue(TRANSIENT)); + } + + public Set<Property> getProperties(Class<? extends Object> type) { + return getProperties(type, beanAccess); + } - public Property getProperty(Class<? extends Object> type, String name) - throws IntrospectionException { - return getProperty(type, name, beanAccess); + public Set<Property> getProperties(Class<? extends Object> type, BeanAccess bAccess) { + if (readableProperties.containsKey(type)) { + return readableProperties.get(type); } + Set<Property> properties = createPropertySet(type, bAccess); + readableProperties.put(type, properties); + return properties; + } - public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess) - throws IntrospectionException { - Map<String, Property> properties = getPropertiesMap(type, bAccess); - Property property = properties.get(name); - if (property == null && skipMissingProperties) { - property = new MissingProperty(name); - } - if (property == null || !property.isWritable()) { - throw new YAMLException("Unable to find property '" + name + "' on class: " - + type.getName()); - } - return property; + protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) { + Set<Property> properties = new TreeSet<Property>(); + Collection<Property> props = getPropertiesMap(type, bAccess).values(); + for (Property property : props) { + if (property.isReadable() && (allowReadOnlyProperties || property.isWritable())) { + properties.add(property); + } } + return properties; + } - public void setBeanAccess(BeanAccess beanAccess) { - if (this.beanAccess != beanAccess) { - this.beanAccess = beanAccess; - propertiesCache.clear(); - readableProperties.clear(); - } + public Property getProperty(Class<? extends Object> type, String name) { + return getProperty(type, name, beanAccess); + } + + public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess) { + Map<String, Property> properties = getPropertiesMap(type, bAccess); + Property property = properties.get(name); + if (property == null && skipMissingProperties) { + property = new MissingProperty(name); } + if (property == null) { + throw new YAMLException("Unable to find property '" + name + "' on class: " + type.getName()); + } + return property; + } - public void setAllowReadOnlyProperties(boolean allowReadOnlyProperties) { - if (this.allowReadOnlyProperties != allowReadOnlyProperties) { - this.allowReadOnlyProperties = allowReadOnlyProperties; - readableProperties.clear(); - } + public void setBeanAccess(BeanAccess beanAccess) { + if (platformFeatureDetector.isRunningOnAndroid() && beanAccess != BeanAccess.FIELD) { + throw new IllegalArgumentException("JVM is Android - only BeanAccess.FIELD is available"); } - /** - * Skip properties that are missing during deserialization of YAML to a Java - * object. The default is false. - * - * @param skipMissingProperties - * true if missing properties should be skipped, false otherwise. - */ - public void setSkipMissingProperties(boolean skipMissingProperties) { - if (this.skipMissingProperties != skipMissingProperties) { - this.skipMissingProperties = skipMissingProperties; - readableProperties.clear(); - } + if (this.beanAccess != beanAccess) { + this.beanAccess = beanAccess; + propertiesCache.clear(); + readableProperties.clear(); + } + } + + public void setAllowReadOnlyProperties(boolean allowReadOnlyProperties) { + if (this.allowReadOnlyProperties != allowReadOnlyProperties) { + this.allowReadOnlyProperties = allowReadOnlyProperties; + readableProperties.clear(); } + } + + public boolean isAllowReadOnlyProperties() { + return allowReadOnlyProperties; + } + + /** + * Skip properties that are missing during deserialization of YAML to a Java object. The default + * is false. + * + * @param skipMissingProperties true if missing properties should be skipped, false otherwise. + */ + public void setSkipMissingProperties(boolean skipMissingProperties) { + if (this.skipMissingProperties != skipMissingProperties) { + this.skipMissingProperties = skipMissingProperties; + readableProperties.clear(); + } + } + + public boolean isSkipMissingProperties() { + return skipMissingProperties; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/AnchorNode.java b/src/main/java/org/yaml/snakeyaml/nodes/AnchorNode.java index 8a901317..52834120 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/AnchorNode.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/AnchorNode.java @@ -1,35 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; +/** + * This class is only used during representation (dumping) + */ public class AnchorNode extends Node { - private Node realNode; + private final Node realNode; - public AnchorNode(Node realNode) { - super(realNode.getTag(), realNode.getStartMark(), realNode.getEndMark()); - this.realNode = realNode; - } + public AnchorNode(Node realNode) { + super(realNode.getTag(), realNode.getStartMark(), realNode.getEndMark()); + this.realNode = realNode; + } - @Override - public NodeId getNodeId() { - return NodeId.anchor; - } + @Override + public NodeId getNodeId() { + return NodeId.anchor; + } - public Node getRealNode() { - return realNode; - } + public Node getRealNode() { + return realNode; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/CollectionNode.java b/src/main/java/org/yaml/snakeyaml/nodes/CollectionNode.java index aa443686..09ad80f5 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/CollectionNode.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/CollectionNode.java @@ -1,49 +1,83 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; +import java.util.List; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** - * Base class for the two collection types {@link MappingNode mapping} and - * {@link SequenceNode collection}. + * Base class for the two collection types {@link MappingNode mapping} and {@link SequenceNode + * collection}. */ -public abstract class CollectionNode extends Node { - private Boolean flowStyle; +public abstract class CollectionNode<T> extends Node { - public CollectionNode(Tag tag, Mark startMark, Mark endMark, Boolean flowStyle) { - super(tag, startMark, endMark); - this.flowStyle = flowStyle; - } + private DumperOptions.FlowStyle flowStyle; - /** - * Serialization style of this collection. - * - * @return <code>true</code> for flow style, <code>false</code> for block - * style. - */ - public Boolean getFlowStyle() { - return flowStyle; - } + public CollectionNode(Tag tag, Mark startMark, Mark endMark, DumperOptions.FlowStyle flowStyle) { + super(tag, startMark, endMark); + setFlowStyle(flowStyle); + } - public void setFlowStyle(Boolean flowStyle) { - this.flowStyle = flowStyle; - } + /* + * Existed in older versions but replaced with {@link DumperOptions.FlowStyle}-based constructor. + * Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link CollectionNode#CollectionNode(Tag, Mark, Mark, + * org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public CollectionNode(Tag tag, Mark startMark, Mark endMark, Boolean flowStyle) { + this(tag, startMark, endMark, DumperOptions.FlowStyle.fromBoolean(flowStyle)); + } + + /** + * Returns the elements in this sequence. + * + * @return Nodes in the specified order. + */ + public abstract List<T> getValue(); - public void setEndMark(Mark endMark) { - this.endMark = endMark; + /** + * Serialization style of this collection. + * + * @return <code>true</code> for flow style, <code>false</code> for block style. + */ + public DumperOptions.FlowStyle getFlowStyle() { + return flowStyle; + } + + public void setFlowStyle(DumperOptions.FlowStyle flowStyle) { + if (flowStyle == null) { + throw new NullPointerException("Flow style must be provided."); } + this.flowStyle = flowStyle; + } + + /* + * Existed in older versions but replaced with {@link DumperOptions.FlowStyle}-based method. + * Restored in v1.26 for backwards compatibility. + * + * @deprecated Since restored in v1.26. Use {@link + * CollectionNode#setFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public void setFlowStyle(Boolean flowStyle) { + setFlowStyle(DumperOptions.FlowStyle.fromBoolean(flowStyle)); + } + + public void setEndMark(Mark endMark) { + this.endMark = endMark; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/MappingNode.java b/src/main/java/org/yaml/snakeyaml/nodes/MappingNode.java index ed3dcff5..f0f7a84d 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/MappingNode.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/MappingNode.java @@ -1,22 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import java.util.List; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** @@ -25,87 +23,113 @@ import org.yaml.snakeyaml.error.Mark; * A map is a collection of unsorted key-value pairs. * </p> */ -public class MappingNode extends CollectionNode { - private List<NodeTuple> value; - private boolean merged = false; - - public MappingNode(Tag tag, boolean resolved, List<NodeTuple> value, Mark startMark, - Mark endMark, Boolean flowStyle) { - super(tag, startMark, endMark, flowStyle); - if (value == null) { - throw new NullPointerException("value in a Node is required."); - } - this.value = value; - this.resolved = resolved; - } +public class MappingNode extends CollectionNode<NodeTuple> { - public MappingNode(Tag tag, List<NodeTuple> value, Boolean flowStyle) { - this(tag, true, value, null, null, flowStyle); - } + private List<NodeTuple> value; + private boolean merged = false; - @Override - public NodeId getNodeId() { - return NodeId.mapping; + public MappingNode(Tag tag, boolean resolved, List<NodeTuple> value, Mark startMark, Mark endMark, + DumperOptions.FlowStyle flowStyle) { + super(tag, startMark, endMark, flowStyle); + if (value == null) { + throw new NullPointerException("value in a Node is required."); } + this.value = value; + this.resolved = resolved; + } - /** - * Returns the entries of this map. - * - * @return List of entries. - */ - public List<NodeTuple> getValue() { - return value; - } + public MappingNode(Tag tag, List<NodeTuple> value, DumperOptions.FlowStyle flowStyle) { + this(tag, true, value, null, null, flowStyle); + } - public void setValue(List<NodeTuple> merge) { - value = merge; - } + /* + * Existed in older versions but replaced with {@link DumperOptions.FlowStyle}-based constructor. + * Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link MappingNode#MappingNode(Tag, boolean, List, + * Mark, Mark, org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public MappingNode(Tag tag, boolean resolved, List<NodeTuple> value, Mark startMark, Mark endMark, + Boolean flowStyle) { + this(tag, resolved, value, startMark, endMark, DumperOptions.FlowStyle.fromBoolean(flowStyle)); + } - public void setOnlyKeyType(Class<? extends Object> keyType) { - for (NodeTuple nodes : value) { - nodes.getKeyNode().setType(keyType); - } - } + /* + * Existed in older versions but replaced with {@link DumperOptions.FlowStyle}-based constructor. + * Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link MappingNode#MappingNode(Tag, List, + * org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public MappingNode(Tag tag, List<NodeTuple> value, Boolean flowStyle) { + this(tag, value, DumperOptions.FlowStyle.fromBoolean(flowStyle)); - public void setTypes(Class<? extends Object> keyType, Class<? extends Object> valueType) { - for (NodeTuple nodes : value) { - nodes.getValueNode().setType(valueType); - nodes.getKeyNode().setType(keyType); - } - } + } + + @Override + public NodeId getNodeId() { + return NodeId.mapping; + } + + /** + * Returns the entries of this map. + * + * @return List of entries. + */ + public List<NodeTuple> getValue() { + return value; + } - @Override - public String toString() { - String values; - StringBuilder buf = new StringBuilder(); - for (NodeTuple node : getValue()) { - buf.append("{ key="); - buf.append(node.getKeyNode()); - buf.append("; value="); - if (node.getValueNode() instanceof CollectionNode) { - // to avoid overflow in case of recursive structures - buf.append(System.identityHashCode(node.getValueNode())); - } else { - buf.append(node.toString()); - } - buf.append(" }"); - } - values = buf.toString(); - return "<" + this.getClass().getName() + " (tag=" + getTag() + ", values=" + values + ")>"; + public void setValue(List<NodeTuple> mergedValue) { + value = mergedValue; + } + + public void setOnlyKeyType(Class<? extends Object> keyType) { + for (NodeTuple nodes : value) { + nodes.getKeyNode().setType(keyType); } + } - /** - * @param merged - * - true if map contains merge node - */ - public void setMerged(boolean merged) { - this.merged = merged; + public void setTypes(Class<? extends Object> keyType, Class<? extends Object> valueType) { + for (NodeTuple nodes : value) { + nodes.getValueNode().setType(valueType); + nodes.getKeyNode().setType(keyType); } + } - /** - * @return true if map contains merge node - */ - public boolean isMerged() { - return merged; + @Override + public String toString() { + String values; + StringBuilder buf = new StringBuilder(); + for (NodeTuple node : getValue()) { + buf.append("{ key="); + buf.append(node.getKeyNode()); + buf.append("; value="); + if (node.getValueNode() instanceof CollectionNode) { + // to avoid overflow in case of recursive structures + buf.append(System.identityHashCode(node.getValueNode())); + } else { + buf.append(node); + } + buf.append(" }"); } + values = buf.toString(); + return "<" + this.getClass().getName() + " (tag=" + getTag() + ", values=" + values + ")>"; + } + + /** + * @param merged - true if map contains merge node + */ + public void setMerged(boolean merged) { + this.merged = merged; + } + + /** + * @return true if map contains merge node + */ + public boolean isMerged() { + return merged; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/Node.java b/src/main/java/org/yaml/snakeyaml/nodes/Node.java index 1037e41a..45b9b9b8 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/Node.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/Node.java @@ -1,166 +1,225 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; +import java.util.List; +import org.yaml.snakeyaml.comments.CommentLine; import org.yaml.snakeyaml.error.Mark; /** * Base class for all nodes. * <p> - * The nodes form the node-graph described in the <a - * href="http://yaml.org/spec/1.1/">YAML Specification</a>. + * The nodes form the node-graph described in the <a href="http://yaml.org/spec/1.1/">YAML + * Specification</a>. * </p> * <p> * While loading, the node graph is usually created by the - * {@link org.yaml.snakeyaml.composer.Composer}, and later transformed into - * application specific Java classes by the classes from the - * {@link org.yaml.snakeyaml.constructor} package. + * {@link org.yaml.snakeyaml.composer.Composer}, and later transformed into application specific + * Java classes by the classes from the {@link org.yaml.snakeyaml.constructor} package. * </p> */ public abstract class Node { - private Tag tag; - private Mark startMark; - protected Mark endMark; - private Class<? extends Object> type; - private boolean twoStepsConstruction; - /** - * true when the tag is assigned by the resolver - */ - protected boolean resolved; - protected Boolean useClassConstructor; - - public Node(Tag tag, Mark startMark, Mark endMark) { - setTag(tag); - this.startMark = startMark; - this.endMark = endMark; - this.type = Object.class; - this.twoStepsConstruction = false; - this.resolved = true; - this.useClassConstructor = null; - } - - /** - * Tag of this node. - * <p> - * Every node has a tag assigned. The tag is either local or global. - * - * @return Tag of this node. - */ - public Tag getTag() { - return this.tag; - } - - public Mark getEndMark() { - return endMark; - } - - /** - * For error reporting. - * - * @see "class variable 'id' in PyYAML" - * @return scalar, sequence, mapping - */ - public abstract NodeId getNodeId(); - - public Mark getStartMark() { - return startMark; - } - - public void setTag(Tag tag) { - if (tag == null) { - throw new NullPointerException("tag in a Node is required."); - } - this.tag = tag; - } - - /** - * Two Nodes are never equal. - */ - @Override - public final boolean equals(Object obj) { - return super.equals(obj); - } - public Class<? extends Object> getType() { - return type; + private Tag tag; + private final Mark startMark; + protected Mark endMark; + private Class<? extends Object> type; + private boolean twoStepsConstruction; + private String anchor; + private List<CommentLine> inLineComments; + private List<CommentLine> blockComments; + // End Comments are only on the last node in a document + private List<CommentLine> endComments; + + /** + * true when the tag is assigned by the resolver + */ + protected boolean resolved; + protected Boolean useClassConstructor; + + public Node(Tag tag, Mark startMark, Mark endMark) { + setTag(tag); + this.startMark = startMark; + this.endMark = endMark; + this.type = Object.class; + this.twoStepsConstruction = false; + this.resolved = true; + this.useClassConstructor = null; + this.inLineComments = null; + this.blockComments = null; + this.endComments = null; + } + + /** + * Tag of this node. + * <p> + * Every node has a tag assigned. The tag is either local or global. + * + * @return Tag of this node. + */ + public Tag getTag() { + return this.tag; + } + + public Mark getEndMark() { + return endMark; + } + + /** + * For error reporting. + * + * @see "class variable 'id' in PyYAML" + * @return scalar, sequence, mapping + */ + public abstract NodeId getNodeId(); + + public Mark getStartMark() { + return startMark; + } + + public void setTag(Tag tag) { + if (tag == null) { + throw new NullPointerException("tag in a Node is required."); } - - public void setType(Class<? extends Object> type) { - if (!type.isAssignableFrom(this.type)) { - this.type = type; - } - } - - public void setTwoStepsConstruction(boolean twoStepsConstruction) { - this.twoStepsConstruction = twoStepsConstruction; - } - - /** - * Indicates if this node must be constructed in two steps. - * <p> - * Two-step construction is required whenever a node is a child (direct or - * indirect) of it self. That is, if a recursive structure is build using - * anchors and aliases. - * </p> - * <p> - * Set by {@link org.yaml.snakeyaml.composer.Composer}, used during the - * construction process. - * </p> - * <p> - * Only relevant during loading. - * </p> - * - * @return <code>true</code> if the node is self referenced. - */ - public boolean isTwoStepsConstruction() { - return twoStepsConstruction; - } - - @Override - public final int hashCode() { - return super.hashCode(); - } - - public boolean useClassConstructor() { - if (useClassConstructor == null) { - if (!tag.isSecondary() && isResolved() && !Object.class.equals(type) - && !tag.equals(Tag.NULL)) { - return true; - } else if (tag.isCompatible(getType())) { - // the tag is compatible with the runtime class - // the tag will be ignored - return true; - } else { - return false; - } - } - return useClassConstructor.booleanValue(); + this.tag = tag; + } + + /** + * Node is only equal to itself + */ + @Override + public final boolean equals(Object obj) { + return super.equals(obj); + } + + public Class<? extends Object> getType() { + return type; + } + + public void setType(Class<? extends Object> type) { + if (!type.isAssignableFrom(this.type)) { + this.type = type; } - - public void setUseClassConstructor(Boolean useClassConstructor) { - this.useClassConstructor = useClassConstructor; - } - - /** - * Indicates if the tag was added by - * {@link org.yaml.snakeyaml.resolver.Resolver}. - * - * @return <code>true</code> if the tag of this node was resolved</code> - */ - public boolean isResolved() { - return resolved; + } + + public void setTwoStepsConstruction(boolean twoStepsConstruction) { + this.twoStepsConstruction = twoStepsConstruction; + } + + /** + * Indicates if this node must be constructed in two steps. + * <p> + * Two-step construction is required whenever a node is a child (direct or indirect) of it self. + * That is, if a recursive structure is build using anchors and aliases. + * </p> + * <p> + * Set by {@link org.yaml.snakeyaml.composer.Composer}, used during the construction process. + * </p> + * <p> + * Only relevant during loading. + * </p> + * + * @return <code>true</code> if the node is self referenced. + */ + public boolean isTwoStepsConstruction() { + return twoStepsConstruction; + } + + @Override + public final int hashCode() { + return super.hashCode(); + } + + public boolean useClassConstructor() { + if (useClassConstructor == null) { + // the tag is compatible with the runtime class + // the tag will be ignored + if (!tag.isSecondary() && resolved && !Object.class.equals(type) && !tag.equals(Tag.NULL)) { + return true; + } else { + return tag.isCompatible(getType()); + } } + return useClassConstructor.booleanValue(); + } + + public void setUseClassConstructor(Boolean useClassConstructor) { + this.useClassConstructor = useClassConstructor; + } + + /** + * Indicates if the tag was added by {@link org.yaml.snakeyaml.resolver.Resolver}. + * + * @return true if the tag of this node was resolved + * + * @deprecated Since v1.22. Absent in immediately prior versions, but present previously. Restored + * deprecated for backwards compatibility. + */ + @Deprecated + public boolean isResolved() { + return resolved; + } + + public String getAnchor() { + return anchor; + } + + public void setAnchor(String anchor) { + this.anchor = anchor; + } + + /** + * The ordered list of in-line comments. The first of which appears at the end of the line + * respresent by this node. The rest are in the following lines, indented per the Spec to indicate + * they are continuation of the inline comment. + * + * @return the comment line list. + */ + public List<CommentLine> getInLineComments() { + return inLineComments; + } + + public void setInLineComments(List<CommentLine> inLineComments) { + this.inLineComments = inLineComments; + } + + /** + * The ordered list of blank lines and block comments (full line) that appear before this node. + * + * @return the comment line list. + */ + public List<CommentLine> getBlockComments() { + return blockComments; + } + + public void setBlockComments(List<CommentLine> blockComments) { + this.blockComments = blockComments; + } + + /** + * The ordered list of blank lines and block comments (full line) that appear AFTER this node. + * <p> + * NOTE: these comment should occur only in the last node in a document, when walking the node + * tree "in order" + * + * @return the comment line list. + */ + public List<CommentLine> getEndComments() { + return endComments; + } + + public void setEndComments(List<CommentLine> endComments) { + this.endComments = endComments; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/NodeId.java b/src/main/java/org/yaml/snakeyaml/nodes/NodeId.java index 178e26d0..f9bcef7b 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/NodeId.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/NodeId.java @@ -1,23 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; /** - * Enum for the three basic YAML types: scalar, sequence and mapping. + * Enum for the basic YAML types: scalar, sequence, mapping or anchor. */ public enum NodeId { - scalar, sequence, mapping, anchor; + scalar, sequence, mapping, anchor } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/NodeTuple.java b/src/main/java/org/yaml/snakeyaml/nodes/NodeTuple.java index 3e3cb36e..1380a5f6 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/NodeTuple.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/NodeTuple.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; @@ -20,36 +18,37 @@ package org.yaml.snakeyaml.nodes; */ public final class NodeTuple { - private Node keyNode; - private Node valueNode; + private final Node keyNode; + private final Node valueNode; - public NodeTuple(Node keyNode, Node valueNode) { - if (keyNode == null || valueNode == null) { - throw new NullPointerException("Nodes must be provided."); - } - this.keyNode = keyNode; - this.valueNode = valueNode; + public NodeTuple(Node keyNode, Node valueNode) { + if (keyNode == null || valueNode == null) { + throw new NullPointerException("Nodes must be provided."); } + this.keyNode = keyNode; + this.valueNode = valueNode; + } - /** - * Key node. - */ - public Node getKeyNode() { - return keyNode; - } + /** + * Key node. + * + * @return the node used as key + */ + public Node getKeyNode() { + return keyNode; + } - /** - * Value node. - * - * @return value - */ - public Node getValueNode() { - return valueNode; - } + /** + * Value node. + * + * @return node used as value + */ + public Node getValueNode() { + return valueNode; + } - @Override - public String toString() { - return "<NodeTuple keyNode=" + keyNode.toString() + "; valueNode=" + valueNode.toString() - + ">"; - } + @Override + public String toString() { + return "<NodeTuple keyNode=" + keyNode + "; valueNode=" + valueNode + ">"; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/ScalarNode.java b/src/main/java/org/yaml/snakeyaml/nodes/ScalarNode.java index 9120d0ee..61212df0 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/ScalarNode.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/ScalarNode.java @@ -1,20 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** @@ -24,51 +23,97 @@ import org.yaml.snakeyaml.error.Mark; * </p> */ public class ScalarNode extends Node { - private Character style; - private String value; - public ScalarNode(Tag tag, String value, Mark startMark, Mark endMark, Character style) { - this(tag, true, value, startMark, endMark, style); - } + private final DumperOptions.ScalarStyle style; + private final String value; - public ScalarNode(Tag tag, boolean resolved, String value, Mark startMark, Mark endMark, - Character style) { - super(tag, startMark, endMark); - if (value == null) { - throw new NullPointerException("value in a Node is required."); - } - this.value = value; - this.style = style; - this.resolved = resolved; - } + public ScalarNode(Tag tag, String value, Mark startMark, Mark endMark, + DumperOptions.ScalarStyle style) { + this(tag, true, value, startMark, endMark, style); + } - /** - * Get scalar style of this node. - * - * @see org.yaml.snakeyaml.events.ScalarEvent - * @see <a href="http://yaml.org/spec/1.1/#id903915">Chapter 9. Scalar - * Styles</a> - */ - public Character getStyle() { - return style; + public ScalarNode(Tag tag, boolean resolved, String value, Mark startMark, Mark endMark, + DumperOptions.ScalarStyle style) { + super(tag, startMark, endMark); + if (value == null) { + throw new NullPointerException("value in a Node is required."); } - - @Override - public NodeId getNodeId() { - return NodeId.scalar; + this.value = value; + if (style == null) { + throw new NullPointerException("Scalar style must be provided."); } + this.style = style; + this.resolved = resolved; + } - /** - * Value of this scalar. - * - * @return Scalar's value. - */ - public String getValue() { - return value; - } + /* + * Existed in older versions but replaced with {@link DumperOptions.ScalarStyle}-based + * constructor. Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link ScalarNode#ScalarNode(Tag, String, Mark, Mark, + * org.yaml.snakeyaml.DumperOptions.ScalarStyle) }. + */ + @Deprecated + public ScalarNode(Tag tag, String value, Mark startMark, Mark endMark, Character style) { + this(tag, value, startMark, endMark, DumperOptions.ScalarStyle.createStyle(style)); + } - public String toString() { - return "<" + this.getClass().getName() + " (tag=" + getTag() + ", value=" + getValue() - + ")>"; - } + /* + * Existed in older versions but replaced with {@link DumperOptions.ScalarStyle}-based + * constructor. Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link ScalarNode#ScalarNode(Tag, boolean, String, + * Mark, Mark, org.yaml.snakeyaml.DumperOptions.ScalarStyle) }. + */ + @Deprecated + public ScalarNode(Tag tag, boolean resolved, String value, Mark startMark, Mark endMark, + Character style) { + this(tag, resolved, value, startMark, endMark, DumperOptions.ScalarStyle.createStyle(style)); + } + + /** + * Get scalar style of this node. + * + * @see org.yaml.snakeyaml.events.ScalarEvent + * @see <a href="http://yaml.org/spec/1.1/#id903915">Chapter 9. Scalar Styles</a> + * @return style of this scalar node + * @deprecated use getScalarStyle instead + */ + @Deprecated + public Character getStyle() { + return style.getChar(); + } + + /** + * Get scalar style of this node. + * + * @see org.yaml.snakeyaml.events.ScalarEvent + * @see <a href="http://yaml.org/spec/1.1/#id903915">Chapter 9. Scalar Styles</a> + * @return style of this scalar node + */ + public DumperOptions.ScalarStyle getScalarStyle() { + return style; + } + + @Override + public NodeId getNodeId() { + return NodeId.scalar; + } + + /** + * Value of this scalar. + * + * @return Scalar's value. + */ + public String getValue() { + return value; + } + + public String toString() { + return "<" + this.getClass().getName() + " (tag=" + getTag() + ", value=" + getValue() + ")>"; + } + + public boolean isPlain() { + return style == DumperOptions.ScalarStyle.PLAIN; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/SequenceNode.java b/src/main/java/org/yaml/snakeyaml/nodes/SequenceNode.java index 5e2f6b40..745268da 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/SequenceNode.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/SequenceNode.java @@ -1,22 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import java.util.List; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; /** @@ -25,45 +23,70 @@ import org.yaml.snakeyaml.error.Mark; * A sequence is a ordered collection of nodes. * </p> */ -public class SequenceNode extends CollectionNode { - final private List<Node> value; +public class SequenceNode extends CollectionNode<Node> { - public SequenceNode(Tag tag, boolean resolved, List<Node> value, Mark startMark, Mark endMark, - Boolean flowStyle) { - super(tag, startMark, endMark, flowStyle); - if (value == null) { - throw new NullPointerException("value in a Node is required."); - } - this.value = value; - this.resolved = resolved; - } + private final List<Node> value; - public SequenceNode(Tag tag, List<Node> value, Boolean flowStyle) { - this(tag, true, value, null, null, flowStyle); + public SequenceNode(Tag tag, boolean resolved, List<Node> value, Mark startMark, Mark endMark, + DumperOptions.FlowStyle flowStyle) { + super(tag, startMark, endMark, flowStyle); + if (value == null) { + throw new NullPointerException("value in a Node is required."); } + this.value = value; + this.resolved = resolved; + } - @Override - public NodeId getNodeId() { - return NodeId.sequence; - } + public SequenceNode(Tag tag, List<Node> value, DumperOptions.FlowStyle flowStyle) { + this(tag, true, value, null, null, flowStyle); + } - /** - * Returns the elements in this sequence. - * - * @return Nodes in the specified order. - */ - public List<Node> getValue() { - return value; - } + /* + * Existed in older versions but replaced with {@link DumperOptions.SequenceStyle}-based + * constructor. Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link SequenceNode#SequenceNode(Tag, List<Node>, + * org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public SequenceNode(Tag tag, List<Node> value, Boolean style) { + this(tag, value, DumperOptions.FlowStyle.fromBoolean(style)); + } - public void setListType(Class<? extends Object> listType) { - for (Node node : value) { - node.setType(listType); - } - } + /* + * Existed in older versions but replaced with {@link DumperOptions.SequenceStyle}-based + * constructor. Restored in v1.22 for backwards compatibility. + * + * @deprecated Since restored in v1.22. Use {@link SequenceNode#SequenceNode(Tag, boolean, + * List<Node>, Mark, Mark, org.yaml.snakeyaml.DumperOptions.FlowStyle) }. + */ + @Deprecated + public SequenceNode(Tag tag, boolean resolved, List<Node> value, Mark startMark, Mark endMark, + Boolean style) { + this(tag, resolved, value, startMark, endMark, DumperOptions.FlowStyle.fromBoolean(style)); + } + + @Override + public NodeId getNodeId() { + return NodeId.sequence; + } - public String toString() { - return "<" + this.getClass().getName() + " (tag=" + getTag() + ", value=" + getValue() - + ")>"; + /** + * Returns the elements in this sequence. + * + * @return Nodes in the specified order. + */ + public List<Node> getValue() { + return value; + } + + public void setListType(Class<? extends Object> listType) { + for (Node node : value) { + node.setType(listType); } + } + + public String toString() { + return "<" + this.getClass().getName() + " (tag=" + getTag() + ", value=" + getValue() + ")>"; + } } diff --git a/src/main/java/org/yaml/snakeyaml/nodes/Tag.java b/src/main/java/org/yaml/snakeyaml/nodes/Tag.java index 913e1f5b..dbb6f5a8 100644 --- a/src/main/java/org/yaml/snakeyaml/nodes/Tag.java +++ b/src/main/java/org/yaml/snakeyaml/nodes/Tag.java @@ -1,172 +1,175 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; -import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; - import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.util.UriEncoder; -public final class Tag implements Comparable<Tag> { - public static final String PREFIX = "tag:yaml.org,2002:"; - public static final Tag YAML = new Tag(PREFIX + "yaml"); - public static final Tag MERGE = new Tag(PREFIX + "merge"); - public static final Tag SET = new Tag(PREFIX + "set"); - public static final Tag PAIRS = new Tag(PREFIX + "pairs"); - public static final Tag OMAP = new Tag(PREFIX + "omap"); - public static final Tag BINARY = new Tag(PREFIX + "binary"); - public static final Tag INT = new Tag(PREFIX + "int"); - public static final Tag FLOAT = new Tag(PREFIX + "float"); - public static final Tag TIMESTAMP = new Tag(PREFIX + "timestamp"); - public static final Tag BOOL = new Tag(PREFIX + "bool"); - public static final Tag NULL = new Tag(PREFIX + "null"); - public static final Tag STR = new Tag(PREFIX + "str"); - public static final Tag SEQ = new Tag(PREFIX + "seq"); - public static final Tag MAP = new Tag(PREFIX + "map"); - public static final Map<Tag, Set<Class<?>>> COMPATIBILITY_MAP; - static { - COMPATIBILITY_MAP = new HashMap<Tag, Set<Class<?>>>(); - Set<Class<?>> floatSet = new HashSet<Class<?>>(); - floatSet.add(Double.class); - floatSet.add(Float.class); - floatSet.add(BigDecimal.class); - COMPATIBILITY_MAP.put(FLOAT, floatSet); - // - Set<Class<?>> intSet = new HashSet<Class<?>>(); - intSet.add(Integer.class); - intSet.add(Long.class); - intSet.add(BigInteger.class); - COMPATIBILITY_MAP.put(INT, intSet); - // - Set<Class<?>> timestampSet = new HashSet<Class<?>>(); - timestampSet.add(Date.class); - timestampSet.add(java.sql.Date.class); - timestampSet.add(Timestamp.class); - COMPATIBILITY_MAP.put(TIMESTAMP, timestampSet); - } - - private final String value; - private boolean secondary = false; // see http://www.yaml.org/refcard.html - - public Tag(String tag) { - if (tag == null) { - throw new NullPointerException("Tag must be provided."); - } else if (tag.length() == 0) { - throw new IllegalArgumentException("Tag must not be empty."); - } else if (tag.trim().length() != tag.length()) { - throw new IllegalArgumentException("Tag must not contain leading or trailing spaces."); - } - this.value = UriEncoder.encode(tag); - this.secondary = !tag.startsWith(PREFIX); +public final class Tag { + + public static final String PREFIX = "tag:yaml.org,2002:"; + public static final Tag YAML = new Tag(PREFIX + "yaml"); + public static final Tag MERGE = new Tag(PREFIX + "merge"); + public static final Tag SET = new Tag(PREFIX + "set"); + public static final Tag PAIRS = new Tag(PREFIX + "pairs"); + public static final Tag OMAP = new Tag(PREFIX + "omap"); + public static final Tag BINARY = new Tag(PREFIX + "binary"); + public static final Tag INT = new Tag(PREFIX + "int"); + public static final Tag FLOAT = new Tag(PREFIX + "float"); + public static final Tag TIMESTAMP = new Tag(PREFIX + "timestamp"); + public static final Tag BOOL = new Tag(PREFIX + "bool"); + public static final Tag NULL = new Tag(PREFIX + "null"); + public static final Tag STR = new Tag(PREFIX + "str"); + public static final Tag SEQ = new Tag(PREFIX + "seq"); + public static final Tag MAP = new Tag(PREFIX + "map"); + // For use to indicate a DUMMY node that contains comments, when there is no other (empty + // document) + public static final Tag COMMENT = new Tag(PREFIX + "comment"); + private static final Map<Tag, Set<Class<?>>> COMPATIBILITY_MAP; + + static { + COMPATIBILITY_MAP = new HashMap<Tag, Set<Class<?>>>(); + Set<Class<?>> floatSet = new HashSet<Class<?>>(); + floatSet.add(Double.class); + floatSet.add(Float.class); + floatSet.add(BigDecimal.class); + COMPATIBILITY_MAP.put(FLOAT, floatSet); + // + Set<Class<?>> intSet = new HashSet<Class<?>>(); + intSet.add(Integer.class); + intSet.add(Long.class); + intSet.add(BigInteger.class); + COMPATIBILITY_MAP.put(INT, intSet); + // + Set<Class<?>> timestampSet = new HashSet<Class<?>>(); + timestampSet.add(Date.class); + + // java.sql is a separate module since jigsaw was introduced in java9 + try { + timestampSet.add(Class.forName("java.sql.Date")); + timestampSet.add(Class.forName("java.sql.Timestamp")); + } catch (ClassNotFoundException ignored) { + // ignore - we are running in a module path without java.sql } - public Tag(Class<? extends Object> clazz) { - if (clazz == null) { - throw new NullPointerException("Class for tag must be provided."); - } - this.value = Tag.PREFIX + UriEncoder.encode(clazz.getName()); - } + COMPATIBILITY_MAP.put(TIMESTAMP, timestampSet); + } - //TODO to be removed ? - public Tag(URI uri) { - if (uri == null) { - throw new NullPointerException("URI for tag must be provided."); - } - this.value = uri.toASCIIString(); - } - - public boolean isSecondary() { - return secondary; - } + private final String value; + private boolean secondary = false; // see http://www.yaml.org/refcard.html - public String getValue() { - return value; + public Tag(String tag) { + if (tag == null) { + throw new NullPointerException("Tag must be provided."); + } else if (tag.length() == 0) { + throw new IllegalArgumentException("Tag must not be empty."); + } else if (tag.trim().length() != tag.length()) { + throw new IllegalArgumentException("Tag must not contain leading or trailing spaces."); } + this.value = UriEncoder.encode(tag); + this.secondary = !tag.startsWith(PREFIX); + } - public boolean startsWith(String prefix) { - return value.startsWith(prefix); + public Tag(Class<? extends Object> clazz) { + if (clazz == null) { + throw new NullPointerException("Class for tag must be provided."); } - - public String getClassName() { - if (!value.startsWith(Tag.PREFIX)) { - throw new YAMLException("Invalid tag: " + value); - } - return UriEncoder.decode(value.substring(Tag.PREFIX.length())); + this.value = Tag.PREFIX + UriEncoder.encode(clazz.getName()); + } + + /** + * @deprecated - it will be removed + * @param uri - URI to be encoded as tag value + */ + @Deprecated + public Tag(URI uri) { + if (uri == null) { + throw new NullPointerException("URI for tag must be provided."); } + this.value = uri.toASCIIString(); + } - public int getLength() { - return value.length(); - } + public boolean isSecondary() { + return secondary; + } - @Override - public String toString() { - return value; - } + public String getValue() { + return value; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Tag) { - return value.equals(((Tag) obj).getValue()); - } else - return false; - } + public boolean startsWith(String prefix) { + return value.startsWith(prefix); + } - @Override - public int hashCode() { - return value.hashCode(); + public String getClassName() { + if (!value.startsWith(Tag.PREFIX)) { + throw new YAMLException("Invalid tag: " + value); } - - /** - * Java has more then 1 class compatible with a language-independent tag - * (!!int, !!float, !!timestamp etc) - * - * @param clazz - * - Class to check compatibility - * @return true when the Class can be represented by this - * language-independent tag - */ - public boolean isCompatible(Class<?> clazz) { - Set<Class<?>> set = COMPATIBILITY_MAP.get(this); - if (set != null) { - return set.contains(clazz); - } else { - return false; - } + return UriEncoder.decode(value.substring(Tag.PREFIX.length())); + } + + @Override + public String toString() { + return value; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Tag) { + return value.equals(((Tag) obj).getValue()); + } else { + return false; } - - /** - * Check whether this tag matches the global tag for the Class - * - * @param clazz - * - Class to check - * @return true when the this tag can be used as a global tag for the Class - */ - public boolean matches(Class<? extends Object> clazz) { - return value.equals(Tag.PREFIX + clazz.getName()); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + /** + * Java has more then 1 class compatible with a language-independent tag (!!int, !!float, + * !!timestamp etc) + * + * @param clazz - Class to check compatibility + * @return true when the Class can be represented by this language-independent tag + */ + public boolean isCompatible(Class<?> clazz) { + Set<Class<?>> set = COMPATIBILITY_MAP.get(this); + if (set != null) { + return set.contains(clazz); + } else { + return false; } + } + + /** + * Check whether this tag matches the global tag for the Class + * + * @param clazz - Class to check + * @return true when the this tag can be used as a global tag for the Class + */ + public boolean matches(Class<? extends Object> clazz) { + return value.equals(Tag.PREFIX + clazz.getName()); + } - public int compareTo(Tag o) { - return value.compareTo(o.getValue()); - } } diff --git a/src/main/java/org/yaml/snakeyaml/parser/Parser.java b/src/main/java/org/yaml/snakeyaml/parser/Parser.java index 8c1bf169..b0e96ea4 100644 --- a/src/main/java/org/yaml/snakeyaml/parser/Parser.java +++ b/src/main/java/org/yaml/snakeyaml/parser/Parser.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.parser; @@ -20,46 +18,40 @@ import org.yaml.snakeyaml.events.Event; /** * This interface represents an input stream of {@link Event Events}. * <p> - * The parser and the scanner form together the 'Parse' step in the loading - * process (see chapter 3.1 of the <a href="http://yaml.org/spec/1.1/">YAML - * Specification</a>). + * The parser and the scanner form together the 'Parse' step in the loading process (see chapter 3.1 + * of the <a href="http://yaml.org/spec/1.1/">YAML Specification</a>). * </p> - * + * * @see org.yaml.snakeyaml.events.Event */ public interface Parser { - /** - * Check if the next event is one of the given type. - * - * @param choice - * Event ID. - * @return <code>true</code> if the next event can be assigned to a variable - * of the given type. Returns <code>false</code> if no more events - * are available. - * @throws ParserException - * Thrown in case of malformed input. - */ - public boolean checkEvent(Event.ID choice); + /** + * Check if the next event is one of the given type. + * + * @param choice Event ID. + * @return <code>true</code> if the next event can be assigned to a variable of the given type. + * Returns <code>false</code> if no more events are available. + * @throws ParserException Thrown in case of malformed input. + */ + boolean checkEvent(Event.ID choice); - /** - * Return the next event, but do not delete it from the stream. - * - * @return The event that will be returned on the next call to - * {@link #getEvent} - * @throws ParserException - * Thrown in case of malformed input. - */ - public Event peekEvent(); + /** + * Return the next event, but do not delete it from the stream. + * + * @return The event that will be returned on the next call to {@link #getEvent} + * @throws ParserException Thrown in case of malformed input. + */ + Event peekEvent(); - /** - * Returns the next event. - * <p> - * The event will be removed from the stream. - * </p> - * - * @throws ParserException - * Thrown in case of malformed input. - */ - public Event getEvent(); + /** + * Returns the next event. + * <p> + * The event will be removed from the stream. + * </p> + * + * @return the next parsed event + * @throws ParserException Thrown in case of malformed input. + */ + Event getEvent(); } diff --git a/src/main/java/org/yaml/snakeyaml/parser/ParserException.java b/src/main/java/org/yaml/snakeyaml/parser/ParserException.java index fd4b1f1c..90e49c08 100644 --- a/src/main/java/org/yaml/snakeyaml/parser/ParserException.java +++ b/src/main/java/org/yaml/snakeyaml/parser/ParserException.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.parser; @@ -19,26 +17,21 @@ import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.MarkedYAMLException; /** - * Exception thrown by the {@link Parser} implementations in case of malformed - * input. + * Exception thrown by the {@link Parser} implementations in case of malformed input. */ public class ParserException extends MarkedYAMLException { - private static final long serialVersionUID = -2349253802798398038L; - /** - * Constructs an instance. - * - * @param context - * Part of the input document in which vicinity the problem - * occurred. - * @param contextMark - * Position of the <code>context</code> within the document. - * @param problem - * Part of the input document that caused the problem. - * @param problemMark - * Position of the <code>problem</code>. within the document. - */ - public ParserException(String context, Mark contextMark, String problem, Mark problemMark) { - super(context, contextMark, problem, problemMark, null, null); - } + private static final long serialVersionUID = -2349253802798398038L; + + /** + * Constructs an instance. + * + * @param context Part of the input document in which vicinity the problem occurred. + * @param contextMark Position of the <code>context</code> within the document. + * @param problem Part of the input document that caused the problem. + * @param problemMark Position of the <code>problem</code>. within the document. + */ + public ParserException(String context, Mark contextMark, String problem, Mark problemMark) { + super(context, contextMark, problem, problemMark, null, null); + } } diff --git a/src/main/java/org/yaml/snakeyaml/parser/ParserImpl.java b/src/main/java/org/yaml/snakeyaml/parser/ParserImpl.java index 7fea2eec..7c66434f 100644 --- a/src/main/java/org/yaml/snakeyaml/parser/ParserImpl.java +++ b/src/main/java/org/yaml/snakeyaml/parser/ParserImpl.java @@ -1,28 +1,30 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.parser; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.Version; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.comments.CommentType; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.events.AliasEvent; +import org.yaml.snakeyaml.events.CommentEvent; import org.yaml.snakeyaml.events.DocumentEndEvent; import org.yaml.snakeyaml.events.DocumentStartEvent; import org.yaml.snakeyaml.events.Event; @@ -41,6 +43,7 @@ import org.yaml.snakeyaml.scanner.ScannerImpl; import org.yaml.snakeyaml.tokens.AliasToken; import org.yaml.snakeyaml.tokens.AnchorToken; import org.yaml.snakeyaml.tokens.BlockEntryToken; +import org.yaml.snakeyaml.tokens.CommentToken; import org.yaml.snakeyaml.tokens.DirectiveToken; import org.yaml.snakeyaml.tokens.ScalarToken; import org.yaml.snakeyaml.tokens.StreamEndToken; @@ -109,686 +112,863 @@ import org.yaml.snakeyaml.util.ArrayStack; * flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } * flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } * </pre> - * - * Since writing a recursive-descendant parser is a straightforward task, we do - * not give many comments here. + * + * Since writing a recursive-descendant parser is a straightforward task, we do not give many + * comments here. */ public class ParserImpl implements Parser { - private static final Map<String, String> DEFAULT_TAGS = new HashMap<String, String>(); - static { - DEFAULT_TAGS.put("!", "!"); - DEFAULT_TAGS.put("!!", Tag.PREFIX); - } - - protected final Scanner scanner; - private Event currentEvent; - private final ArrayStack<Production> states; - private final ArrayStack<Mark> marks; - private Production state; - private VersionTagsTuple directives; - - public ParserImpl(StreamReader reader) { - this(new ScannerImpl(reader)); - } - - public ParserImpl(Scanner scanner) { - this.scanner = scanner; - currentEvent = null; - directives = new VersionTagsTuple(null, new HashMap<String, String>(DEFAULT_TAGS)); - states = new ArrayStack<Production>(100); - marks = new ArrayStack<Mark>(10); - state = new ParseStreamStart(); - } - - /** - * Check the type of the next event. - */ - public boolean checkEvent(Event.ID choice) { - peekEvent(); - return currentEvent != null && currentEvent.is(choice); - } - - /** - * Get the next event. - */ - public Event peekEvent() { - if (currentEvent == null) { - if (state != null) { - currentEvent = state.produce(); - } - } - return currentEvent; - } - - /** - * Get the next event and proceed further. - */ - public Event getEvent() { - peekEvent(); - Event value = currentEvent; - currentEvent = null; - return value; - } - - /** - * <pre> - * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END - * implicit_document ::= block_node DOCUMENT-END* - * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* - * </pre> - */ - private class ParseStreamStart implements Production { - public Event produce() { - // Parse the stream start. - StreamStartToken token = (StreamStartToken) scanner.getToken(); - Event event = new StreamStartEvent(token.getStartMark(), token.getEndMark()); - // Prepare the next state. - state = new ParseImplicitDocumentStart(); - return event; - } - } - - private class ParseImplicitDocumentStart implements Production { - public Event produce() { - // Parse an implicit document. - if (!scanner.checkToken(Token.ID.Directive, Token.ID.DocumentStart, Token.ID.StreamEnd)) { - directives = new VersionTagsTuple(null, DEFAULT_TAGS); - Token token = scanner.peekToken(); - Mark startMark = token.getStartMark(); - Mark endMark = startMark; - Event event = new DocumentStartEvent(startMark, endMark, false, null, null); - // Prepare the next state. - states.push(new ParseDocumentEnd()); - state = new ParseBlockNode(); - return event; - } else { - Production p = new ParseDocumentStart(); - return p.produce(); - } - } - } - - private class ParseDocumentStart implements Production { - public Event produce() { - // Parse any extra document end indicators. - while (scanner.checkToken(Token.ID.DocumentEnd)) { - scanner.getToken(); - } - // Parse an explicit document. - Event event; - if (!scanner.checkToken(Token.ID.StreamEnd)) { - Token token = scanner.peekToken(); - Mark startMark = token.getStartMark(); - VersionTagsTuple tuple = processDirectives(); - if (!scanner.checkToken(Token.ID.DocumentStart)) { - throw new ParserException(null, null, "expected '<document start>', but found " - + scanner.peekToken().getTokenId(), scanner.peekToken().getStartMark()); - } - token = scanner.getToken(); - Mark endMark = token.getEndMark(); - event = new DocumentStartEvent(startMark, endMark, true, tuple.getVersion(), - tuple.getTags()); - states.push(new ParseDocumentEnd()); - state = new ParseDocumentContent(); - } else { - // Parse the end of the stream. - StreamEndToken token = (StreamEndToken) scanner.getToken(); - event = new StreamEndEvent(token.getStartMark(), token.getEndMark()); - if (!states.isEmpty()) { - throw new YAMLException("Unexpected end of stream. States left: " + states); - } - if (!marks.isEmpty()) { - throw new YAMLException("Unexpected end of stream. Marks left: " + marks); - } - state = null; - } - return event; - } - } - - private class ParseDocumentEnd implements Production { - public Event produce() { - // Parse the document end. - Token token = scanner.peekToken(); - Mark startMark = token.getStartMark(); - Mark endMark = startMark; - boolean explicit = false; - if (scanner.checkToken(Token.ID.DocumentEnd)) { - token = scanner.getToken(); - endMark = token.getEndMark(); - explicit = true; - } - Event event = new DocumentEndEvent(startMark, endMark, explicit); - // Prepare the next state. - state = new ParseDocumentStart(); - return event; - } - } - private class ParseDocumentContent implements Production { - public Event produce() { - Event event; - if (scanner.checkToken(Token.ID.Directive, Token.ID.DocumentStart, - Token.ID.DocumentEnd, Token.ID.StreamEnd)) { - event = processEmptyScalar(scanner.peekToken().getStartMark()); - state = states.pop(); - return event; - } else { - Production p = new ParseBlockNode(); - return p.produce(); - } + private static final Map<String, String> DEFAULT_TAGS = new HashMap<String, String>(); + + static { + DEFAULT_TAGS.put("!", "!"); + DEFAULT_TAGS.put("!!", Tag.PREFIX); + } + + protected final Scanner scanner; + private Event currentEvent; + private final ArrayStack<Production> states; + private final ArrayStack<Mark> marks; + private Production state; + private VersionTagsTuple directives; + + public ParserImpl(StreamReader reader) { + this(new ScannerImpl(reader)); + } + + @Deprecated + public ParserImpl(StreamReader reader, boolean parseComments) { + this(new ScannerImpl(reader, new LoaderOptions().setProcessComments(parseComments))); + } + + public ParserImpl(StreamReader reader, LoaderOptions options) { + this(new ScannerImpl(reader, options)); + } + + public ParserImpl(Scanner scanner) { + this.scanner = scanner; + currentEvent = null; + directives = new VersionTagsTuple(null, new HashMap<String, String>(DEFAULT_TAGS)); + states = new ArrayStack<Production>(100); + marks = new ArrayStack<Mark>(10); + state = new ParseStreamStart(); + } + + /** + * Check the type of the next event. + */ + public boolean checkEvent(Event.ID choice) { + peekEvent(); + return currentEvent != null && currentEvent.is(choice); + } + + /** + * Get the next event. + */ + public Event peekEvent() { + if (currentEvent == null) { + if (state != null) { + currentEvent = state.produce(); + } + } + return currentEvent; + } + + /** + * Get the next event and proceed further. + */ + public Event getEvent() { + peekEvent(); + Event value = currentEvent; + currentEvent = null; + return value; + } + + private CommentEvent produceCommentEvent(CommentToken token) { + Mark startMark = token.getStartMark(); + Mark endMark = token.getEndMark(); + String value = token.getValue(); + CommentType type = token.getCommentType(); + + // state = state, that no change in state + + return new CommentEvent(type, value, startMark, endMark); + } + + /** + * <pre> + * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END + * implicit_document ::= block_node DOCUMENT-END* + * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + * </pre> + */ + private class ParseStreamStart implements Production { + + public Event produce() { + // Parse the stream start. + StreamStartToken token = (StreamStartToken) scanner.getToken(); + Event event = new StreamStartEvent(token.getStartMark(), token.getEndMark()); + // Prepare the next state. + state = new ParseImplicitDocumentStart(); + return event; + } + } + + private class ParseImplicitDocumentStart implements Production { + + public Event produce() { + // Parse an implicit document. + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseImplicitDocumentStart(); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (!scanner.checkToken(Token.ID.Directive, Token.ID.DocumentStart, Token.ID.StreamEnd)) { + Token token = scanner.peekToken(); + Mark startMark = token.getStartMark(); + Mark endMark = startMark; + Event event = new DocumentStartEvent(startMark, endMark, false, null, null); + // Prepare the next state. + states.push(new ParseDocumentEnd()); + state = new ParseBlockNode(); + return event; + } + return new ParseDocumentStart().produce(); + } + } + + private class ParseDocumentStart implements Production { + + public Event produce() { + // Parse any extra document end indicators. + while (scanner.checkToken(Token.ID.DocumentEnd)) { + scanner.getToken(); + } + // Parse an explicit document. + Event event; + if (!scanner.checkToken(Token.ID.StreamEnd)) { + Token token = scanner.peekToken(); + Mark startMark = token.getStartMark(); + VersionTagsTuple tuple = processDirectives(); + while (scanner.checkToken(Token.ID.Comment)) { + // TODO: till we figure out what todo with the comments + scanner.getToken(); } - } - - @SuppressWarnings("unchecked") - private VersionTagsTuple processDirectives() { - Version yamlVersion = null; - HashMap<String, String> tagHandles = new HashMap<String, String>(); - while (scanner.checkToken(Token.ID.Directive)) { - @SuppressWarnings("rawtypes") - DirectiveToken token = (DirectiveToken) scanner.getToken(); - if (token.getName().equals("YAML")) { - if (yamlVersion != null) { - throw new ParserException(null, null, "found duplicate YAML directive", - token.getStartMark()); - } - List<Integer> value = (List<Integer>) token.getValue(); - Integer major = value.get(0); - if (major != 1) { - throw new ParserException(null, null, - "found incompatible YAML document (version 1.* is required)", - token.getStartMark()); - } - Integer minor = value.get(1); - switch (minor) { - case 0: - yamlVersion = Version.V1_0; - break; - - default: - yamlVersion = Version.V1_1; - break; - } - } else if (token.getName().equals("TAG")) { - List<String> value = (List<String>) token.getValue(); - String handle = value.get(0); - String prefix = value.get(1); - if (tagHandles.containsKey(handle)) { - throw new ParserException(null, null, "duplicate tag handle " + handle, - token.getStartMark()); - } - tagHandles.put(handle, prefix); - } + if (!scanner.checkToken(Token.ID.StreamEnd)) { + if (!scanner.checkToken(Token.ID.DocumentStart)) { + throw new ParserException(null, null, + "expected '<document start>', but found '" + scanner.peekToken().getTokenId() + "'", + scanner.peekToken().getStartMark()); + } + token = scanner.getToken(); + Mark endMark = token.getEndMark(); + event = + new DocumentStartEvent(startMark, endMark, true, tuple.getVersion(), tuple.getTags()); + states.push(new ParseDocumentEnd()); + state = new ParseDocumentContent(); + return event; } - if (yamlVersion != null || !tagHandles.isEmpty()) { - // directives in the document found - drop the previous - for (String key : DEFAULT_TAGS.keySet()) { - // do not overwrite re-defined tags - if (!tagHandles.containsKey(key)) { - tagHandles.put(key, DEFAULT_TAGS.get(key)); - } - } - directives = new VersionTagsTuple(yamlVersion, tagHandles); + } + // Parse the end of the stream. + StreamEndToken token = (StreamEndToken) scanner.getToken(); + event = new StreamEndEvent(token.getStartMark(), token.getEndMark()); + if (!states.isEmpty()) { + throw new YAMLException("Unexpected end of stream. States left: " + states); + } + if (!marks.isEmpty()) { + throw new YAMLException("Unexpected end of stream. Marks left: " + marks); + } + state = null; + return event; + } + } + + private class ParseDocumentEnd implements Production { + + public Event produce() { + // Parse the document end. + Token token = scanner.peekToken(); + Mark startMark = token.getStartMark(); + Mark endMark = startMark; + boolean explicit = false; + if (scanner.checkToken(Token.ID.DocumentEnd)) { + token = scanner.getToken(); + endMark = token.getEndMark(); + explicit = true; + } + Event event = new DocumentEndEvent(startMark, endMark, explicit); + // Prepare the next state. + state = new ParseDocumentStart(); + return event; + } + } + + private class ParseDocumentContent implements Production { + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseDocumentContent(); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (scanner.checkToken(Token.ID.Directive, Token.ID.DocumentStart, Token.ID.DocumentEnd, + Token.ID.StreamEnd)) { + Event event = processEmptyScalar(scanner.peekToken().getStartMark()); + state = states.pop(); + return event; + } + return new ParseBlockNode().produce(); + } + } + + /** + * https://yaml.org/spec/1.1/#id898785 says "If the document specifies no directives, it is parsed + * using the same settings as the previous document. If the document does specify any directives, + * all directives of previous documents, if any, are ignored." TODO the last statement is not + * respected (as in PyYAML, to work the same) + * + * @return directives to be applied for the current document + */ + @SuppressWarnings("unchecked") + private VersionTagsTuple processDirectives() { + HashMap<String, String> tagHandles = new HashMap<String, String>(directives.getTags()); + for (String key : DEFAULT_TAGS.keySet()) { + tagHandles.remove(key); + } + // keep only added tag handlers + directives = new VersionTagsTuple(null, tagHandles); + while (scanner.checkToken(Token.ID.Directive)) { + @SuppressWarnings("rawtypes") + DirectiveToken token = (DirectiveToken) scanner.getToken(); + if (token.getName().equals("YAML")) { + if (directives.getVersion() != null) { + throw new ParserException(null, null, "found duplicate YAML directive", + token.getStartMark()); } - return directives; - } - - /** - * <pre> - * block_node_or_indentless_sequence ::= ALIAS - * | properties (block_content | indentless_block_sequence)? - * | block_content - * | indentless_block_sequence - * block_node ::= ALIAS - * | properties block_content? - * | block_content - * flow_node ::= ALIAS - * | properties flow_content? - * | flow_content - * properties ::= TAG ANCHOR? | ANCHOR TAG? - * block_content ::= block_collection | flow_collection | SCALAR - * flow_content ::= flow_collection | SCALAR - * block_collection ::= block_sequence | block_mapping - * flow_collection ::= flow_sequence | flow_mapping - * </pre> - */ - - private class ParseBlockNode implements Production { - public Event produce() { - return parseNode(true, false); + List<Integer> value = (List<Integer>) token.getValue(); + Integer major = value.get(0); + if (major != 1) { + throw new ParserException(null, null, + "found incompatible YAML document (version 1.* is required)", token.getStartMark()); } - } - - private Event parseFlowNode() { - return parseNode(false, false); - } - - private Event parseBlockNodeOrIndentlessSequence() { - return parseNode(true, true); - } - - private Event parseNode(boolean block, boolean indentlessSequence) { - Event event; - Mark startMark = null; - Mark endMark = null; - Mark tagMark = null; - if (scanner.checkToken(Token.ID.Alias)) { - AliasToken token = (AliasToken) scanner.getToken(); - event = new AliasEvent(token.getValue(), token.getStartMark(), token.getEndMark()); - state = states.pop(); + Integer minor = value.get(1); + // TODO refactor with ternary + if (minor == 0) { + directives = new VersionTagsTuple(Version.V1_0, tagHandles); } else { - String anchor = null; - TagTuple tagTokenTag = null; - if (scanner.checkToken(Token.ID.Anchor)) { - AnchorToken token = (AnchorToken) scanner.getToken(); - startMark = token.getStartMark(); - endMark = token.getEndMark(); - anchor = token.getValue(); - if (scanner.checkToken(Token.ID.Tag)) { - TagToken tagToken = (TagToken) scanner.getToken(); - tagMark = tagToken.getStartMark(); - endMark = tagToken.getEndMark(); - tagTokenTag = tagToken.getValue(); - } - } else if (scanner.checkToken(Token.ID.Tag)) { - TagToken tagToken = (TagToken) scanner.getToken(); - startMark = tagToken.getStartMark(); - tagMark = startMark; - endMark = tagToken.getEndMark(); - tagTokenTag = tagToken.getValue(); - if (scanner.checkToken(Token.ID.Anchor)) { - AnchorToken token = (AnchorToken) scanner.getToken(); - endMark = token.getEndMark(); - anchor = token.getValue(); - } - } - String tag = null; - if (tagTokenTag != null) { - String handle = tagTokenTag.getHandle(); - String suffix = tagTokenTag.getSuffix(); - if (handle != null) { - if (!directives.getTags().containsKey(handle)) { - throw new ParserException("while parsing a node", startMark, - "found undefined tag handle " + handle, tagMark); - } - tag = directives.getTags().get(handle) + suffix; - } else { - tag = suffix; - } - } - if (startMark == null) { - startMark = scanner.peekToken().getStartMark(); - endMark = startMark; - } - event = null; - boolean implicit = tag == null || tag.equals("!"); - if (indentlessSequence && scanner.checkToken(Token.ID.BlockEntry)) { - endMark = scanner.peekToken().getEndMark(); - event = new SequenceStartEvent(anchor, tag, implicit, startMark, endMark, - Boolean.FALSE); - state = new ParseIndentlessSequenceEntry(); - } else { - if (scanner.checkToken(Token.ID.Scalar)) { - ScalarToken token = (ScalarToken) scanner.getToken(); - endMark = token.getEndMark(); - ImplicitTuple implicitValues; - if ((token.getPlain() && tag == null) || "!".equals(tag)) { - implicitValues = new ImplicitTuple(true, false); - } else if (tag == null) { - implicitValues = new ImplicitTuple(false, true); - } else { - implicitValues = new ImplicitTuple(false, false); - } - event = new ScalarEvent(anchor, tag, implicitValues, token.getValue(), - startMark, endMark, token.getStyle()); - state = states.pop(); - } else if (scanner.checkToken(Token.ID.FlowSequenceStart)) { - endMark = scanner.peekToken().getEndMark(); - event = new SequenceStartEvent(anchor, tag, implicit, startMark, endMark, - Boolean.TRUE); - state = new ParseFlowSequenceFirstEntry(); - } else if (scanner.checkToken(Token.ID.FlowMappingStart)) { - endMark = scanner.peekToken().getEndMark(); - event = new MappingStartEvent(anchor, tag, implicit, startMark, endMark, - Boolean.TRUE); - state = new ParseFlowMappingFirstKey(); - } else if (block && scanner.checkToken(Token.ID.BlockSequenceStart)) { - endMark = scanner.peekToken().getStartMark(); - event = new SequenceStartEvent(anchor, tag, implicit, startMark, endMark, - Boolean.FALSE); - state = new ParseBlockSequenceFirstEntry(); - } else if (block && scanner.checkToken(Token.ID.BlockMappingStart)) { - endMark = scanner.peekToken().getStartMark(); - event = new MappingStartEvent(anchor, tag, implicit, startMark, endMark, - Boolean.FALSE); - state = new ParseBlockMappingFirstKey(); - } else if (anchor != null || tag != null) { - // Empty scalars are allowed even if a tag or an anchor is - // specified. - event = new ScalarEvent(anchor, tag, new ImplicitTuple(implicit, false), "", - startMark, endMark, (char) 0); - state = states.pop(); - } else { - String node; - if (block) { - node = "block"; - } else { - node = "flow"; - } - Token token = scanner.peekToken(); - throw new ParserException("while parsing a " + node + " node", startMark, - "expected the node content, but found " + token.getTokenId(), - token.getStartMark()); - } - } - } - return event; - } - - // block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* - // BLOCK-END - - private class ParseBlockSequenceFirstEntry implements Production { - public Event produce() { - Token token = scanner.getToken(); - marks.push(token.getStartMark()); - return new ParseBlockSequenceEntry().produce(); + directives = new VersionTagsTuple(Version.V1_1, tagHandles); } - } - - private class ParseBlockSequenceEntry implements Production { - public Event produce() { - if (scanner.checkToken(Token.ID.BlockEntry)) { - BlockEntryToken token = (BlockEntryToken) scanner.getToken(); - if (!scanner.checkToken(Token.ID.BlockEntry, Token.ID.BlockEnd)) { - states.push(new ParseBlockSequenceEntry()); - return new ParseBlockNode().produce(); - } else { - state = new ParseBlockSequenceEntry(); - return processEmptyScalar(token.getEndMark()); - } - } - if (!scanner.checkToken(Token.ID.BlockEnd)) { - Token token = scanner.peekToken(); - throw new ParserException("while parsing a block collection", marks.pop(), - "expected <block end>, but found " + token.getTokenId(), - token.getStartMark()); - } - Token token = scanner.getToken(); - Event event = new SequenceEndEvent(token.getStartMark(), token.getEndMark()); - state = states.pop(); - marks.pop(); - return event; - } - } - - // indentless_sequence ::= (BLOCK-ENTRY block_node?)+ - - private class ParseIndentlessSequenceEntry implements Production { - public Event produce() { - if (scanner.checkToken(Token.ID.BlockEntry)) { - Token token = scanner.getToken(); - if (!scanner.checkToken(Token.ID.BlockEntry, Token.ID.Key, Token.ID.Value, - Token.ID.BlockEnd)) { - states.push(new ParseIndentlessSequenceEntry()); - return new ParseBlockNode().produce(); - } else { - state = new ParseIndentlessSequenceEntry(); - return processEmptyScalar(token.getEndMark()); - } - } - Token token = scanner.peekToken(); - Event event = new SequenceEndEvent(token.getStartMark(), token.getEndMark()); - state = states.pop(); - return event; + } else if (token.getName().equals("TAG")) { + List<String> value = (List<String>) token.getValue(); + String handle = value.get(0); + String prefix = value.get(1); + if (tagHandles.containsKey(handle)) { + throw new ParserException(null, null, "duplicate tag handle " + handle, + token.getStartMark()); } - } - - private class ParseBlockMappingFirstKey implements Production { - public Event produce() { - Token token = scanner.getToken(); - marks.push(token.getStartMark()); - return new ParseBlockMappingKey().produce(); + tagHandles.put(handle, prefix); + } + } + HashMap<String, String> detectedTagHandles = new HashMap<String, String>(); + if (!tagHandles.isEmpty()) { + // copy from tagHandles + detectedTagHandles = new HashMap<String, String>(tagHandles); + } + // add default tag handlers to resolve tags + for (String key : DEFAULT_TAGS.keySet()) { + // do not overwrite re-defined tags + if (!tagHandles.containsKey(key)) { + tagHandles.put(key, DEFAULT_TAGS.get(key)); + } + } + // data for the events (no default tags added) + return new VersionTagsTuple(directives.getVersion(), detectedTagHandles); + } + + /** + * <pre> + * block_node_or_indentless_sequence ::= ALIAS + * | properties (block_content | indentless_block_sequence)? + * | block_content + * | indentless_block_sequence + * block_node ::= ALIAS + * | properties block_content? + * | block_content + * flow_node ::= ALIAS + * | properties flow_content? + * | flow_content + * properties ::= TAG ANCHOR? | ANCHOR TAG? + * block_content ::= block_collection | flow_collection | SCALAR + * flow_content ::= flow_collection | SCALAR + * block_collection ::= block_sequence | block_mapping + * flow_collection ::= flow_sequence | flow_mapping + * </pre> + */ + + private class ParseBlockNode implements Production { + + public Event produce() { + return parseNode(true, false); + } + } + + private Event parseFlowNode() { + return parseNode(false, false); + } + + private Event parseBlockNodeOrIndentlessSequence() { + return parseNode(true, true); + } + + private Event parseNode(boolean block, boolean indentlessSequence) { + Event event; + Mark startMark = null; + Mark endMark = null; + Mark tagMark = null; + if (scanner.checkToken(Token.ID.Alias)) { + AliasToken token = (AliasToken) scanner.getToken(); + event = new AliasEvent(token.getValue(), token.getStartMark(), token.getEndMark()); + state = states.pop(); + } else { + String anchor = null; + TagTuple tagTokenTag = null; + if (scanner.checkToken(Token.ID.Anchor)) { + AnchorToken token = (AnchorToken) scanner.getToken(); + startMark = token.getStartMark(); + endMark = token.getEndMark(); + anchor = token.getValue(); + if (scanner.checkToken(Token.ID.Tag)) { + TagToken tagToken = (TagToken) scanner.getToken(); + tagMark = tagToken.getStartMark(); + endMark = tagToken.getEndMark(); + tagTokenTag = tagToken.getValue(); } - } - - private class ParseBlockMappingKey implements Production { - public Event produce() { - if (scanner.checkToken(Token.ID.Key)) { - Token token = scanner.getToken(); - if (!scanner.checkToken(Token.ID.Key, Token.ID.Value, Token.ID.BlockEnd)) { - states.push(new ParseBlockMappingValue()); - return parseBlockNodeOrIndentlessSequence(); - } else { - state = new ParseBlockMappingValue(); - return processEmptyScalar(token.getEndMark()); - } - } - if (!scanner.checkToken(Token.ID.BlockEnd)) { - Token token = scanner.peekToken(); - throw new ParserException("while parsing a block mapping", marks.pop(), - "expected <block end>, but found " + token.getTokenId(), - token.getStartMark()); - } - Token token = scanner.getToken(); - Event event = new MappingEndEvent(token.getStartMark(), token.getEndMark()); - state = states.pop(); - marks.pop(); - return event; + } else if (scanner.checkToken(Token.ID.Tag)) { + TagToken tagToken = (TagToken) scanner.getToken(); + startMark = tagToken.getStartMark(); + tagMark = startMark; + endMark = tagToken.getEndMark(); + tagTokenTag = tagToken.getValue(); + if (scanner.checkToken(Token.ID.Anchor)) { + AnchorToken token = (AnchorToken) scanner.getToken(); + endMark = token.getEndMark(); + anchor = token.getValue(); } - } - - private class ParseBlockMappingValue implements Production { - public Event produce() { - if (scanner.checkToken(Token.ID.Value)) { - Token token = scanner.getToken(); - if (!scanner.checkToken(Token.ID.Key, Token.ID.Value, Token.ID.BlockEnd)) { - states.push(new ParseBlockMappingKey()); - return parseBlockNodeOrIndentlessSequence(); - } else { - state = new ParseBlockMappingKey(); - return processEmptyScalar(token.getEndMark()); - } - } - state = new ParseBlockMappingKey(); - Token token = scanner.peekToken(); - return processEmptyScalar(token.getStartMark()); + } + String tag = null; + if (tagTokenTag != null) { + String handle = tagTokenTag.getHandle(); + String suffix = tagTokenTag.getSuffix(); + if (handle != null) { + if (!directives.getTags().containsKey(handle)) { + throw new ParserException("while parsing a node", startMark, + "found undefined tag handle " + handle, tagMark); + } + tag = directives.getTags().get(handle) + suffix; + } else { + tag = suffix; } - } - - /** - * <pre> - * flow_sequence ::= FLOW-SEQUENCE-START - * (flow_sequence_entry FLOW-ENTRY)* - * flow_sequence_entry? - * FLOW-SEQUENCE-END - * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? - * Note that while production rules for both flow_sequence_entry and - * flow_mapping_entry are equal, their interpretations are different. - * For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?` - * generate an inline mapping (set syntax). - * </pre> - */ - private class ParseFlowSequenceFirstEntry implements Production { - public Event produce() { - Token token = scanner.getToken(); - marks.push(token.getStartMark()); - return new ParseFlowSequenceEntry(true).produce(); + } + if (startMark == null) { + startMark = scanner.peekToken().getStartMark(); + endMark = startMark; + } + event = null; + boolean implicit = tag == null || tag.equals("!"); + if (indentlessSequence && scanner.checkToken(Token.ID.BlockEntry)) { + endMark = scanner.peekToken().getEndMark(); + event = new SequenceStartEvent(anchor, tag, implicit, startMark, endMark, + DumperOptions.FlowStyle.BLOCK); + state = new ParseIndentlessSequenceEntryKey(); + } else { + if (scanner.checkToken(Token.ID.Scalar)) { + ScalarToken token = (ScalarToken) scanner.getToken(); + endMark = token.getEndMark(); + ImplicitTuple implicitValues; + if ((token.getPlain() && tag == null) || "!".equals(tag)) { + implicitValues = new ImplicitTuple(true, false); + } else if (tag == null) { + implicitValues = new ImplicitTuple(false, true); + } else { + implicitValues = new ImplicitTuple(false, false); + } + event = new ScalarEvent(anchor, tag, implicitValues, token.getValue(), startMark, endMark, + token.getStyle()); + state = states.pop(); + } else if (scanner.checkToken(Token.ID.FlowSequenceStart)) { + endMark = scanner.peekToken().getEndMark(); + event = new SequenceStartEvent(anchor, tag, implicit, startMark, endMark, + DumperOptions.FlowStyle.FLOW); + state = new ParseFlowSequenceFirstEntry(); + } else if (scanner.checkToken(Token.ID.FlowMappingStart)) { + endMark = scanner.peekToken().getEndMark(); + event = new MappingStartEvent(anchor, tag, implicit, startMark, endMark, + DumperOptions.FlowStyle.FLOW); + state = new ParseFlowMappingFirstKey(); + } else if (block && scanner.checkToken(Token.ID.BlockSequenceStart)) { + endMark = scanner.peekToken().getStartMark(); + event = new SequenceStartEvent(anchor, tag, implicit, startMark, endMark, + DumperOptions.FlowStyle.BLOCK); + state = new ParseBlockSequenceFirstEntry(); + } else if (block && scanner.checkToken(Token.ID.BlockMappingStart)) { + endMark = scanner.peekToken().getStartMark(); + event = new MappingStartEvent(anchor, tag, implicit, startMark, endMark, + DumperOptions.FlowStyle.BLOCK); + state = new ParseBlockMappingFirstKey(); + } else if (anchor != null || tag != null) { + // Empty scalars are allowed even if a tag or an anchor is + // specified. + event = new ScalarEvent(anchor, tag, new ImplicitTuple(implicit, false), "", startMark, + endMark, DumperOptions.ScalarStyle.PLAIN); + state = states.pop(); + } else { + Token token = scanner.peekToken(); + throw new ParserException("while parsing a " + (block ? "block" : "flow") + " node", + startMark, "expected the node content, but found '" + token.getTokenId() + "'", + token.getStartMark()); } - } + } + } + return event; + } + + // block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* + // BLOCK-END + + private class ParseBlockSequenceFirstEntry implements Production { + + public Event produce() { + Token token = scanner.getToken(); + marks.push(token.getStartMark()); + return new ParseBlockSequenceEntryKey().produce(); + } + } + + private class ParseBlockSequenceEntryKey implements Production { - private class ParseFlowSequenceEntry implements Production { - private boolean first = false; - - public ParseFlowSequenceEntry(boolean first) { - this.first = first; + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseBlockSequenceEntryKey(); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (scanner.checkToken(Token.ID.BlockEntry)) { + BlockEntryToken token = (BlockEntryToken) scanner.getToken(); + return new ParseBlockSequenceEntryValue(token).produce(); + } + if (!scanner.checkToken(Token.ID.BlockEnd)) { + Token token = scanner.peekToken(); + throw new ParserException("while parsing a block collection", marks.pop(), + "expected <block end>, but found '" + token.getTokenId() + "'", token.getStartMark()); + } + Token token = scanner.getToken(); + Event event = new SequenceEndEvent(token.getStartMark(), token.getEndMark()); + state = states.pop(); + marks.pop(); + return event; + } + } + + private class ParseBlockSequenceEntryValue implements Production { + + BlockEntryToken token; + + public ParseBlockSequenceEntryValue(final BlockEntryToken token) { + this.token = token; + } + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseBlockSequenceEntryValue(token); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (!scanner.checkToken(Token.ID.BlockEntry, Token.ID.BlockEnd)) { + states.push(new ParseBlockSequenceEntryKey()); + return new ParseBlockNode().produce(); + } else { + state = new ParseBlockSequenceEntryKey(); + return processEmptyScalar(token.getEndMark()); + } + } + } + + // indentless_sequence ::= (BLOCK-ENTRY block_node?)+ + + private class ParseIndentlessSequenceEntryKey implements Production { + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseIndentlessSequenceEntryKey(); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (scanner.checkToken(Token.ID.BlockEntry)) { + BlockEntryToken token = (BlockEntryToken) scanner.getToken(); + return new ParseIndentlessSequenceEntryValue(token).produce(); + } + Token token = scanner.peekToken(); + Event event = new SequenceEndEvent(token.getStartMark(), token.getEndMark()); + state = states.pop(); + return event; + } + } + + private class ParseIndentlessSequenceEntryValue implements Production { + + BlockEntryToken token; + + public ParseIndentlessSequenceEntryValue(final BlockEntryToken token) { + this.token = token; + } + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseIndentlessSequenceEntryValue(token); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (!scanner.checkToken(Token.ID.BlockEntry, Token.ID.Key, Token.ID.Value, + Token.ID.BlockEnd)) { + states.push(new ParseIndentlessSequenceEntryKey()); + return new ParseBlockNode().produce(); + } else { + state = new ParseIndentlessSequenceEntryKey(); + return processEmptyScalar(token.getEndMark()); + } + } + } + + private class ParseBlockMappingFirstKey implements Production { + + public Event produce() { + Token token = scanner.getToken(); + marks.push(token.getStartMark()); + return new ParseBlockMappingKey().produce(); + } + } + + private class ParseBlockMappingKey implements Production { + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseBlockMappingKey(); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (scanner.checkToken(Token.ID.Key)) { + Token token = scanner.getToken(); + if (!scanner.checkToken(Token.ID.Key, Token.ID.Value, Token.ID.BlockEnd)) { + states.push(new ParseBlockMappingValue()); + return parseBlockNodeOrIndentlessSequence(); + } else { + state = new ParseBlockMappingValue(); + return processEmptyScalar(token.getEndMark()); } - - public Event produce() { - if (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { - if (!first) { - if (scanner.checkToken(Token.ID.FlowEntry)) { - scanner.getToken(); - } else { - Token token = scanner.peekToken(); - throw new ParserException("while parsing a flow sequence", marks.pop(), - "expected ',' or ']', but got " + token.getTokenId(), - token.getStartMark()); - } - } - if (scanner.checkToken(Token.ID.Key)) { - Token token = scanner.peekToken(); - Event event = new MappingStartEvent(null, null, true, token.getStartMark(), - token.getEndMark(), Boolean.TRUE); - state = new ParseFlowSequenceEntryMappingKey(); - return event; - } else if (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { - states.push(new ParseFlowSequenceEntry(false)); - return parseFlowNode(); - } - } - Token token = scanner.getToken(); - Event event = new SequenceEndEvent(token.getStartMark(), token.getEndMark()); - state = states.pop(); - marks.pop(); - return event; + } + if (!scanner.checkToken(Token.ID.BlockEnd)) { + Token token = scanner.peekToken(); + throw new ParserException("while parsing a block mapping", marks.pop(), + "expected <block end>, but found '" + token.getTokenId() + "'", token.getStartMark()); + } + Token token = scanner.getToken(); + Event event = new MappingEndEvent(token.getStartMark(), token.getEndMark()); + state = states.pop(); + marks.pop(); + return event; + } + } + + private class ParseBlockMappingValue implements Production { + + public Event produce() { + if (scanner.checkToken(Token.ID.Value)) { + Token token = scanner.getToken(); + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseBlockMappingValueComment(); + return state.produce(); + } else if (!scanner.checkToken(Token.ID.Key, Token.ID.Value, Token.ID.BlockEnd)) { + states.push(new ParseBlockMappingKey()); + return parseBlockNodeOrIndentlessSequence(); + } else { + state = new ParseBlockMappingKey(); + return processEmptyScalar(token.getEndMark()); } - } - - private class ParseFlowSequenceEntryMappingKey implements Production { - public Event produce() { - Token token = scanner.getToken(); - if (!scanner.checkToken(Token.ID.Value, Token.ID.FlowEntry, Token.ID.FlowSequenceEnd)) { - states.push(new ParseFlowSequenceEntryMappingValue()); - return parseFlowNode(); - } else { - state = new ParseFlowSequenceEntryMappingValue(); - return processEmptyScalar(token.getEndMark()); - } + } else if (scanner.checkToken(Token.ID.Scalar)) { + states.push(new ParseBlockMappingKey()); + return parseBlockNodeOrIndentlessSequence(); + } + state = new ParseBlockMappingKey(); + Token token = scanner.peekToken(); + return processEmptyScalar(token.getStartMark()); + } + } + + private class ParseBlockMappingValueComment implements Production { + + List<CommentToken> tokens = new LinkedList<>(); + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + tokens.add((CommentToken) scanner.getToken()); + return produce(); + } else if (!scanner.checkToken(Token.ID.Key, Token.ID.Value, Token.ID.BlockEnd)) { + if (!tokens.isEmpty()) { + return produceCommentEvent(tokens.remove(0)); } - } - - private class ParseFlowSequenceEntryMappingValue implements Production { - public Event produce() { - if (scanner.checkToken(Token.ID.Value)) { - Token token = scanner.getToken(); - if (!scanner.checkToken(Token.ID.FlowEntry, Token.ID.FlowSequenceEnd)) { - states.push(new ParseFlowSequenceEntryMappingEnd()); - return parseFlowNode(); - } else { - state = new ParseFlowSequenceEntryMappingEnd(); - return processEmptyScalar(token.getEndMark()); - } - } else { - state = new ParseFlowSequenceEntryMappingEnd(); - Token token = scanner.peekToken(); - return processEmptyScalar(token.getStartMark()); + states.push(new ParseBlockMappingKey()); + return parseBlockNodeOrIndentlessSequence(); + } else { + state = new ParseBlockMappingValueCommentList(tokens); + return processEmptyScalar(scanner.peekToken().getStartMark()); + } + } + } + + private class ParseBlockMappingValueCommentList implements Production { + + List<CommentToken> tokens; + + public ParseBlockMappingValueCommentList(final List<CommentToken> tokens) { + this.tokens = tokens; + } + + public Event produce() { + if (!tokens.isEmpty()) { + return produceCommentEvent(tokens.remove(0)); + } + return new ParseBlockMappingKey().produce(); + } + } + + /** + * <pre> + * flow_sequence ::= FLOW-SEQUENCE-START + * (flow_sequence_entry FLOW-ENTRY)* + * flow_sequence_entry? + * FLOW-SEQUENCE-END + * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * Note that while production rules for both flow_sequence_entry and + * flow_mapping_entry are equal, their interpretations are different. + * For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?` + * generate an inline mapping (set syntax). + * </pre> + */ + private class ParseFlowSequenceFirstEntry implements Production { + + public Event produce() { + Token token = scanner.getToken(); + marks.push(token.getStartMark()); + return new ParseFlowSequenceEntry(true).produce(); + } + } + + private class ParseFlowSequenceEntry implements Production { + + private final boolean first; + + public ParseFlowSequenceEntry(boolean first) { + this.first = first; + } + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseFlowSequenceEntry(first); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { + if (!first) { + if (scanner.checkToken(Token.ID.FlowEntry)) { + scanner.getToken(); + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseFlowSequenceEntry(true); + return produceCommentEvent((CommentToken) scanner.getToken()); } - } - } - - private class ParseFlowSequenceEntryMappingEnd implements Production { - public Event produce() { - state = new ParseFlowSequenceEntry(false); + } else { Token token = scanner.peekToken(); - return new MappingEndEvent(token.getStartMark(), token.getEndMark()); + throw new ParserException("while parsing a flow sequence", marks.pop(), + "expected ',' or ']', but got " + token.getTokenId(), token.getStartMark()); + } } - } - - /** - * <pre> - * flow_mapping ::= FLOW-MAPPING-START - * (flow_mapping_entry FLOW-ENTRY)* - * flow_mapping_entry? - * FLOW-MAPPING-END - * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? - * </pre> - */ - private class ParseFlowMappingFirstKey implements Production { - public Event produce() { - Token token = scanner.getToken(); - marks.push(token.getStartMark()); - return new ParseFlowMappingKey(true).produce(); + if (scanner.checkToken(Token.ID.Key)) { + Token token = scanner.peekToken(); + Event event = new MappingStartEvent(null, null, true, token.getStartMark(), + token.getEndMark(), DumperOptions.FlowStyle.FLOW); + state = new ParseFlowSequenceEntryMappingKey(); + return event; + } else if (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { + states.push(new ParseFlowSequenceEntry(false)); + return parseFlowNode(); } - } - - private class ParseFlowMappingKey implements Production { - private boolean first = false; - - public ParseFlowMappingKey(boolean first) { - this.first = first; + } + Token token = scanner.getToken(); + Event event = new SequenceEndEvent(token.getStartMark(), token.getEndMark()); + if (!scanner.checkToken(Token.ID.Comment)) { + state = states.pop(); + } else { + state = new ParseFlowEndComment(); + } + marks.pop(); + return event; + } + } + + private class ParseFlowEndComment implements Production { + + public Event produce() { + Event event = produceCommentEvent((CommentToken) scanner.getToken()); + if (!scanner.checkToken(Token.ID.Comment)) { + state = states.pop(); + } + return event; + } + } + + private class ParseFlowSequenceEntryMappingKey implements Production { + + public Event produce() { + Token token = scanner.getToken(); + if (!scanner.checkToken(Token.ID.Value, Token.ID.FlowEntry, Token.ID.FlowSequenceEnd)) { + states.push(new ParseFlowSequenceEntryMappingValue()); + return parseFlowNode(); + } else { + state = new ParseFlowSequenceEntryMappingValue(); + return processEmptyScalar(token.getEndMark()); + } + } + } + + private class ParseFlowSequenceEntryMappingValue implements Production { + + public Event produce() { + if (scanner.checkToken(Token.ID.Value)) { + Token token = scanner.getToken(); + if (!scanner.checkToken(Token.ID.FlowEntry, Token.ID.FlowSequenceEnd)) { + states.push(new ParseFlowSequenceEntryMappingEnd()); + return parseFlowNode(); + } else { + state = new ParseFlowSequenceEntryMappingEnd(); + return processEmptyScalar(token.getEndMark()); } - - public Event produce() { - if (!scanner.checkToken(Token.ID.FlowMappingEnd)) { - if (!first) { - if (scanner.checkToken(Token.ID.FlowEntry)) { - scanner.getToken(); - } else { - Token token = scanner.peekToken(); - throw new ParserException("while parsing a flow mapping", marks.pop(), - "expected ',' or '}', but got " + token.getTokenId(), - token.getStartMark()); - } - } - if (scanner.checkToken(Token.ID.Key)) { - Token token = scanner.getToken(); - if (!scanner.checkToken(Token.ID.Value, Token.ID.FlowEntry, - Token.ID.FlowMappingEnd)) { - states.push(new ParseFlowMappingValue()); - return parseFlowNode(); - } else { - state = new ParseFlowMappingValue(); - return processEmptyScalar(token.getEndMark()); - } - } else if (!scanner.checkToken(Token.ID.FlowMappingEnd)) { - states.push(new ParseFlowMappingEmptyValue()); - return parseFlowNode(); - } + } else { + state = new ParseFlowSequenceEntryMappingEnd(); + Token token = scanner.peekToken(); + return processEmptyScalar(token.getStartMark()); + } + } + } + + private class ParseFlowSequenceEntryMappingEnd implements Production { + + public Event produce() { + state = new ParseFlowSequenceEntry(false); + Token token = scanner.peekToken(); + return new MappingEndEvent(token.getStartMark(), token.getEndMark()); + } + } + + /** + * <pre> + * flow_mapping ::= FLOW-MAPPING-START + * (flow_mapping_entry FLOW-ENTRY)* + * flow_mapping_entry? + * FLOW-MAPPING-END + * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * </pre> + */ + private class ParseFlowMappingFirstKey implements Production { + + public Event produce() { + Token token = scanner.getToken(); + marks.push(token.getStartMark()); + return new ParseFlowMappingKey(true).produce(); + } + } + + private class ParseFlowMappingKey implements Production { + + private final boolean first; + + public ParseFlowMappingKey(boolean first) { + this.first = first; + } + + public Event produce() { + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseFlowMappingKey(first); + return produceCommentEvent((CommentToken) scanner.getToken()); + } + if (!scanner.checkToken(Token.ID.FlowMappingEnd)) { + if (!first) { + if (scanner.checkToken(Token.ID.FlowEntry)) { + scanner.getToken(); + if (scanner.checkToken(Token.ID.Comment)) { + state = new ParseFlowMappingKey(true); + return produceCommentEvent((CommentToken) scanner.getToken()); } - Token token = scanner.getToken(); - Event event = new MappingEndEvent(token.getStartMark(), token.getEndMark()); - state = states.pop(); - marks.pop(); - return event; + } else { + Token token = scanner.peekToken(); + throw new ParserException("while parsing a flow mapping", marks.pop(), + "expected ',' or '}', but got " + token.getTokenId(), token.getStartMark()); + } } - } - - private class ParseFlowMappingValue implements Production { - public Event produce() { - if (scanner.checkToken(Token.ID.Value)) { - Token token = scanner.getToken(); - if (!scanner.checkToken(Token.ID.FlowEntry, Token.ID.FlowMappingEnd)) { - states.push(new ParseFlowMappingKey(false)); - return parseFlowNode(); - } else { - state = new ParseFlowMappingKey(false); - return processEmptyScalar(token.getEndMark()); - } - } else { - state = new ParseFlowMappingKey(false); - Token token = scanner.peekToken(); - return processEmptyScalar(token.getStartMark()); - } + if (scanner.checkToken(Token.ID.Key)) { + Token token = scanner.getToken(); + if (!scanner.checkToken(Token.ID.Value, Token.ID.FlowEntry, Token.ID.FlowMappingEnd)) { + states.push(new ParseFlowMappingValue()); + return parseFlowNode(); + } else { + state = new ParseFlowMappingValue(); + return processEmptyScalar(token.getEndMark()); + } + } else if (!scanner.checkToken(Token.ID.FlowMappingEnd)) { + states.push(new ParseFlowMappingEmptyValue()); + return parseFlowNode(); } - } - - private class ParseFlowMappingEmptyValue implements Production { - public Event produce() { - state = new ParseFlowMappingKey(false); - return processEmptyScalar(scanner.peekToken().getStartMark()); + } + Token token = scanner.getToken(); + Event event = new MappingEndEvent(token.getStartMark(), token.getEndMark()); + marks.pop(); + if (!scanner.checkToken(Token.ID.Comment)) { + state = states.pop(); + } else { + state = new ParseFlowEndComment(); + } + return event; + } + } + + private class ParseFlowMappingValue implements Production { + + public Event produce() { + if (scanner.checkToken(Token.ID.Value)) { + Token token = scanner.getToken(); + if (!scanner.checkToken(Token.ID.FlowEntry, Token.ID.FlowMappingEnd)) { + states.push(new ParseFlowMappingKey(false)); + return parseFlowNode(); + } else { + state = new ParseFlowMappingKey(false); + return processEmptyScalar(token.getEndMark()); } - } - - /** - * <pre> - * block_mapping ::= BLOCK-MAPPING_START - * ((KEY block_node_or_indentless_sequence?)? - * (VALUE block_node_or_indentless_sequence?)?)* - * BLOCK-END - * </pre> - */ - private Event processEmptyScalar(Mark mark) { - return new ScalarEvent(null, null, new ImplicitTuple(true, false), "", mark, mark, (char) 0); - } + } else { + state = new ParseFlowMappingKey(false); + Token token = scanner.peekToken(); + return processEmptyScalar(token.getStartMark()); + } + } + } + + private class ParseFlowMappingEmptyValue implements Production { + + public Event produce() { + state = new ParseFlowMappingKey(false); + return processEmptyScalar(scanner.peekToken().getStartMark()); + } + } + + /** + * <pre> + * block_mapping ::= BLOCK-MAPPING_START + * ((KEY block_node_or_indentless_sequence?)? + * (VALUE block_node_or_indentless_sequence?)?)* + * BLOCK-END + * </pre> + */ + private Event processEmptyScalar(Mark mark) { + return new ScalarEvent(null, null, new ImplicitTuple(true, false), "", mark, mark, + DumperOptions.ScalarStyle.PLAIN); + } } diff --git a/src/main/java/org/yaml/snakeyaml/parser/Production.java b/src/main/java/org/yaml/snakeyaml/parser/Production.java index 5dd3949c..d886733c 100644 --- a/src/main/java/org/yaml/snakeyaml/parser/Production.java +++ b/src/main/java/org/yaml/snakeyaml/parser/Production.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.parser; import org.yaml.snakeyaml.events.Event; /** - * Helper for {@link ParserImpl}. A grammar rule to apply given the symbols on - * top of its stack and the next input token - * - * @see <a href="http://en.wikipedia.org/wiki/LL_parser"></a> + * Helper for {@link ParserImpl}. A grammar rule to apply given the symbols on top of its stack and + * the next input token + * + * @see <a href="http://en.wikipedia.org/wiki/LL_parser">LL parser</a> */ interface Production { - Event produce(); + + Event produce(); } diff --git a/src/main/java/org/yaml/snakeyaml/parser/VersionTagsTuple.java b/src/main/java/org/yaml/snakeyaml/parser/VersionTagsTuple.java index 44ed2fbb..6a2a1f64 100644 --- a/src/main/java/org/yaml/snakeyaml/parser/VersionTagsTuple.java +++ b/src/main/java/org/yaml/snakeyaml/parser/VersionTagsTuple.java @@ -1,46 +1,44 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.parser; import java.util.Map; - import org.yaml.snakeyaml.DumperOptions.Version; /** * Store the internal state for directives */ class VersionTagsTuple { - private Version version; - private Map<String, String> tags; - public VersionTagsTuple(Version version, Map<String, String> tags) { - this.version = version; - this.tags = tags; - } + private final Version version; + private final Map<String, String> tags; + + public VersionTagsTuple(Version version, Map<String, String> tags) { + this.version = version; + this.tags = tags; + } - public Version getVersion() { - return version; - } + public Version getVersion() { + return version; + } - public Map<String, String> getTags() { - return tags; - } + public Map<String, String> getTags() { + return tags; + } - @Override - public String toString() { - return String.format("VersionTagsTuple<%s, %s>", version, tags); - } + @Override + public String toString() { + return String.format("VersionTagsTuple<%s, %s>", version, tags); + } } diff --git a/src/main/java/org/yaml/snakeyaml/reader/ReaderException.java b/src/main/java/org/yaml/snakeyaml/reader/ReaderException.java index 7a8a06b2..d44141ec 100644 --- a/src/main/java/org/yaml/snakeyaml/reader/ReaderException.java +++ b/src/main/java/org/yaml/snakeyaml/reader/ReaderException.java @@ -1,51 +1,50 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.reader; import org.yaml.snakeyaml.error.YAMLException; public class ReaderException extends YAMLException { - private static final long serialVersionUID = 8710781187529689083L; - private final String name; - private final char character; - private final int position; - - public ReaderException(String name, int position, char character, String message) { - super(message); - this.name = name; - this.character = character; - this.position = position; - } - - public String getName() { - return name; - } - - public char getCharacter() { - return character; - } - - public int getPosition() { - return position; - } - - @Override - public String toString() { - return "unacceptable character '" + character + "' (0x" - + Integer.toHexString((int) character).toUpperCase() + ") " + getMessage() - + "\nin \"" + name + "\", position " + position; - } + + private static final long serialVersionUID = 8710781187529689083L; + private final String name; + private final int codePoint; + private final int position; + + public ReaderException(String name, int position, int codePoint, String message) { + super(message); + this.name = name; + this.codePoint = codePoint; + this.position = position; + } + + public String getName() { + return name; + } + + public int getCodePoint() { + return codePoint; + } + + public int getPosition() { + return position; + } + + @Override + public String toString() { + final String s = new String(Character.toChars(codePoint)); + return "unacceptable code point '" + s + "' (0x" + Integer.toHexString(codePoint).toUpperCase() + + ") " + getMessage() + "\nin \"" + name + "\", position " + position; + } } diff --git a/src/main/java/org/yaml/snakeyaml/reader/StreamReader.java b/src/main/java/org/yaml/snakeyaml/reader/StreamReader.java index 56ec0078..6799e76e 100644 --- a/src/main/java/org/yaml/snakeyaml/reader/StreamReader.java +++ b/src/main/java/org/yaml/snakeyaml/reader/StreamReader.java @@ -1,220 +1,230 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.reader; import java.io.IOException; import java.io.Reader; -import java.nio.charset.Charset; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - +import java.io.StringReader; +import java.util.Arrays; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.scanner.Constant; /** - * Reader: checks if characters are in allowed range, adds '\0' to the end. + * Reader: checks if code points are in allowed range. Returns '\0' when end of data has been + * reached. */ public class StreamReader { - public final static Pattern NON_PRINTABLE = Pattern - .compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFD]"); - private String name; - private final Reader stream; - private int pointer = 0; - private boolean eof = true; - private String buffer; - private int index = 0; - private int line = 0; - private int column = 0; - private char[] data; - - public StreamReader(String stream) { - this.name = "'string'"; - this.buffer = ""; // to set length to 0 - checkPrintable(stream); - this.buffer = stream + "\0"; - this.stream = null; - this.eof = true; - this.data = null; - } - - public StreamReader(Reader reader) { - this.name = "'reader'"; - this.buffer = ""; - this.stream = reader; - this.eof = false; - this.data = new char[1024]; - this.update(); - } - void checkPrintable(CharSequence data) { - Matcher em = NON_PRINTABLE.matcher(data); - if (em.find()) { - int position = this.index + this.buffer.length() - this.pointer + em.start(); - throw new ReaderException(name, position, em.group().charAt(0), - "special characters are not allowed"); + private String name; + private final Reader stream; + /** + * Read data (as a moving window for input stream) + */ + private int[] dataWindow; + + /** + * Real length of the data in dataWindow + */ + private int dataLength; + + /** + * The variable points to the current position in the data array + */ + private int pointer = 0; + private boolean eof; + private int index = 0; // in code points + private int line = 0; + private int column = 0; // in code points + private final char[] buffer; // temp buffer for one read operation (to avoid + // creating the array in stack) + + private static final int BUFFER_SIZE = 1025; + + public StreamReader(String stream) { + this(new StringReader(stream)); + this.name = "'string'"; + } + + public StreamReader(Reader reader) { + this.name = "'reader'"; + this.dataWindow = new int[0]; + this.dataLength = 0; + this.stream = reader; + this.eof = false; + this.buffer = new char[BUFFER_SIZE]; + } + + public static boolean isPrintable(final String data) { + final int length = data.length(); + for (int offset = 0; offset < length;) { + final int codePoint = data.codePointAt(offset); + + if (!isPrintable(codePoint)) { + return false; + } + + offset += Character.charCount(codePoint); + } + + return true; + } + + public static boolean isPrintable(final int c) { + return (c >= 0x20 && c <= 0x7E) || c == 0x9 || c == 0xA || c == 0xD || c == 0x85 + || (c >= 0xA0 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) + || (c >= 0x10000 && c <= 0x10FFFF); + } + + public Mark getMark() { + return new Mark(name, this.index, this.line, this.column, this.dataWindow, this.pointer); + } + + public void forward() { + forward(1); + } + + /** + * read the next length characters and move the pointer. if the last character is high surrogate + * one more character will be read + * + * @param length amount of characters to move forward + */ + public void forward(int length) { + for (int i = 0; i < length && ensureEnoughData(); i++) { + int c = dataWindow[pointer++]; + this.index++; + if (Constant.LINEBR.has(c) + || (c == '\r' && (ensureEnoughData() && dataWindow[pointer] != '\n'))) { + this.line++; + this.column = 0; + } else if (c != 0xFEFF) { + this.column++; + } + } + } + + public int peek() { + return (ensureEnoughData()) ? dataWindow[pointer] : '\0'; + } + + /** + * Peek the next index-th code point + * + * @param index to peek + * @return the next index-th code point + */ + public int peek(int index) { + return (ensureEnoughData(index)) ? dataWindow[pointer + index] : '\0'; + } + + /** + * peek the next length code points + * + * @param length amount of the characters to peek + * @return the next length code points + */ + public String prefix(int length) { + if (length == 0) { + return ""; + } else if (ensureEnoughData(length)) { + return new String(this.dataWindow, pointer, length); + } else { + return new String(this.dataWindow, pointer, Math.min(length, dataLength - pointer)); + } + } + + /** + * prefix(length) immediately followed by forward(length) + * + * @param length amount of characters to get + * @return the next length code points + */ + public String prefixForward(int length) { + final String prefix = prefix(length); + this.pointer += length; + this.index += length; + // prefix never contains new line characters + this.column += length; + return prefix; + } + + private boolean ensureEnoughData() { + return ensureEnoughData(0); + } + + private boolean ensureEnoughData(int size) { + if (!eof && pointer + size >= dataLength) { + update(); + } + return (this.pointer + size) < dataLength; + } + + private void update() { + try { + int read = stream.read(buffer, 0, BUFFER_SIZE - 1); + if (read > 0) { + int cpIndex = (dataLength - pointer); + dataWindow = Arrays.copyOfRange(dataWindow, pointer, dataLength + read); + + if (Character.isHighSurrogate(buffer[read - 1])) { + if (stream.read(buffer, read, 1) == -1) { + eof = true; + } else { + read++; + } } - } - /** - * Checks <code>chars</chars> for the non-printable characters. - * - * @param chars - * the array where to search. - * @param begin - * the beginning index, inclusive. - * @param end - * the ending index, exclusive. - * @throws ReaderException - * if <code>chars</code> contains non-printable character(s). - */ - void checkPrintable(final char[] chars, final int begin, final int end) { - for (int i = begin; i < end; i++) { - final char c = chars[i]; - - if (isPrintable(c)) { - continue; - } - - int position = this.index + this.buffer.length() - this.pointer + i; - throw new ReaderException(name, position, c, "special characters are not allowed"); + int nonPrintable = ' '; + for (int i = 0; i < read; cpIndex++) { + int codePoint = Character.codePointAt(buffer, i); + dataWindow[cpIndex] = codePoint; + if (isPrintable(codePoint)) { + i += Character.charCount(codePoint); + } else { + nonPrintable = codePoint; + i = read; + } } - } - - public static boolean isPrintable(final char c) { - return (c >= '\u0020' && c <= '\u007E') || c == '\n' || c == '\r' || c == '\t' - || c == '\u0085' || (c >= '\u00A0' && c <= '\uD7FF') - || (c >= '\uE000' && c <= '\uFFFD'); - } - public Mark getMark() { - return new Mark(name, this.index, this.line, this.column, this.buffer, this.pointer); - } - - public void forward() { - forward(1); - } - - /** - * read the next length characters and move the pointer. - * - * @param length - */ - public void forward(int length) { - if (this.pointer + length + 1 >= this.buffer.length()) { - update(); - } - char ch = 0; - for (int i = 0; i < length; i++) { - ch = this.buffer.charAt(this.pointer); - this.pointer++; - this.index++; - if (Constant.LINEBR.has(ch) || (ch == '\r' && buffer.charAt(pointer) != '\n')) { - this.line++; - this.column = 0; - } else if (ch != '\uFEFF') { - this.column++; - } + dataLength = cpIndex; + pointer = 0; + if (nonPrintable != ' ') { + throw new ReaderException(name, cpIndex - 1, nonPrintable, + "special characters are not allowed"); } + } else { + eof = true; + } + } catch (IOException ioe) { + throw new YAMLException(ioe); } + } - public char peek() { - return this.buffer.charAt(this.pointer); - } - /** - * Peek the next index-th character - * - * @param index - * @return the next index-th character - */ - public char peek(int index) { - if (this.pointer + index + 1 > this.buffer.length()) { - update(); - } - return this.buffer.charAt(this.pointer + index); - } + public int getColumn() { + return column; + } - /** - * peek the next length characters - * - * @param length - * @return the next length characters - */ - public String prefix(int length) { - if (this.pointer + length >= this.buffer.length()) { - update(); - } - if (this.pointer + length > this.buffer.length()) { - return this.buffer.substring(this.pointer); - } - return this.buffer.substring(this.pointer, this.pointer + length); - } - - /** - * prefix(length) immediately followed by forward(length) - */ - public String prefixForward(int length) { - final String prefix = prefix(length); - this.pointer += length; - this.index += length; - // prefix never contains new line characters - this.column += length; - return prefix; - } - - private void update() { - if (!this.eof) { - this.buffer = buffer.substring(this.pointer); - this.pointer = 0; - try { - int converted = this.stream.read(data); - if (converted > 0) { - /* - * Let's create StringBuilder manually. Anyway str1 + str2 - * generates new StringBuilder(str1).append(str2).toSting() - * Giving correct capacity to the constructor prevents - * unnecessary operations in appends. - */ - checkPrintable(data, 0, converted); - this.buffer = new StringBuilder(buffer.length() + converted).append(buffer) - .append(data, 0, converted).toString(); - } else { - this.eof = true; - this.buffer += "\0"; - } - } catch (IOException ioe) { - throw new YAMLException(ioe); - } - } - } + /** + * @return current position as number (in characters) from the beginning of the stream + */ + public int getIndex() { + return index; + } - public int getColumn() { - return column; - } - - public Charset getEncoding() { - return Charset.forName(((UnicodeReader) this.stream).getEncoding()); - } - - public int getIndex() { - return index; - } - - public int getLine() { - return line; - } + public int getLine() { + return line; + } } diff --git a/src/main/java/org/yaml/snakeyaml/reader/UnicodeReader.java b/src/main/java/org/yaml/snakeyaml/reader/UnicodeReader.java index dd9dc39b..4c9c9039 100644 --- a/src/main/java/org/yaml/snakeyaml/reader/UnicodeReader.java +++ b/src/main/java/org/yaml/snakeyaml/reader/UnicodeReader.java @@ -1,40 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.reader; /** - version: 1.1 / 2007-01-25 - - changed BOM recognition ordering (longer boms first) - - Original pseudocode : Thomas Weidenfeller - Implementation tweaked: Aki Nieminen - Implementation changed: Andrey Somov - * UTF-32 removed because it is not supported by YAML - * no default encoding - - http://www.unicode.org/unicode/faq/utf_bom.html - BOMs: - 00 00 FE FF = UTF-32, big-endian - FF FE 00 00 = UTF-32, little-endian - EF BB BF = UTF-8, - FE FF = UTF-16, big-endian - FF FE = UTF-16, little-endian - - Win2k Notepad: - Unicode format = UTF-16LE + * version: 1.1 / 2007-01-25 - changed BOM recognition ordering (longer boms first) + * + * Original pseudocode : Thomas Weidenfeller Implementation tweaked: Aki Nieminen Implementation + * changed: Andrey Somov UTF-32 removed because it is not supported by YAML no default encoding + * + * http://www.unicode.org/unicode/faq/utf_bom.html BOMs: 00 00 FE FF = UTF-32, big-endian FF FE 00 + * 00 = UTF-32, little-endian EF BB BF = UTF-8, FE FF = UTF-16, big-endian FF FE = UTF-16, + * little-endian + * + * Win2k Notepad: Unicode format = UTF-16LE ***/ import java.io.IOException; @@ -45,81 +34,87 @@ import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; /** - * Generic unicode textreader, which will use BOM mark to identify the encoding - * to be used. If BOM is not found then use a given default or system encoding. + * Generic unicode textreader, which will use BOM mark to identify the encoding to be used. If BOM + * is not found then use a given default or system encoding. */ public class UnicodeReader extends Reader { - private static final Charset UTF8 = Charset.forName("UTF-8"); - private static final Charset UTF16BE = Charset.forName("UTF-16BE"); - private static final Charset UTF16LE = Charset.forName("UTF-16LE"); - - PushbackInputStream internalIn; - InputStreamReader internalIn2 = null; - - private static final int BOM_SIZE = 3; - /** - * @param in - * InputStream to be read - */ - public UnicodeReader(InputStream in) { - internalIn = new PushbackInputStream(in, BOM_SIZE); + private static final Charset UTF8 = StandardCharsets.UTF_8; + private static final Charset UTF16BE = StandardCharsets.UTF_16BE; + private static final Charset UTF16LE = StandardCharsets.UTF_16LE; + + PushbackInputStream internalIn; + InputStreamReader internalIn2 = null; + + private static final int BOM_SIZE = 3; + + /** + * @param in InputStream to be read + */ + public UnicodeReader(InputStream in) { + internalIn = new PushbackInputStream(in, BOM_SIZE); + } + + /** + * Get stream encoding or NULL if stream is uninitialized. Call init() or read() method to + * initialize it. + * + * @return the name of the character encoding being used by this stream. + */ + public String getEncoding() { + return internalIn2.getEncoding(); + } + + /** + * Read-ahead four bytes and check for BOM marks. Extra bytes are unread back to the stream, only + * BOM bytes are skipped. + * + * @throws IOException if InputStream cannot be created + */ + protected void init() throws IOException { + if (internalIn2 != null) { + return; } - /** - * Get stream encoding or NULL if stream is uninitialized. Call init() or - * read() method to initialize it. - */ - public String getEncoding() { - return internalIn2.getEncoding(); + Charset encoding; + byte[] bom = new byte[BOM_SIZE]; + int n, unread; + n = internalIn.read(bom, 0, bom.length); + + if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) { + encoding = UTF8; + unread = n - 3; + } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) { + encoding = UTF16BE; + unread = n - 2; + } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) { + encoding = UTF16LE; + unread = n - 2; + } else { + // Unicode BOM mark not found, unread all bytes + encoding = UTF8; + unread = n; } - /** - * Read-ahead four bytes and check for BOM marks. Extra bytes are unread - * back to the stream, only BOM bytes are skipped. - */ - protected void init() throws IOException { - if (internalIn2 != null) - return; - - Charset encoding; - byte bom[] = new byte[BOM_SIZE]; - int n, unread; - n = internalIn.read(bom, 0, bom.length); - - if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) { - encoding = UTF8; - unread = n - 3; - } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) { - encoding = UTF16BE; - unread = n - 2; - } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) { - encoding = UTF16LE; - unread = n - 2; - } else { - // Unicode BOM mark not found, unread all bytes - encoding = UTF8; - unread = n; - } - - if (unread > 0) - internalIn.unread(bom, (n - unread), unread); - - // Use given encoding - CharsetDecoder decoder = encoding.newDecoder().onUnmappableCharacter( - CodingErrorAction.REPORT); - internalIn2 = new InputStreamReader(internalIn, decoder); + if (unread > 0) { + internalIn.unread(bom, (n - unread), unread); } - public void close() throws IOException { - init(); - internalIn2.close(); - } - - public int read(char[] cbuf, int off, int len) throws IOException { - init(); - return internalIn2.read(cbuf, off, len); - } -}
\ No newline at end of file + // Use given encoding + CharsetDecoder decoder = encoding.newDecoder().onUnmappableCharacter(CodingErrorAction.REPORT); + internalIn2 = new InputStreamReader(internalIn, decoder); + } + + public void close() throws IOException { + init(); + internalIn2.close(); + } + + public int read(char[] cbuf, int off, int len) throws IOException { + init(); + return internalIn2.read(cbuf, off, len); + } +} diff --git a/src/main/java/org/yaml/snakeyaml/representer/BaseRepresenter.java b/src/main/java/org/yaml/snakeyaml/representer/BaseRepresenter.java index c4419fb2..6257b4b6 100644 --- a/src/main/java/org/yaml/snakeyaml/representer/BaseRepresenter.java +++ b/src/main/java/org/yaml/snakeyaml/representer/BaseRepresenter.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; @@ -21,7 +19,7 @@ import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.DumperOptions.ScalarStyle; import org.yaml.snakeyaml.introspector.PropertyUtils; @@ -37,166 +35,175 @@ import org.yaml.snakeyaml.nodes.Tag; * Represent basic YAML structures: scalar, sequence, mapping */ public abstract class BaseRepresenter { - protected final Map<Class<?>, Represent> representers = new HashMap<Class<?>, Represent>(); - /** - * in Java 'null' is not a type. So we have to keep the null representer - * separately otherwise it will coincide with the default representer which - * is stored with the key null. - */ - protected Represent nullRepresenter; - // the order is important (map can be also a sequence of key-values) - protected final Map<Class<?>, Represent> multiRepresenters = new LinkedHashMap<Class<?>, Represent>(); - protected Character defaultScalarStyle; - protected FlowStyle defaultFlowStyle = FlowStyle.AUTO; - protected final Map<Object, Node> representedObjects = new IdentityHashMap<Object, Node>() { - private static final long serialVersionUID = -5576159264232131854L; - - public Node put(Object key, Node value) { - return super.put(key, new AnchorNode(value)); - } - }; - protected Object objectToRepresent; - private PropertyUtils propertyUtils; - private boolean explicitPropertyUtils = false; - - public Node represent(Object data) { - Node node = representData(data); - representedObjects.clear(); - objectToRepresent = null; - return node; + protected final Map<Class<?>, Represent> representers = new HashMap<Class<?>, Represent>(); + /** + * in Java 'null' is not a type. So we have to keep the null representer separately otherwise it + * will coincide with the default representer which is stored with the key null. + */ + protected Represent nullRepresenter; + // the order is important (map can be also a sequence of key-values) + protected final Map<Class<?>, Represent> multiRepresenters = + new LinkedHashMap<Class<?>, Represent>(); + protected DumperOptions.ScalarStyle defaultScalarStyle = null; // not explicitly defined + protected FlowStyle defaultFlowStyle = FlowStyle.AUTO; + protected final Map<Object, Node> representedObjects = new IdentityHashMap<Object, Node>() { + private static final long serialVersionUID = -5576159264232131854L; + + public Node put(Object key, Node value) { + return super.put(key, new AnchorNode(value)); } - - protected final Node representData(Object data) { - objectToRepresent = data; - // check for identity - if (representedObjects.containsKey(objectToRepresent)) { - Node node = representedObjects.get(objectToRepresent); - return node; - } - // } - // check for null first - if (data == null) { - Node node = nullRepresenter.representData(null); - return node; - } - // check the same class - Node node; - Class<?> clazz = data.getClass(); - if (representers.containsKey(clazz)) { - Represent representer = representers.get(clazz); - node = representer.representData(data); - } else { - // check the parents - for (Class<?> repr : multiRepresenters.keySet()) { - if (repr.isInstance(data)) { - Represent representer = multiRepresenters.get(repr); - node = representer.representData(data); - return node; - } - } - - // check defaults - if (multiRepresenters.containsKey(null)) { - Represent representer = multiRepresenters.get(null); - node = representer.representData(data); - } else { - Represent representer = representers.get(null); - node = representer.representData(data); - } - } - return node; + }; + + protected Object objectToRepresent; + private PropertyUtils propertyUtils; + private boolean explicitPropertyUtils = false; + + public Node represent(Object data) { + Node node = representData(data); + representedObjects.clear(); + objectToRepresent = null; + return node; + } + + protected final Node representData(Object data) { + objectToRepresent = data; + // check for identity + if (representedObjects.containsKey(objectToRepresent)) { + Node node = representedObjects.get(objectToRepresent); + return node; } - - protected Node representScalar(Tag tag, String value, Character style) { - if (style == null) { - style = this.defaultScalarStyle; + // } + // check for null first + if (data == null) { + Node node = nullRepresenter.representData(null); + return node; + } + // check the same class + Node node; + Class<?> clazz = data.getClass(); + if (representers.containsKey(clazz)) { + Represent representer = representers.get(clazz); + node = representer.representData(data); + } else { + // check the parents + for (Class<?> repr : multiRepresenters.keySet()) { + if (repr != null && repr.isInstance(data)) { + Represent representer = multiRepresenters.get(repr); + node = representer.representData(data); + return node; } - Node node = new ScalarNode(tag, value, null, null, style); - return node; + } + + // check defaults + if (multiRepresenters.containsKey(null)) { + Represent representer = multiRepresenters.get(null); + node = representer.representData(data); + } else { + Represent representer = representers.get(null); + node = representer.representData(data); + } } + return node; + } - protected Node representScalar(Tag tag, String value) { - return representScalar(tag, value, null); + protected Node representScalar(Tag tag, String value, DumperOptions.ScalarStyle style) { + if (style == null) { + style = this.defaultScalarStyle; } - - protected Node representSequence(Tag tag, Iterable<?> sequence, Boolean flowStyle) { - int size = 10;// default for ArrayList - if (sequence instanceof List<?>) { - size = ((List<?>) sequence).size(); - } - List<Node> value = new ArrayList<Node>(size); - SequenceNode node = new SequenceNode(tag, value, flowStyle); - representedObjects.put(objectToRepresent, node); - boolean bestStyle = true; - for (Object item : sequence) { - Node nodeItem = representData(item); - if (!(nodeItem instanceof ScalarNode && ((ScalarNode) nodeItem).getStyle() == null)) { - bestStyle = false; - } - value.add(nodeItem); - } - if (flowStyle == null) { - if (defaultFlowStyle != FlowStyle.AUTO) { - node.setFlowStyle(defaultFlowStyle.getStyleBoolean()); - } else { - node.setFlowStyle(bestStyle); - } - } - return node; + Node node = new ScalarNode(tag, value, null, null, style); + return node; + } + + protected Node representScalar(Tag tag, String value) { + return representScalar(tag, value, null); + } + + protected Node representSequence(Tag tag, Iterable<?> sequence, + DumperOptions.FlowStyle flowStyle) { + int size = 10;// default for ArrayList + if (sequence instanceof List<?>) { + size = ((List<?>) sequence).size(); } - - protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) { - List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size()); - MappingNode node = new MappingNode(tag, value, flowStyle); - representedObjects.put(objectToRepresent, node); - boolean bestStyle = true; - for (Map.Entry<?, ?> entry : mapping.entrySet()) { - Node nodeKey = representData(entry.getKey()); - Node nodeValue = representData(entry.getValue()); - if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null)) { - bestStyle = false; - } - if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) { - bestStyle = false; - } - value.add(new NodeTuple(nodeKey, nodeValue)); - } - if (flowStyle == null) { - if (defaultFlowStyle != FlowStyle.AUTO) { - node.setFlowStyle(defaultFlowStyle.getStyleBoolean()); - } else { - node.setFlowStyle(bestStyle); - } - } - return node; + List<Node> value = new ArrayList<Node>(size); + SequenceNode node = new SequenceNode(tag, value, flowStyle); + representedObjects.put(objectToRepresent, node); + DumperOptions.FlowStyle bestStyle = FlowStyle.FLOW; + for (Object item : sequence) { + Node nodeItem = representData(item); + if (!(nodeItem instanceof ScalarNode && ((ScalarNode) nodeItem).isPlain())) { + bestStyle = FlowStyle.BLOCK; + } + value.add(nodeItem); } - - public void setDefaultScalarStyle(ScalarStyle defaultStyle) { - this.defaultScalarStyle = defaultStyle.getChar(); + if (flowStyle == FlowStyle.AUTO) { + if (defaultFlowStyle != FlowStyle.AUTO) { + node.setFlowStyle(defaultFlowStyle); + } else { + node.setFlowStyle(bestStyle); + } } - - public void setDefaultFlowStyle(FlowStyle defaultFlowStyle) { - this.defaultFlowStyle = defaultFlowStyle; + return node; + } + + protected Node representMapping(Tag tag, Map<?, ?> mapping, DumperOptions.FlowStyle flowStyle) { + List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size()); + MappingNode node = new MappingNode(tag, value, flowStyle); + representedObjects.put(objectToRepresent, node); + DumperOptions.FlowStyle bestStyle = FlowStyle.FLOW; + for (Map.Entry<?, ?> entry : mapping.entrySet()) { + Node nodeKey = representData(entry.getKey()); + Node nodeValue = representData(entry.getValue()); + if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).isPlain())) { + bestStyle = FlowStyle.BLOCK; + } + if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).isPlain())) { + bestStyle = FlowStyle.BLOCK; + } + value.add(new NodeTuple(nodeKey, nodeValue)); } - - public FlowStyle getDefaultFlowStyle() { - return this.defaultFlowStyle; + if (flowStyle == FlowStyle.AUTO) { + if (defaultFlowStyle != FlowStyle.AUTO) { + node.setFlowStyle(defaultFlowStyle); + } else { + node.setFlowStyle(bestStyle); + } } + return node; + } - public void setPropertyUtils(PropertyUtils propertyUtils) { - this.propertyUtils = propertyUtils; - this.explicitPropertyUtils = true; - } + public void setDefaultScalarStyle(ScalarStyle defaultStyle) { + this.defaultScalarStyle = defaultStyle; + } - public final PropertyUtils getPropertyUtils() { - if (propertyUtils == null) { - propertyUtils = new PropertyUtils(); - } - return propertyUtils; + public ScalarStyle getDefaultScalarStyle() { + if (defaultScalarStyle == null) { + return ScalarStyle.PLAIN; } + return defaultScalarStyle; + } + + public void setDefaultFlowStyle(FlowStyle defaultFlowStyle) { + this.defaultFlowStyle = defaultFlowStyle; + } - public final boolean isExplicitPropertyUtils() { - return explicitPropertyUtils; + public FlowStyle getDefaultFlowStyle() { + return this.defaultFlowStyle; + } + + public void setPropertyUtils(PropertyUtils propertyUtils) { + this.propertyUtils = propertyUtils; + this.explicitPropertyUtils = true; + } + + public final PropertyUtils getPropertyUtils() { + if (propertyUtils == null) { + propertyUtils = new PropertyUtils(); } + return propertyUtils; + } + + public final boolean isExplicitPropertyUtils() { + return explicitPropertyUtils; + } } diff --git a/src/main/java/org/yaml/snakeyaml/representer/Represent.java b/src/main/java/org/yaml/snakeyaml/representer/Represent.java index 55629ed4..0b0d6ef1 100644 --- a/src/main/java/org/yaml/snakeyaml/representer/Represent.java +++ b/src/main/java/org/yaml/snakeyaml/representer/Represent.java @@ -1,36 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; import org.yaml.snakeyaml.nodes.Node; /** - * Create a Node Graph out of the provided Native Data Structure (Java - * instance). - * - * @see <a href="http://yaml.org/spec/1.1/#id859109">Chapter 3. Processing YAML - * Information</a> + * Create a Node Graph out of the provided Native Data Structure (Java instance). + * + * @see <a href="http://yaml.org/spec/1.1/#id859109">Chapter 3. Processing YAML Information</a> */ public interface Represent { - /** - * Create a Node - * - * @param data - * the instance to represent - * @return Node to dump - */ - Node representData(Object data); + + /** + * Create a Node + * + * @param data the instance to represent + * @return Node to dump + */ + Node representData(Object data); } diff --git a/src/main/java/org/yaml/snakeyaml/representer/Representer.java b/src/main/java/org/yaml/snakeyaml/representer/Representer.java index e83a5ea2..5376b6e2 100644 --- a/src/main/java/org/yaml/snakeyaml/representer/Representer.java +++ b/src/main/java/org/yaml/snakeyaml/representer/Representer.java @@ -1,32 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; -import java.beans.IntrospectionException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; -import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertyUtils; import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeId; @@ -40,209 +40,225 @@ import org.yaml.snakeyaml.nodes.Tag; */ public class Representer extends SafeRepresenter { - public Representer() { - this.representers.put(null, new RepresentJavaBean()); + protected Map<Class<? extends Object>, TypeDescription> typeDefinitions = Collections.emptyMap(); + + public Representer() { + this.representers.put(null, new RepresentJavaBean()); + } + + public Representer(DumperOptions options) { + super(options); + this.representers.put(null, new RepresentJavaBean()); + } + + public TypeDescription addTypeDescription(TypeDescription td) { + if (Collections.EMPTY_MAP == typeDefinitions) { + typeDefinitions = new HashMap<Class<? extends Object>, TypeDescription>(); } + if (td.getTag() != null) { + addClassTag(td.getType(), td.getTag()); + } + td.setPropertyUtils(getPropertyUtils()); + return typeDefinitions.put(td.getType(), td); + } - protected class RepresentJavaBean implements Represent { - public Node representData(Object data) { - try { - return representJavaBean(getProperties(data.getClass()), data); - } catch (IntrospectionException e) { - throw new YAMLException(e); - } - } + @Override + public void setPropertyUtils(PropertyUtils propertyUtils) { + super.setPropertyUtils(propertyUtils); + Collection<TypeDescription> tds = typeDefinitions.values(); + for (TypeDescription typeDescription : tds) { + typeDescription.setPropertyUtils(propertyUtils); } + } - /** - * Tag logic:<br/> - * - explicit root tag is set in serializer <br/> - * - if there is a predefined class tag it is used<br/> - * - a global tag with class name is always used as tag. The JavaBean parent - * of the specified JavaBean may set another tag (tag:yaml.org,2002:map) - * when the property class is the same as runtime class - * - * @param properties - * JavaBean getters - * @param javaBean - * instance for Node - * @return Node to get serialized - */ - protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { - List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size()); - Tag tag; - Tag customTag = classTags.get(javaBean.getClass()); - tag = customTag != null ? customTag : new Tag(javaBean.getClass()); - // flow style will be chosen by BaseRepresenter - MappingNode node = new MappingNode(tag, value, null); - representedObjects.put(javaBean, node); - boolean bestStyle = true; - for (Property property : properties) { - Object memberValue = property.get(javaBean); - Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue - .getClass()); - NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, - customPropertyTag); - if (tuple == null) { - continue; - } - if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) { - bestStyle = false; - } - Node nodeValue = tuple.getValueNode(); - if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) { - bestStyle = false; - } - value.add(tuple); - } - if (defaultFlowStyle != FlowStyle.AUTO) { - node.setFlowStyle(defaultFlowStyle.getStyleBoolean()); - } else { - node.setFlowStyle(bestStyle); - } - return node; + protected class RepresentJavaBean implements Represent { + + public Node representData(Object data) { + return representJavaBean(getProperties(data.getClass()), data); + } + } + + /** + * Tag logic: - explicit root tag is set in serializer - if there is a predefined class tag it is + * used - a global tag with class name is always used as tag. The JavaBean parent of the specified + * JavaBean may set another tag (tag:yaml.org,2002:map) when the property class is the same as + * runtime class + * + * @param properties JavaBean getters + * @param javaBean instance for Node + * @return Node to get serialized + */ + protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { + List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size()); + Tag tag; + Tag customTag = classTags.get(javaBean.getClass()); + tag = customTag != null ? customTag : new Tag(javaBean.getClass()); + // flow style will be chosen by BaseRepresenter + MappingNode node = new MappingNode(tag, value, FlowStyle.AUTO); + representedObjects.put(javaBean, node); + DumperOptions.FlowStyle bestStyle = FlowStyle.FLOW; + for (Property property : properties) { + Object memberValue = property.get(javaBean); + Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass()); + NodeTuple tuple = + representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag); + if (tuple == null) { + continue; + } + if (!((ScalarNode) tuple.getKeyNode()).isPlain()) { + bestStyle = FlowStyle.BLOCK; + } + Node nodeValue = tuple.getValueNode(); + if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).isPlain())) { + bestStyle = FlowStyle.BLOCK; + } + value.add(tuple); } + if (defaultFlowStyle != FlowStyle.AUTO) { + node.setFlowStyle(defaultFlowStyle); + } else { + node.setFlowStyle(bestStyle); + } + return node; + } + + /** + * Represent one JavaBean property. + * + * @param javaBean - the instance to be represented + * @param property - the property of the instance + * @param propertyValue - value to be represented + * @param customTag - user defined Tag + * @return NodeTuple to be used in a MappingNode. Return null to skip the property + */ + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, + Object propertyValue, Tag customTag) { + ScalarNode nodeKey = (ScalarNode) representData(property.getName()); + // the first occurrence of the node must keep the tag + boolean hasAlias = this.representedObjects.containsKey(propertyValue); - /** - * Represent one JavaBean property. - * - * @param javaBean - * - the instance to be represented - * @param property - * - the property of the instance - * @param propertyValue - * - value to be represented - * @param customTag - * - user defined Tag - * @return NodeTuple to be used in a MappingNode. Return null to skip the - * property - */ - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, - Object propertyValue, Tag customTag) { - ScalarNode nodeKey = (ScalarNode) representData(property.getName()); - // the first occurrence of the node must keep the tag - boolean hasAlias = this.representedObjects.containsKey(propertyValue); - - Node nodeValue = representData(propertyValue); - - if (propertyValue != null && !hasAlias) { - NodeId nodeId = nodeValue.getNodeId(); - if (customTag == null) { - if (nodeId == NodeId.scalar) { - if (propertyValue instanceof Enum<?>) { - nodeValue.setTag(Tag.STR); - } - } else { - if (nodeId == NodeId.mapping) { - if (property.getType() == propertyValue.getClass()) { - if (!(propertyValue instanceof Map<?, ?>)) { - if (!nodeValue.getTag().equals(Tag.SET)) { - nodeValue.setTag(Tag.MAP); - } - } - } - } - checkGlobalTag(property, nodeValue, propertyValue); + Node nodeValue = representData(propertyValue); + + if (propertyValue != null && !hasAlias) { + NodeId nodeId = nodeValue.getNodeId(); + if (customTag == null) { + if (nodeId == NodeId.scalar) { + // generic Enum requires the full tag + if (property.getType() != java.lang.Enum.class) { + if (propertyValue instanceof Enum<?>) { + nodeValue.setTag(Tag.STR); + } + } + } else { + if (nodeId == NodeId.mapping) { + if (property.getType() == propertyValue.getClass()) { + if (!(propertyValue instanceof Map<?, ?>)) { + if (!nodeValue.getTag().equals(Tag.SET)) { + nodeValue.setTag(Tag.MAP); } + } } + } + checkGlobalTag(property, nodeValue, propertyValue); } + } + } - return new NodeTuple(nodeKey, nodeValue); + return new NodeTuple(nodeKey, nodeValue); + } + + /** + * Remove redundant global tag for a type safe (generic) collection if it is the same as defined + * by the JavaBean property + * + * @param property - JavaBean property + * @param node - representation of the property + * @param object - instance represented by the node + */ + @SuppressWarnings("unchecked") + protected void checkGlobalTag(Property property, Node node, Object object) { + // Skip primitive arrays. + if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) { + return; } - /** - * Remove redundant global tag for a type safe (generic) collection if it is - * the same as defined by the JavaBean property - * - * @param property - * - JavaBean property - * @param node - * - representation of the property - * @param object - * - instance represented by the node - */ - @SuppressWarnings("unchecked") - protected void checkGlobalTag(Property property, Node node, Object object) { - // Skip primitive arrays. - if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) { - return; + Class<?>[] arguments = property.getActualTypeArguments(); + if (arguments != null) { + if (node.getNodeId() == NodeId.sequence) { + // apply map tag where class is the same + Class<? extends Object> t = arguments[0]; + SequenceNode snode = (SequenceNode) node; + Iterable<Object> memberList = Collections.EMPTY_LIST; + if (object.getClass().isArray()) { + memberList = Arrays.asList((Object[]) object); + } else if (object instanceof Iterable<?>) { + // list + memberList = (Iterable<Object>) object; } - - Class<?>[] arguments = property.getActualTypeArguments(); - if (arguments != null) { - if (node.getNodeId() == NodeId.sequence) { - // apply map tag where class is the same - Class<? extends Object> t = arguments[0]; - SequenceNode snode = (SequenceNode) node; - Iterable<Object> memberList = Collections.EMPTY_LIST; - if (object.getClass().isArray()) { - memberList = Arrays.asList((Object[]) object); - } else if (object instanceof Iterable<?>) { - // list - memberList = (Iterable<Object>) object; + Iterator<Object> iter = memberList.iterator(); + if (iter.hasNext()) { + for (Node childNode : snode.getValue()) { + Object member = iter.next(); + if (member != null) { + if (t.equals(member.getClass())) { + if (childNode.getNodeId() == NodeId.mapping) { + childNode.setTag(Tag.MAP); } - Iterator<Object> iter = memberList.iterator(); - if (iter.hasNext()) { - for (Node childNode : snode.getValue()) { - Object member = iter.next(); - if (member != null) { - if (t.equals(member.getClass())) - if (childNode.getNodeId() == NodeId.mapping) { - childNode.setTag(Tag.MAP); - } - } - } - } - } else if (object instanceof Set) { - Class<?> t = arguments[0]; - MappingNode mnode = (MappingNode) node; - Iterator<NodeTuple> iter = mnode.getValue().iterator(); - Set<?> set = (Set<?>) object; - for (Object member : set) { - NodeTuple tuple = iter.next(); - Node keyNode = tuple.getKeyNode(); - if (t.equals(member.getClass())) { - if (keyNode.getNodeId() == NodeId.mapping) { - keyNode.setTag(Tag.MAP); - } - } - } - } else if (object instanceof Map) { - Class<?> keyType = arguments[0]; - Class<?> valueType = arguments[1]; - MappingNode mnode = (MappingNode) node; - for (NodeTuple tuple : mnode.getValue()) { - resetTag(keyType, tuple.getKeyNode()); - resetTag(valueType, tuple.getValueNode()); - } - } else { - // the type for collection entries cannot be - // detected + } } + } } - } - - private void resetTag(Class<? extends Object> type, Node node) { - Tag tag = node.getTag(); - if (tag.matches(type)) { - if (Enum.class.isAssignableFrom(type)) { - node.setTag(Tag.STR); - } else { - node.setTag(Tag.MAP); + } else if (object instanceof Set) { + Class<?> t = arguments[0]; + MappingNode mnode = (MappingNode) node; + Iterator<NodeTuple> iter = mnode.getValue().iterator(); + Set<?> set = (Set<?>) object; + for (Object member : set) { + NodeTuple tuple = iter.next(); + Node keyNode = tuple.getKeyNode(); + if (t.equals(member.getClass())) { + if (keyNode.getNodeId() == NodeId.mapping) { + keyNode.setTag(Tag.MAP); } + } + } + } else if (object instanceof Map) { // NodeId.mapping ends-up here + Class<?> keyType = arguments[0]; + Class<?> valueType = arguments[1]; + MappingNode mnode = (MappingNode) node; + for (NodeTuple tuple : mnode.getValue()) { + resetTag(keyType, tuple.getKeyNode()); + resetTag(valueType, tuple.getValueNode()); } + } else { + // the type for collection entries cannot be + // detected + } + } + } + + private void resetTag(Class<? extends Object> type, Node node) { + Tag tag = node.getTag(); + if (tag.matches(type)) { + if (Enum.class.isAssignableFrom(type)) { + node.setTag(Tag.STR); + } else { + node.setTag(Tag.MAP); + } } + } - /** - * Get JavaBean properties to be serialised. The order is respected. This - * method may be overridden to provide custom property selection or order. - * - * @param type - * - JavaBean to inspect the properties - * @return properties to serialise - */ - protected Set<Property> getProperties(Class<? extends Object> type) - throws IntrospectionException { - return getPropertyUtils().getProperties(type); + /** + * Get JavaBean properties to be serialised. The order is respected. This method may be overridden + * to provide custom property selection or order. + * + * @param type - JavaBean to inspect the properties + * @return properties to serialise + */ + protected Set<Property> getProperties(Class<? extends Object> type) { + if (typeDefinitions.containsKey(type)) { + return typeDefinitions.get(type).getProperties(); } + return getPropertyUtils().getProperties(type); + } } diff --git a/src/main/java/org/yaml/snakeyaml/representer/SafeRepresenter.java b/src/main/java/org/yaml/snakeyaml/representer/SafeRepresenter.java index 147e3af5..b46e07fe 100644 --- a/src/main/java/org/yaml/snakeyaml/representer/SafeRepresenter.java +++ b/src/main/java/org/yaml/snakeyaml/representer/SafeRepresenter.java @@ -1,22 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; -import java.io.UnsupportedEncodingException; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -30,7 +28,7 @@ import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.regex.Pattern; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import org.yaml.snakeyaml.nodes.Node; @@ -42,385 +40,432 @@ import org.yaml.snakeyaml.reader.StreamReader; */ class SafeRepresenter extends BaseRepresenter { - protected Map<Class<? extends Object>, Tag> classTags; - protected TimeZone timeZone = null; - - public SafeRepresenter() { - this.nullRepresenter = new RepresentNull(); - this.representers.put(String.class, new RepresentString()); - this.representers.put(Boolean.class, new RepresentBoolean()); - this.representers.put(Character.class, new RepresentString()); - this.representers.put(UUID.class, new RepresentUuid()); - this.representers.put(byte[].class, new RepresentByteArray()); - - Represent primitiveArray = new RepresentPrimitiveArray(); - representers.put(short[].class, primitiveArray); - representers.put(int[].class, primitiveArray); - representers.put(long[].class, primitiveArray); - representers.put(float[].class, primitiveArray); - representers.put(double[].class, primitiveArray); - representers.put(char[].class, primitiveArray); - representers.put(boolean[].class, primitiveArray); - - this.multiRepresenters.put(Number.class, new RepresentNumber()); - this.multiRepresenters.put(List.class, new RepresentList()); - this.multiRepresenters.put(Map.class, new RepresentMap()); - this.multiRepresenters.put(Set.class, new RepresentSet()); - this.multiRepresenters.put(Iterator.class, new RepresentIterator()); - this.multiRepresenters.put(new Object[0].getClass(), new RepresentArray()); - this.multiRepresenters.put(Date.class, new RepresentDate()); - this.multiRepresenters.put(Enum.class, new RepresentEnum()); - this.multiRepresenters.put(Calendar.class, new RepresentDate()); - classTags = new HashMap<Class<? extends Object>, Tag>(); + protected Map<Class<? extends Object>, Tag> classTags; + protected TimeZone timeZone = null; + protected DumperOptions.NonPrintableStyle nonPrintableStyle; + + public SafeRepresenter() { + this(new DumperOptions()); + } + + public SafeRepresenter(DumperOptions options) { + this.nullRepresenter = new RepresentNull(); + this.representers.put(String.class, new RepresentString()); + this.representers.put(Boolean.class, new RepresentBoolean()); + this.representers.put(Character.class, new RepresentString()); + this.representers.put(UUID.class, new RepresentUuid()); + this.representers.put(byte[].class, new RepresentByteArray()); + + Represent primitiveArray = new RepresentPrimitiveArray(); + representers.put(short[].class, primitiveArray); + representers.put(int[].class, primitiveArray); + representers.put(long[].class, primitiveArray); + representers.put(float[].class, primitiveArray); + representers.put(double[].class, primitiveArray); + representers.put(char[].class, primitiveArray); + representers.put(boolean[].class, primitiveArray); + + this.multiRepresenters.put(Number.class, new RepresentNumber()); + this.multiRepresenters.put(List.class, new RepresentList()); + this.multiRepresenters.put(Map.class, new RepresentMap()); + this.multiRepresenters.put(Set.class, new RepresentSet()); + this.multiRepresenters.put(Iterator.class, new RepresentIterator()); + this.multiRepresenters.put(new Object[0].getClass(), new RepresentArray()); + this.multiRepresenters.put(Date.class, new RepresentDate()); + this.multiRepresenters.put(Enum.class, new RepresentEnum()); + this.multiRepresenters.put(Calendar.class, new RepresentDate()); + classTags = new HashMap<Class<? extends Object>, Tag>(); + this.nonPrintableStyle = options.getNonPrintableStyle(); + } + + protected Tag getTag(Class<?> clazz, Tag defaultTag) { + if (classTags.containsKey(clazz)) { + return classTags.get(clazz); + } else { + return defaultTag; + } + } + + /** + * Define a tag for the <code>Class</code> to serialize. + * + * @param clazz <code>Class</code> which tag is changed + * @param tag new tag to be used for every instance of the specified <code>Class</code> + * @return the previous tag associated with the <code>Class</code> + */ + public Tag addClassTag(Class<? extends Object> clazz, Tag tag) { + if (tag == null) { + throw new NullPointerException("Tag must be provided."); } + return classTags.put(clazz, tag); + } - protected Tag getTag(Class<?> clazz, Tag defaultTag) { - if (classTags.containsKey(clazz)) { - return classTags.get(clazz); - } else { - return defaultTag; + protected class RepresentNull implements Represent { + + public Node representData(Object data) { + return representScalar(Tag.NULL, "null"); + } + } + + private static final Pattern MULTILINE_PATTERN = Pattern.compile("\n|\u0085|\u2028|\u2029"); + + protected class RepresentString implements Represent { + + public Node representData(Object data) { + Tag tag = Tag.STR; + DumperOptions.ScalarStyle style = null;// not defined + String value = data.toString(); + if (nonPrintableStyle == DumperOptions.NonPrintableStyle.BINARY + && !StreamReader.isPrintable(value)) { + tag = Tag.BINARY; + char[] binary; + final byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + // sometimes above will just silently fail - it will return incomplete data + // it happens when String has invalid code points + // (for example half surrogate character without other half) + final String checkValue = new String(bytes, StandardCharsets.UTF_8); + if (!checkValue.equals(value)) { + throw new YAMLException("invalid string value has occurred"); } + binary = Base64Coder.encode(bytes); + value = String.valueOf(binary); + style = DumperOptions.ScalarStyle.LITERAL; + } + // if no other scalar style is explicitly set, use literal style for + // multiline scalars + if (defaultScalarStyle == DumperOptions.ScalarStyle.PLAIN + && MULTILINE_PATTERN.matcher(value).find()) { + style = DumperOptions.ScalarStyle.LITERAL; + } + return representScalar(tag, value, style); } - - /** - * Define a tag for the <code>Class</code> to serialize. - * - * @param clazz - * <code>Class</code> which tag is changed - * @param tag - * new tag to be used for every instance of the specified - * <code>Class</code> - * @return the previous tag associated with the <code>Class</code> - */ - public Tag addClassTag(Class<? extends Object> clazz, Tag tag) { - if (tag == null) { - throw new NullPointerException("Tag must be provided."); + } + + protected class RepresentBoolean implements Represent { + + public Node representData(Object data) { + String value; + if (Boolean.TRUE.equals(data)) { + value = "true"; + } else { + value = "false"; + } + return representScalar(Tag.BOOL, value); + } + } + + protected class RepresentNumber implements Represent { + + public Node representData(Object data) { + Tag tag; + String value; + if (data instanceof Byte || data instanceof Short || data instanceof Integer + || data instanceof Long || data instanceof BigInteger) { + tag = Tag.INT; + value = data.toString(); + } else { + Number number = (Number) data; + tag = Tag.FLOAT; + if (number.equals(Double.NaN)) { + value = ".NaN"; + } else if (number.equals(Double.POSITIVE_INFINITY)) { + value = ".inf"; + } else if (number.equals(Double.NEGATIVE_INFINITY)) { + value = "-.inf"; + } else { + value = number.toString(); } - return classTags.put(clazz, tag); + } + return representScalar(getTag(data.getClass(), tag), value); } + } - protected class RepresentNull implements Represent { - public Node representData(Object data) { - return representScalar(Tag.NULL, "null"); - } + protected class RepresentList implements Represent { + + @SuppressWarnings("unchecked") + public Node representData(Object data) { + return representSequence(getTag(data.getClass(), Tag.SEQ), (List<Object>) data, + DumperOptions.FlowStyle.AUTO); } + } - public static Pattern MULTILINE_PATTERN = Pattern.compile("\n|\u0085|\u2028|\u2029"); - - protected class RepresentString implements Represent { - public Node representData(Object data) { - Tag tag = Tag.STR; - Character style = null; - String value = data.toString(); - if (StreamReader.NON_PRINTABLE.matcher(value).find()) { - tag = Tag.BINARY; - char[] binary; - try { - binary = Base64Coder.encode(value.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new YAMLException(e); - } - value = String.valueOf(binary); - style = '|'; - } - // if no other scalar style is explicitly set, use literal style for - // multiline scalars - if (defaultScalarStyle == null && MULTILINE_PATTERN.matcher(value).find()) { - style = '|'; - } - return representScalar(tag, value, style); - } + protected class RepresentIterator implements Represent { + + @SuppressWarnings("unchecked") + public Node representData(Object data) { + Iterator<Object> iter = (Iterator<Object>) data; + return representSequence(getTag(data.getClass(), Tag.SEQ), new IteratorWrapper(iter), + DumperOptions.FlowStyle.AUTO); } + } - protected class RepresentBoolean implements Represent { - public Node representData(Object data) { - String value; - if (Boolean.TRUE.equals(data)) { - value = "true"; - } else { - value = "false"; - } - return representScalar(Tag.BOOL, value); - } + private static class IteratorWrapper implements Iterable<Object> { + + private final Iterator<Object> iter; + + public IteratorWrapper(Iterator<Object> iter) { + this.iter = iter; } - protected class RepresentNumber implements Represent { - public Node representData(Object data) { - Tag tag; - String value; - if (data instanceof Byte || data instanceof Short || data instanceof Integer - || data instanceof Long || data instanceof BigInteger) { - tag = Tag.INT; - value = data.toString(); - } else { - Number number = (Number) data; - tag = Tag.FLOAT; - if (number.equals(Double.NaN)) { - value = ".NaN"; - } else if (number.equals(Double.POSITIVE_INFINITY)) { - value = ".inf"; - } else if (number.equals(Double.NEGATIVE_INFINITY)) { - value = "-.inf"; - } else { - value = number.toString(); - } - } - return representScalar(getTag(data.getClass(), tag), value); - } + public Iterator<Object> iterator() { + return iter; } + } - protected class RepresentList implements Represent { - @SuppressWarnings("unchecked") - public Node representData(Object data) { - return representSequence(getTag(data.getClass(), Tag.SEQ), (List<Object>) data, null); - } + protected class RepresentArray implements Represent { + + public Node representData(Object data) { + Object[] array = (Object[]) data; + List<Object> list = Arrays.asList(array); + return representSequence(Tag.SEQ, list, DumperOptions.FlowStyle.AUTO); + } + } + + /** + * Represents primitive arrays, such as short[] and float[], by converting them into equivalent + * List<Short> and List<Float> using the appropriate autoboxing type. + */ + protected class RepresentPrimitiveArray implements Represent { + + public Node representData(Object data) { + Class<?> type = data.getClass().getComponentType(); + + if (byte.class == type) { + return representSequence(Tag.SEQ, asByteList(data), DumperOptions.FlowStyle.AUTO); + } else if (short.class == type) { + return representSequence(Tag.SEQ, asShortList(data), DumperOptions.FlowStyle.AUTO); + } else if (int.class == type) { + return representSequence(Tag.SEQ, asIntList(data), DumperOptions.FlowStyle.AUTO); + } else if (long.class == type) { + return representSequence(Tag.SEQ, asLongList(data), DumperOptions.FlowStyle.AUTO); + } else if (float.class == type) { + return representSequence(Tag.SEQ, asFloatList(data), DumperOptions.FlowStyle.AUTO); + } else if (double.class == type) { + return representSequence(Tag.SEQ, asDoubleList(data), DumperOptions.FlowStyle.AUTO); + } else if (char.class == type) { + return representSequence(Tag.SEQ, asCharList(data), DumperOptions.FlowStyle.AUTO); + } else if (boolean.class == type) { + return representSequence(Tag.SEQ, asBooleanList(data), DumperOptions.FlowStyle.AUTO); + } + + throw new YAMLException("Unexpected primitive '" + type.getCanonicalName() + "'"); } - protected class RepresentIterator implements Represent { - @SuppressWarnings("unchecked") - public Node representData(Object data) { - Iterator<Object> iter = (Iterator<Object>) data; - return representSequence(getTag(data.getClass(), Tag.SEQ), new IteratorWrapper(iter), - null); - } + private List<Byte> asByteList(Object in) { + byte[] array = (byte[]) in; + List<Byte> list = new ArrayList<Byte>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; } - private static class IteratorWrapper implements Iterable<Object> { - private Iterator<Object> iter; + private List<Short> asShortList(Object in) { + short[] array = (short[]) in; + List<Short> list = new ArrayList<Short>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; + } - public IteratorWrapper(Iterator<Object> iter) { - this.iter = iter; - } + private List<Integer> asIntList(Object in) { + int[] array = (int[]) in; + List<Integer> list = new ArrayList<Integer>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; + } - public Iterator<Object> iterator() { - return iter; - } + private List<Long> asLongList(Object in) { + long[] array = (long[]) in; + List<Long> list = new ArrayList<Long>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; } - protected class RepresentArray implements Represent { - public Node representData(Object data) { - Object[] array = (Object[]) data; - List<Object> list = Arrays.asList(array); - return representSequence(Tag.SEQ, list, null); - } + private List<Float> asFloatList(Object in) { + float[] array = (float[]) in; + List<Float> list = new ArrayList<Float>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; } - /** - * Represents primitive arrays, such as short[] and float[], by converting - * them into equivalent List<Short> and List<Float> using the appropriate - * autoboxing type. - */ - protected class RepresentPrimitiveArray implements Represent { - public Node representData(Object data) { - Class<?> type = data.getClass().getComponentType(); - - if (byte.class == type) { - return representSequence(Tag.SEQ, asByteList(data), null); - } else if (short.class == type) { - return representSequence(Tag.SEQ, asShortList(data), null); - } else if (int.class == type) { - return representSequence(Tag.SEQ, asIntList(data), null); - } else if (long.class == type) { - return representSequence(Tag.SEQ, asLongList(data), null); - } else if (float.class == type) { - return representSequence(Tag.SEQ, asFloatList(data), null); - } else if (double.class == type) { - return representSequence(Tag.SEQ, asDoubleList(data), null); - } else if (char.class == type) { - return representSequence(Tag.SEQ, asCharList(data), null); - } else if (boolean.class == type) { - return representSequence(Tag.SEQ, asBooleanList(data), null); - } - - throw new YAMLException("Unexpected primitive '" + type.getCanonicalName() + "'"); - } + private List<Double> asDoubleList(Object in) { + double[] array = (double[]) in; + List<Double> list = new ArrayList<Double>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; + } - private List<Byte> asByteList(Object in) { - byte[] array = (byte[]) in; - List<Byte> list = new ArrayList<Byte>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; - } + private List<Character> asCharList(Object in) { + char[] array = (char[]) in; + List<Character> list = new ArrayList<Character>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; + } - private List<Short> asShortList(Object in) { - short[] array = (short[]) in; - List<Short> list = new ArrayList<Short>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; - } + private List<Boolean> asBooleanList(Object in) { + boolean[] array = (boolean[]) in; + List<Boolean> list = new ArrayList<Boolean>(array.length); + for (int i = 0; i < array.length; ++i) { + list.add(array[i]); + } + return list; + } + } - private List<Integer> asIntList(Object in) { - int[] array = (int[]) in; - List<Integer> list = new ArrayList<Integer>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; - } + protected class RepresentMap implements Represent { - private List<Long> asLongList(Object in) { - long[] array = (long[]) in; - List<Long> list = new ArrayList<Long>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; + @SuppressWarnings("unchecked") + public Node representData(Object data) { + return representMapping(getTag(data.getClass(), Tag.MAP), (Map<Object, Object>) data, + DumperOptions.FlowStyle.AUTO); + } + } + + protected class RepresentSet implements Represent { + + @SuppressWarnings("unchecked") + public Node representData(Object data) { + Map<Object, Object> value = new LinkedHashMap<Object, Object>(); + Set<Object> set = (Set<Object>) data; + for (Object key : set) { + value.put(key, null); + } + return representMapping(getTag(data.getClass(), Tag.SET), value, + DumperOptions.FlowStyle.AUTO); + } + } + + protected class RepresentDate implements Represent { + + public Node representData(Object data) { + // because SimpleDateFormat ignores timezone we have to use Calendar + Calendar calendar; + if (data instanceof Calendar) { + calendar = (Calendar) data; + } else { + calendar = + Calendar.getInstance(getTimeZone() == null ? TimeZone.getTimeZone("UTC") : timeZone); + calendar.setTime((Date) data); + } + int years = calendar.get(Calendar.YEAR); + int months = calendar.get(Calendar.MONTH) + 1; // 0..12 + int days = calendar.get(Calendar.DAY_OF_MONTH); // 1..31 + int hour24 = calendar.get(Calendar.HOUR_OF_DAY); // 0..24 + int minutes = calendar.get(Calendar.MINUTE); // 0..59 + int seconds = calendar.get(Calendar.SECOND); // 0..59 + int millis = calendar.get(Calendar.MILLISECOND); + StringBuilder buffer = new StringBuilder(String.valueOf(years)); + while (buffer.length() < 4) { + // ancient years + buffer.insert(0, "0"); + } + buffer.append("-"); + if (months < 10) { + buffer.append("0"); + } + buffer.append(months); + buffer.append("-"); + if (days < 10) { + buffer.append("0"); + } + buffer.append(days); + buffer.append("T"); + if (hour24 < 10) { + buffer.append("0"); + } + buffer.append(hour24); + buffer.append(":"); + if (minutes < 10) { + buffer.append("0"); + } + buffer.append(minutes); + buffer.append(":"); + if (seconds < 10) { + buffer.append("0"); + } + buffer.append(seconds); + if (millis > 0) { + if (millis < 10) { + buffer.append(".00"); + } else if (millis < 100) { + buffer.append(".0"); + } else { + buffer.append("."); } - - private List<Float> asFloatList(Object in) { - float[] array = (float[]) in; - List<Float> list = new ArrayList<Float>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; + buffer.append(millis); + } + + // Get the offset from GMT taking DST into account + int gmtOffset = calendar.getTimeZone().getOffset(calendar.getTime().getTime()); + if (gmtOffset == 0) { + buffer.append('Z'); + } else { + if (gmtOffset < 0) { + buffer.append('-'); + gmtOffset *= -1; + } else { + buffer.append('+'); } + int minutesOffset = gmtOffset / (60 * 1000); + int hoursOffset = minutesOffset / 60; + int partOfHour = minutesOffset % 60; - private List<Double> asDoubleList(Object in) { - double[] array = (double[]) in; - List<Double> list = new ArrayList<Double>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; + if (hoursOffset < 10) { + buffer.append('0'); } - - private List<Character> asCharList(Object in) { - char[] array = (char[]) in; - List<Character> list = new ArrayList<Character>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; + buffer.append(hoursOffset); + buffer.append(':'); + if (partOfHour < 10) { + buffer.append('0'); } + buffer.append(partOfHour); + } - private List<Boolean> asBooleanList(Object in) { - boolean[] array = (boolean[]) in; - List<Boolean> list = new ArrayList<Boolean>(array.length); - for (int i = 0; i < array.length; ++i) - list.add(array[i]); - return list; - } + return representScalar(getTag(data.getClass(), Tag.TIMESTAMP), buffer.toString(), + DumperOptions.ScalarStyle.PLAIN); } + } - protected class RepresentMap implements Represent { - @SuppressWarnings("unchecked") - public Node representData(Object data) { - return representMapping(getTag(data.getClass(), Tag.MAP), (Map<Object, Object>) data, - null); - } - } + protected class RepresentEnum implements Represent { - protected class RepresentSet implements Represent { - @SuppressWarnings("unchecked") - public Node representData(Object data) { - Map<Object, Object> value = new LinkedHashMap<Object, Object>(); - Set<Object> set = (Set<Object>) data; - for (Object key : set) { - value.put(key, null); - } - return representMapping(getTag(data.getClass(), Tag.SET), value, null); - } + public Node representData(Object data) { + Tag tag = new Tag(data.getClass()); + return representScalar(getTag(data.getClass(), tag), ((Enum<?>) data).name()); } + } - protected class RepresentDate implements Represent { - public Node representData(Object data) { - // because SimpleDateFormat ignores timezone we have to use Calendar - Calendar calendar; - if (data instanceof Calendar) { - calendar = (Calendar) data; - } else { - calendar = Calendar.getInstance(getTimeZone() == null ? TimeZone.getTimeZone("UTC") - : timeZone); - calendar.setTime((Date) data); - } - int years = calendar.get(Calendar.YEAR); - int months = calendar.get(Calendar.MONTH) + 1; // 0..12 - int days = calendar.get(Calendar.DAY_OF_MONTH); // 1..31 - int hour24 = calendar.get(Calendar.HOUR_OF_DAY); // 0..24 - int minutes = calendar.get(Calendar.MINUTE); // 0..59 - int seconds = calendar.get(Calendar.SECOND); // 0..59 - int millis = calendar.get(Calendar.MILLISECOND); - StringBuilder buffer = new StringBuilder(String.valueOf(years)); - while (buffer.length() < 4) { - // ancient years - buffer.insert(0, "0"); - } - buffer.append("-"); - if (months < 10) { - buffer.append("0"); - } - buffer.append(String.valueOf(months)); - buffer.append("-"); - if (days < 10) { - buffer.append("0"); - } - buffer.append(String.valueOf(days)); - buffer.append("T"); - if (hour24 < 10) { - buffer.append("0"); - } - buffer.append(String.valueOf(hour24)); - buffer.append(":"); - if (minutes < 10) { - buffer.append("0"); - } - buffer.append(String.valueOf(minutes)); - buffer.append(":"); - if (seconds < 10) { - buffer.append("0"); - } - buffer.append(String.valueOf(seconds)); - if (millis > 0) { - if (millis < 10) { - buffer.append(".00"); - } else if (millis < 100) { - buffer.append(".0"); - } else { - buffer.append("."); - } - buffer.append(String.valueOf(millis)); - } - if (TimeZone.getTimeZone("UTC").equals(calendar.getTimeZone())) { - buffer.append("Z"); - } else { - // Get the Offset from GMT taking DST into account - int gmtOffset = calendar.getTimeZone().getOffset(calendar.get(Calendar.ERA), - calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), - calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.DAY_OF_WEEK), - calendar.get(Calendar.MILLISECOND)); - int minutesOffset = gmtOffset / (60 * 1000); - int hoursOffset = minutesOffset / 60; - int partOfHour = minutesOffset % 60; - buffer.append((hoursOffset > 0 ? "+" : "") + hoursOffset + ":" - + (partOfHour < 10 ? "0" + partOfHour : partOfHour)); - } - return representScalar(getTag(data.getClass(), Tag.TIMESTAMP), buffer.toString(), null); - } - } + protected class RepresentByteArray implements Represent { - protected class RepresentEnum implements Represent { - public Node representData(Object data) { - Tag tag = new Tag(data.getClass()); - return representScalar(getTag(data.getClass(), tag), ((Enum<?>) data).name()); - } + public Node representData(Object data) { + char[] binary = Base64Coder.encode((byte[]) data); + return representScalar(Tag.BINARY, String.valueOf(binary), DumperOptions.ScalarStyle.LITERAL); } + } - protected class RepresentByteArray implements Represent { - public Node representData(Object data) { - char[] binary = Base64Coder.encode((byte[]) data); - return representScalar(Tag.BINARY, String.valueOf(binary), '|'); - } - } + public TimeZone getTimeZone() { + return timeZone; + } - public TimeZone getTimeZone() { - return timeZone; - } + public void setTimeZone(TimeZone timeZone) { + this.timeZone = timeZone; + } - public void setTimeZone(TimeZone timeZone) { - this.timeZone = timeZone; - } + protected class RepresentUuid implements Represent { - protected class RepresentUuid implements Represent { - public Node representData(Object data) { - return representScalar(getTag(data.getClass(), new Tag(UUID.class)), data.toString()); - } + public Node representData(Object data) { + return representScalar(getTag(data.getClass(), new Tag(UUID.class)), data.toString()); } + } } diff --git a/src/main/java/org/yaml/snakeyaml/resolver/Resolver.java b/src/main/java/org/yaml/snakeyaml/resolver/Resolver.java index f8ec36fa..38960561 100644 --- a/src/main/java/org/yaml/snakeyaml/resolver/Resolver.java +++ b/src/main/java/org/yaml/snakeyaml/resolver/Resolver.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.resolver; @@ -20,7 +18,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; - import org.yaml.snakeyaml.nodes.NodeId; import org.yaml.snakeyaml.nodes.Tag; @@ -28,111 +25,123 @@ import org.yaml.snakeyaml.nodes.Tag; * Resolver tries to detect a type by content (when the tag is implicit) */ public class Resolver { - public static final Pattern BOOL = Pattern - .compile("^(?:yes|Yes|YES|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$"); - /** - * The regular expression is taken from the 1.2 specification but '_'s are - * added to keep backwards compatibility - */ - public static final Pattern FLOAT = Pattern - .compile("^([-+]?(\\.[0-9]+|[0-9_]+(\\.[0-9_]*)?)([eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); - public static final Pattern INT = Pattern - .compile("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?(?:0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$"); - public static final Pattern MERGE = Pattern.compile("^(?:<<)$"); - public static final Pattern NULL = Pattern.compile("^(?:~|null|Null|NULL| )$"); - public static final Pattern EMPTY = Pattern.compile("^$"); - public static final Pattern TIMESTAMP = Pattern - .compile("^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?(?:[Tt]|[ \t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](?:\\.[0-9]*)?(?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$"); - public static final Pattern VALUE = Pattern.compile("^(?:=)$"); - public static final Pattern YAML = Pattern.compile("^(?:!|&|\\*)$"); + public static final Pattern BOOL = Pattern + .compile("^(?:yes|Yes|YES|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$"); - protected Map<Character, List<ResolverTuple>> yamlImplicitResolvers = new HashMap<Character, List<ResolverTuple>>(); + /** + * The regular expression is taken from the 1.2 specification but '_'s are added to keep backwards + * compatibility + */ + public static final Pattern FLOAT = + Pattern.compile("^(" + "[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?" + // (base 10) + "|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)" + // (base 10, scientific notation without .) + "|[-+]?\\.[0-9_]+(?:[eE][-+]?[0-9]+)?" + // (base 10, starting with .) + "|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*" + // (base 60) + "|[-+]?\\.(?:inf|Inf|INF)" + "|\\.(?:nan|NaN|NAN)" + ")$"); + public static final Pattern INT = Pattern.compile("^(?:" + "[-+]?0b_*[0-1][0-1_]*" + // (base 2) + "|[-+]?0_*[0-7][0-7_]*" + // (base 8) + "|[-+]?(?:0|[1-9][0-9_]*)" + // (base 10) + "|[-+]?0x_*[0-9a-fA-F][0-9a-fA-F_]*" + // (base 16) + "|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+" + // (base 60) + ")$"); + public static final Pattern MERGE = Pattern.compile("^(?:<<)$"); + public static final Pattern NULL = Pattern.compile("^(?:~|null|Null|NULL| )$"); + public static final Pattern EMPTY = Pattern.compile("^$"); + public static final Pattern TIMESTAMP = Pattern.compile( + "^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?(?:[Tt]|[ \t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](?:\\.[0-9]*)?(?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$"); + public static final Pattern VALUE = Pattern.compile("^(?:=)$"); + public static final Pattern YAML = Pattern.compile("^(?:!|&|\\*)$"); - protected void addImplicitResolvers() { - addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO"); - /* - * INT must be before FLOAT because the regular expression for FLOAT - * matches INT (see issue 130) - * http://code.google.com/p/snakeyaml/issues/detail?id=130 - */ - addImplicitResolver(Tag.INT, INT, "-+0123456789"); - addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); - addImplicitResolver(Tag.MERGE, MERGE, "<"); - addImplicitResolver(Tag.NULL, NULL, "~nN\0"); - addImplicitResolver(Tag.NULL, EMPTY, null); - addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789"); - // The following implicit resolver is only for documentation - // purposes. - // It cannot work - // because plain scalars cannot start with '!', '&', or '*'. - addImplicitResolver(Tag.YAML, YAML, "!&*"); - } + protected Map<Character, List<ResolverTuple>> yamlImplicitResolvers = + new HashMap<Character, List<ResolverTuple>>(); - public Resolver() { - addImplicitResolvers(); - } + protected void addImplicitResolvers() { + addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO", 10); + /* + * INT must be before FLOAT because the regular expression for FLOAT matches INT (see issue 130) + * http://code.google.com/p/snakeyaml/issues/detail?id=130 + */ + addImplicitResolver(Tag.INT, INT, "-+0123456789"); + addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); + addImplicitResolver(Tag.MERGE, MERGE, "<", 10); + addImplicitResolver(Tag.NULL, NULL, "~nN\0", 10); + addImplicitResolver(Tag.NULL, EMPTY, null, 10); + addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789", 50); + // The following implicit resolver is only for documentation purposes. + // It cannot work because plain scalars cannot start with '!', '&', or '*'. + addImplicitResolver(Tag.YAML, YAML, "!&*", 10); + } - public void addImplicitResolver(Tag tag, Pattern regexp, String first) { - if (first == null) { - List<ResolverTuple> curr = yamlImplicitResolvers.get(null); - if (curr == null) { - curr = new ArrayList<ResolverTuple>(); - yamlImplicitResolvers.put(null, curr); - } - curr.add(new ResolverTuple(tag, regexp)); - } else { - char[] chrs = first.toCharArray(); - for (int i = 0, j = chrs.length; i < j; i++) { - Character theC = Character.valueOf(chrs[i]); - if (theC == 0) { - // special case: for null - theC = null; - } - List<ResolverTuple> curr = yamlImplicitResolvers.get(theC); - if (curr == null) { - curr = new ArrayList<ResolverTuple>(); - yamlImplicitResolvers.put(theC, curr); - } - curr.add(new ResolverTuple(tag, regexp)); - } + public Resolver() { + addImplicitResolvers(); + } + + public void addImplicitResolver(Tag tag, Pattern regexp, String first) { + addImplicitResolver(tag, regexp, first, 1024); + } + + public void addImplicitResolver(Tag tag, Pattern regexp, String first, int limit) { + if (first == null) { + List<ResolverTuple> curr = yamlImplicitResolvers.get(null); + if (curr == null) { + curr = new ArrayList<ResolverTuple>(); + yamlImplicitResolvers.put(null, curr); + } + curr.add(new ResolverTuple(tag, regexp, limit)); + } else { + char[] chrs = first.toCharArray(); + for (int i = 0, j = chrs.length; i < j; i++) { + Character theC = Character.valueOf(chrs[i]); + if (theC == 0) { + // special case: for null + theC = null; } + List<ResolverTuple> curr = yamlImplicitResolvers.get(theC); + if (curr == null) { + curr = new ArrayList<ResolverTuple>(); + yamlImplicitResolvers.put(theC, curr); + } + curr.add(new ResolverTuple(tag, regexp, limit)); + } } + } - public Tag resolve(NodeId kind, String value, boolean implicit) { - if (kind == NodeId.scalar && implicit) { - List<ResolverTuple> resolvers = null; - if (value.length() == 0) { - resolvers = yamlImplicitResolvers.get('\0'); - } else { - resolvers = yamlImplicitResolvers.get(value.charAt(0)); - } - if (resolvers != null) { - for (ResolverTuple v : resolvers) { - Tag tag = v.getTag(); - Pattern regexp = v.getRegexp(); - if (regexp.matcher(value).matches()) { - return tag; - } - } - } - if (yamlImplicitResolvers.containsKey(null)) { - for (ResolverTuple v : yamlImplicitResolvers.get(null)) { - Tag tag = v.getTag(); - Pattern regexp = v.getRegexp(); - if (regexp.matcher(value).matches()) { - return tag; - } - } - } + public Tag resolve(NodeId kind, String value, boolean implicit) { + if (kind == NodeId.scalar && implicit) { + final List<ResolverTuple> resolvers; + if (value.length() == 0) { + resolvers = yamlImplicitResolvers.get('\0'); + } else { + resolvers = yamlImplicitResolvers.get(value.charAt(0)); + } + if (resolvers != null) { + for (ResolverTuple v : resolvers) { + Tag tag = v.getTag(); + Pattern regexp = v.getRegexp(); + if (value.length() <= v.getLimit() && regexp.matcher(value).matches()) { + return tag; + } } - switch (kind) { - case scalar: - return Tag.STR; - case sequence: - return Tag.SEQ; - default: - return Tag.MAP; + } + if (yamlImplicitResolvers.containsKey(null)) { + // check null resolver + for (ResolverTuple v : yamlImplicitResolvers.get(null)) { + Tag tag = v.getTag(); + Pattern regexp = v.getRegexp(); + if (value.length() <= v.getLimit() && regexp.matcher(value).matches()) { + return tag; + } } + } + } + switch (kind) { + case scalar: + return Tag.STR; + case sequence: + return Tag.SEQ; + default: + return Tag.MAP; } -}
\ No newline at end of file + } +} diff --git a/src/main/java/org/yaml/snakeyaml/resolver/ResolverTuple.java b/src/main/java/org/yaml/snakeyaml/resolver/ResolverTuple.java index 3fbfac04..0f8df776 100644 --- a/src/main/java/org/yaml/snakeyaml/resolver/ResolverTuple.java +++ b/src/main/java/org/yaml/snakeyaml/resolver/ResolverTuple.java @@ -1,43 +1,47 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.resolver; import java.util.regex.Pattern; - import org.yaml.snakeyaml.nodes.Tag; final class ResolverTuple { - private final Tag tag; - private final Pattern regexp; - - public ResolverTuple(Tag tag, Pattern regexp) { - this.tag = tag; - this.regexp = regexp; - } - - public Tag getTag() { - return tag; - } - - public Pattern getRegexp() { - return regexp; - } - - @Override - public String toString() { - return "Tuple tag=" + tag + " regexp=" + regexp; - } -}
\ No newline at end of file + + private final Tag tag; + private final Pattern regexp; + private final int limit; + + public ResolverTuple(Tag tag, Pattern regexp, int limit) { + this.tag = tag; + this.regexp = regexp; + this.limit = limit; + } + + public Tag getTag() { + return tag; + } + + public Pattern getRegexp() { + return regexp; + } + + public int getLimit() { + return limit; + } + + @Override + public String toString() { + return "Tuple tag=" + tag + " regexp=" + regexp + " limit=" + limit; + } +} diff --git a/src/main/java/org/yaml/snakeyaml/scanner/Constant.java b/src/main/java/org/yaml/snakeyaml/scanner/Constant.java index 391bcaa7..83720afe 100644 --- a/src/main/java/org/yaml/snakeyaml/scanner/Constant.java +++ b/src/main/java/org/yaml/snakeyaml/scanner/Constant.java @@ -1,76 +1,76 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; import java.util.Arrays; public final class Constant { - private final static String ALPHA_S = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"; - private final static String LINEBR_S = "\n\u0085\u2028\u2029"; - private final static String FULL_LINEBR_S = "\r" + LINEBR_S; - private final static String NULL_OR_LINEBR_S = "\0" + FULL_LINEBR_S; - private final static String NULL_BL_LINEBR_S = " " + NULL_OR_LINEBR_S; - private final static String NULL_BL_T_LINEBR_S = "\t" + NULL_BL_LINEBR_S; - private final static String NULL_BL_T_S = "\0 \t"; - private final static String URI_CHARS_S = ALPHA_S + "-;/?:@&=+$,_.!~*\'()[]%"; + private static final String ALPHA_S = + "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"; - public final static Constant LINEBR = new Constant(LINEBR_S); - public final static Constant FULL_LINEBR = new Constant(FULL_LINEBR_S); - public final static Constant NULL_OR_LINEBR = new Constant(NULL_OR_LINEBR_S); - public final static Constant NULL_BL_LINEBR = new Constant(NULL_BL_LINEBR_S); - public final static Constant NULL_BL_T_LINEBR = new Constant(NULL_BL_T_LINEBR_S); - public final static Constant NULL_BL_T = new Constant(NULL_BL_T_S); - public final static Constant URI_CHARS = new Constant(URI_CHARS_S); + private static final String LINEBR_S = "\n\u0085\u2028\u2029"; + private static final String FULL_LINEBR_S = "\r" + LINEBR_S; + private static final String NULL_OR_LINEBR_S = "\0" + FULL_LINEBR_S; + private static final String NULL_BL_LINEBR_S = " " + NULL_OR_LINEBR_S; + private static final String NULL_BL_T_LINEBR_S = "\t" + NULL_BL_LINEBR_S; + private static final String NULL_BL_T_S = "\0 \t"; + private static final String URI_CHARS_S = ALPHA_S + "-;/?:@&=+$,_.!~*'()[]%"; - public final static Constant ALPHA = new Constant(ALPHA_S); + public static final Constant LINEBR = new Constant(LINEBR_S); + public static final Constant NULL_OR_LINEBR = new Constant(NULL_OR_LINEBR_S); + public static final Constant NULL_BL_LINEBR = new Constant(NULL_BL_LINEBR_S); + public static final Constant NULL_BL_T_LINEBR = new Constant(NULL_BL_T_LINEBR_S); + public static final Constant NULL_BL_T = new Constant(NULL_BL_T_S); + public static final Constant URI_CHARS = new Constant(URI_CHARS_S); - private String content; - boolean[] contains = new boolean[128]; - boolean noASCII = false; + public static final Constant ALPHA = new Constant(ALPHA_S); - private Constant(String content) { - Arrays.fill(contains, false); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < content.length(); i++) { - char ch = content.charAt(i); - if (ch < 128) - contains[ch] = true; - else - sb.append(ch); - } - if (sb.length() > 0) { - noASCII = true; - this.content = sb.toString(); - } - } + private String content; + boolean[] contains = new boolean[128]; + boolean noASCII = false; - public boolean has(char ch) { - return (ch < 128) ? contains[ch] : noASCII && content.indexOf(ch, 0) != -1; + private Constant(String content) { + Arrays.fill(contains, false); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < content.length(); i++) { + int c = content.codePointAt(i); + if (c < 128) { + contains[c] = true; + } else { + sb.appendCodePoint(c); + } } - - public boolean hasNo(char ch) { - return !has(ch); + if (sb.length() > 0) { + noASCII = true; + this.content = sb.toString(); } + } - public boolean has(char ch, String additional) { - return has(ch) || additional.indexOf(ch, 0) != -1; - } + public boolean has(int c) { + return (c < 128) ? contains[c] : noASCII && content.indexOf(c) != -1; + } - public boolean hasNo(char ch, String additional) { - return !has(ch, additional); - } + public boolean hasNo(int c) { + return !has(c); + } + + public boolean has(int c, String additional) { + return has(c) || additional.indexOf(c) != -1; + } + + public boolean hasNo(int c, String additional) { + return !has(c, additional); + } } diff --git a/src/main/java/org/yaml/snakeyaml/scanner/Scanner.java b/src/main/java/org/yaml/snakeyaml/scanner/Scanner.java index 6fc0d97c..ef9b8d65 100644 --- a/src/main/java/org/yaml/snakeyaml/scanner/Scanner.java +++ b/src/main/java/org/yaml/snakeyaml/scanner/Scanner.java @@ -1,65 +1,60 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; import org.yaml.snakeyaml.tokens.Token; /** - * This interface represents an input stream of {@link Token Tokens}. + * This interface represents an input stream of {@link Token}s. * <p> - * The parser and the scanner form together the 'Parse' step in the loading - * process (see chapter 3.1 of the <a href="http://yaml.org/spec/1.1/">YAML - * Specification</a>). + * The parser and the scanner form together the 'Parse' step in the loading process (see chapter 3.1 + * of the <a href="http://yaml.org/spec/1.1/">YAML Specification</a>). * </p> - * + * * @see org.yaml.snakeyaml.tokens.Token */ public interface Scanner { - /** - * Check if the next token is one of the given types. - * - * @param choices - * token IDs. - * @return <code>true</code> if the next token can be assigned to a variable - * of at least one of the given types. Returns <code>false</code> if - * no more tokens are available. - * @throws ScannerException - * Thrown in case of malformed input. - */ - boolean checkToken(Token.ID... choices); + /** + * Check if the next token is one of the given types. + * + * @param choices token IDs to match with + * @return <code>true</code> if the next token is one of the given types. Returns + * <code>false</code> if no more tokens are available. + * @throws ScannerException Thrown in case of malformed input. + */ + boolean checkToken(Token.ID... choices); - /** - * Return the next token, but do not delete it from the stream. - * - * @return The token that will be returned on the next call to - * {@link #getToken} - * @throws ScannerException - * Thrown in case of malformed input. - */ - Token peekToken(); + /** + * Return the next token, but do not delete it from the stream. + * + * @return The token that will be returned on the next call to {@link #getToken} + * @throws ScannerException Thrown in case of malformed input. + * @throws IndexOutOfBoundsException if no more token left + */ + Token peekToken(); - /** - * Returns the next token. - * <p> - * The token will be removed from the stream. - * </p> - * - * @throws ScannerException - * Thrown in case of malformed input. - */ - Token getToken(); + /** + * Returns the next token. + * <p> + * The token will be removed from the stream. (Every invocation of this method must happen after + * calling either {@link #checkToken} or {@link #peekToken()} + * </p> + * + * @return the coming token + * @throws ScannerException Thrown in case of malformed input. + * @throws IndexOutOfBoundsException if no more token left + */ + Token getToken(); } diff --git a/src/main/java/org/yaml/snakeyaml/scanner/ScannerException.java b/src/main/java/org/yaml/snakeyaml/scanner/ScannerException.java index b4ee9eef..1c3f5b51 100644 --- a/src/main/java/org/yaml/snakeyaml/scanner/ScannerException.java +++ b/src/main/java/org/yaml/snakeyaml/scanner/ScannerException.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; @@ -19,48 +17,35 @@ import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.MarkedYAMLException; /** - * Exception thrown by the {@link Scanner} implementations in case of malformed - * input. + * Exception thrown by the {@link Scanner} implementations in case of malformed input. */ public class ScannerException extends MarkedYAMLException { - private static final long serialVersionUID = 4782293188600445954L; + private static final long serialVersionUID = 4782293188600445954L; - /** - * Constructs an instance. - * - * @param context - * Part of the input document in which vicinity the problem - * occurred. - * @param contextMark - * Position of the <code>context</code> within the document. - * @param problem - * Part of the input document that caused the problem. - * @param problemMark - * Position of the <code>problem</code> within the document. - * @param note - * Message for the user with further information about the - * problem. - */ - public ScannerException(String context, Mark contextMark, String problem, Mark problemMark, - String note) { - super(context, contextMark, problem, problemMark, note); - } + /** + * Constructs an instance. + * + * @param context Part of the input document in which vicinity the problem occurred. + * @param contextMark Position of the <code>context</code> within the document. + * @param problem Part of the input document that caused the problem. + * @param problemMark Position of the <code>problem</code> within the document. + * @param note Message for the user with further information about the problem. + */ + public ScannerException(String context, Mark contextMark, String problem, Mark problemMark, + String note) { + super(context, contextMark, problem, problemMark, note); + } - /** - * Constructs an instance. - * - * @param context - * Part of the input document in which vicinity the problem - * occurred. - * @param contextMark - * Position of the <code>context</code> within the document. - * @param problem - * Part of the input document that caused the problem. - * @param problemMark - * Position of the <code>problem</code> within the document. - */ - public ScannerException(String context, Mark contextMark, String problem, Mark problemMark) { - this(context, contextMark, problem, problemMark, null); - } + /** + * Constructs an instance. + * + * @param context Part of the input document in which vicinity the problem occurred. + * @param contextMark Position of the <code>context</code> within the document. + * @param problem Part of the input document that caused the problem. + * @param problemMark Position of the <code>problem</code> within the document. + */ + public ScannerException(String context, Mark contextMark, String problem, Mark problemMark) { + this(context, contextMark, problem, problemMark, null); + } } diff --git a/src/main/java/org/yaml/snakeyaml/scanner/ScannerImpl.java b/src/main/java/org/yaml/snakeyaml/scanner/ScannerImpl.java index 4272aab7..ec8711f9 100644 --- a/src/main/java/org/yaml/snakeyaml/scanner/ScannerImpl.java +++ b/src/main/java/org/yaml/snakeyaml/scanner/ScannerImpl.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; @@ -24,7 +22,9 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; - +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.comments.CommentType; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.reader.StreamReader; @@ -34,6 +34,7 @@ import org.yaml.snakeyaml.tokens.BlockEndToken; import org.yaml.snakeyaml.tokens.BlockEntryToken; import org.yaml.snakeyaml.tokens.BlockMappingStartToken; import org.yaml.snakeyaml.tokens.BlockSequenceStartToken; +import org.yaml.snakeyaml.tokens.CommentToken; import org.yaml.snakeyaml.tokens.DirectiveToken; import org.yaml.snakeyaml.tokens.DocumentEndToken; import org.yaml.snakeyaml.tokens.DocumentStartToken; @@ -58,6 +59,7 @@ import org.yaml.snakeyaml.util.UriEncoder; * Scanner produces tokens of the following types: * STREAM-START * STREAM-END + * COMMENT * DIRECTIVE(name, value) * DOCUMENT-START * DOCUMENT-END @@ -80,2209 +82,2311 @@ import org.yaml.snakeyaml.util.UriEncoder; * </pre> */ public final class ScannerImpl implements Scanner { - /** - * A regular expression matching characters which are not in the hexadecimal - * set (0-9, A-F, a-f). - */ - private final static Pattern NOT_HEXA = Pattern.compile("[^0-9A-Fa-f]"); - - /** - * A mapping from an escaped character in the input stream to the character - * that they should be replaced with. - * - * YAML defines several common and a few uncommon escape sequences. - * - * @see <a href="http://www.yaml.org/spec/current.html#id2517668">4.1.6. - * Escape Sequences</a> - */ - public final static Map<Character, String> ESCAPE_REPLACEMENTS = new HashMap<Character, String>(); - - /** - * A mapping from a character to a number of bytes to read-ahead for that - * escape sequence. These escape sequences are used to handle unicode - * escaping in the following formats, where H is a hexadecimal character: - * - * <pre> - * \xHH : escaped 8-bit Unicode character - * \uHHHH : escaped 16-bit Unicode character - * \UHHHHHHHH : escaped 32-bit Unicode character - * </pre> - * - * @see <a href="http://yaml.org/spec/1.1/current.html#id872840">5.6. Escape - * Sequences</a> - */ - public final static Map<Character, Integer> ESCAPE_CODES = new HashMap<Character, Integer>(); - - static { - // ASCII null - ESCAPE_REPLACEMENTS.put(Character.valueOf('0'), "\0"); - // ASCII bell - ESCAPE_REPLACEMENTS.put(Character.valueOf('a'), "\u0007"); - // ASCII backspace - ESCAPE_REPLACEMENTS.put(Character.valueOf('b'), "\u0008"); - // ASCII horizontal tab - ESCAPE_REPLACEMENTS.put(Character.valueOf('t'), "\u0009"); - // ASCII newline (line feed; \n maps to 0x0A) - ESCAPE_REPLACEMENTS.put(Character.valueOf('n'), "\n"); - // ASCII vertical tab - ESCAPE_REPLACEMENTS.put(Character.valueOf('v'), "\u000B"); - // ASCII form-feed - ESCAPE_REPLACEMENTS.put(Character.valueOf('f'), "\u000C"); - // carriage-return (\r maps to 0x0D) - ESCAPE_REPLACEMENTS.put(Character.valueOf('r'), "\r"); - // ASCII escape character (Esc) - ESCAPE_REPLACEMENTS.put(Character.valueOf('e'), "\u001B"); - // ASCII space - ESCAPE_REPLACEMENTS.put(Character.valueOf(' '), "\u0020"); - // ASCII double-quote - ESCAPE_REPLACEMENTS.put(Character.valueOf('"'), "\""); - // ASCII backslash - ESCAPE_REPLACEMENTS.put(Character.valueOf('\\'), "\\"); - // Unicode next line - ESCAPE_REPLACEMENTS.put(Character.valueOf('N'), "\u0085"); - // Unicode non-breaking-space - ESCAPE_REPLACEMENTS.put(Character.valueOf('_'), "\u00A0"); - // Unicode line-separator - ESCAPE_REPLACEMENTS.put(Character.valueOf('L'), "\u2028"); - // Unicode paragraph separator - ESCAPE_REPLACEMENTS.put(Character.valueOf('P'), "\u2029"); - - // 8-bit Unicode - ESCAPE_CODES.put(Character.valueOf('x'), 2); - // 16-bit Unicode - ESCAPE_CODES.put(Character.valueOf('u'), 4); - // 32-bit Unicode (Supplementary characters are supported) - ESCAPE_CODES.put(Character.valueOf('U'), 8); - } - private final StreamReader reader; - // Had we reached the end of the stream? - private boolean done = false; - - // The number of unclosed '{' and '['. `flow_level == 0` means block - // context. - private int flowLevel = 0; - - // List of processed tokens that are not yet emitted. - private List<Token> tokens; - - // Number of tokens that were emitted through the `get_token` method. - private int tokensTaken = 0; - - // The current indentation level. - private int indent = -1; - - // Past indentation levels. - private ArrayStack<Integer> indents; - - // Variables related to simple keys treatment. See PyYAML. - - /** - * <pre> - * A simple key is a key that is not denoted by the '?' indicator. - * Example of simple keys: - * --- - * block simple key: value - * ? not a simple key: - * : { flow simple key: value } - * We emit the KEY token before all keys, so when we find a potential - * simple key, we try to locate the corresponding ':' indicator. - * Simple keys should be limited to a single line and 1024 characters. - * - * Can a simple key start at the current position? A simple key may - * start: - * - at the beginning of the line, not counting indentation spaces - * (in block context), - * - after '{', '[', ',' (in the flow context), - * - after '?', ':', '-' (in the block context). - * In the block context, this flag also signifies if a block collection - * may start at the current position. - * </pre> - */ - private boolean allowSimpleKey = true; - /* - * Keep track of possible simple keys. This is a dictionary. The key is - * `flow_level`; there can be no more that one possible simple key for each - * level. The value is a SimpleKey record: (token_number, required, index, - * line, column, mark) A simple key may start with ALIAS, ANCHOR, TAG, - * SCALAR(flow), '[', or '{' tokens. - */ - private Map<Integer, SimpleKey> possibleSimpleKeys; - - public ScannerImpl(StreamReader reader) { - this.reader = reader; - this.tokens = new ArrayList<Token>(100); - this.indents = new ArrayStack<Integer>(10); - // The order in possibleSimpleKeys is kept for nextPossibleSimpleKey() - this.possibleSimpleKeys = new LinkedHashMap<Integer, SimpleKey>(); - fetchStreamStart();// Add the STREAM-START token. - } - - /** - * Check whether the next token is one of the given types. - */ - public boolean checkToken(Token.ID... choices) { - while (needMoreTokens()) { - fetchMoreTokens(); - } - if (!this.tokens.isEmpty()) { - if (choices.length == 0) { - return true; - } - // since profiler puts this method on top (it is used a lot), we - // should not use 'foreach' here because of the performance reasons - Token.ID first = this.tokens.get(0).getTokenId(); - for (int i = 0; i < choices.length; i++) { - if (first == choices[i]) { - return true; - } - } - } - return false; - } - - /** - * Return the next token, but do not delete it from the queue. - */ - public Token peekToken() { - while (needMoreTokens()) { - fetchMoreTokens(); - } - return this.tokens.get(0); - } - - /** - * Return the next token, removing it from the queue. - */ - public Token getToken() { - if (!this.tokens.isEmpty()) { - this.tokensTaken++; - return this.tokens.remove(0); - } - return null; - } - - // Private methods. - /** - * Returns true if more tokens should be scanned. - */ - private boolean needMoreTokens() { - // If we are done, we do not require more tokens. - if (this.done) { - return false; - } - // If we aren't done, but we have no tokens, we need to scan more. - if (this.tokens.isEmpty()) { - return true; - } - // The current token may be a potential simple key, so we - // need to look further. - stalePossibleSimpleKeys(); - return nextPossibleSimpleKey() == this.tokensTaken; - } - - /** - * Fetch one or more tokens from the StreamReader. - */ - private void fetchMoreTokens() { - // Eat whitespaces and comments until we reach the next token. - scanToNextToken(); - // Remove obsolete possible simple keys. - stalePossibleSimpleKeys(); - // Compare the current indentation and column. It may add some tokens - // and decrease the current indentation level. - unwindIndent(reader.getColumn()); - // Peek the next character, to decide what the next group of tokens - // will look like. - char ch = reader.peek(); - switch (ch) { - case '\0': - // Is it the end of stream? - fetchStreamEnd(); - return; - case '%': - // Is it a directive? - if (checkDirective()) { - fetchDirective(); - return; - } - break; - case '-': - // Is it the document start? - if (checkDocumentStart()) { - fetchDocumentStart(); - return; - // Is it the block entry indicator? - } else if (checkBlockEntry()) { - fetchBlockEntry(); - return; - } - break; - case '.': - // Is it the document end? - if (checkDocumentEnd()) { - fetchDocumentEnd(); - return; - } - break; - // TODO support for BOM within a stream. (not implemented in PyYAML) - case '[': - // Is it the flow sequence start indicator? - fetchFlowSequenceStart(); - return; - case '{': - // Is it the flow mapping start indicator? - fetchFlowMappingStart(); - return; - case ']': - // Is it the flow sequence end indicator? - fetchFlowSequenceEnd(); - return; - case '}': - // Is it the flow mapping end indicator? - fetchFlowMappingEnd(); - return; - case ',': - // Is it the flow entry indicator? - fetchFlowEntry(); - return; - // see block entry indicator above - case '?': - // Is it the key indicator? - if (checkKey()) { - fetchKey(); - return; - } - break; - case ':': - // Is it the value indicator? - if (checkValue()) { - fetchValue(); - return; - } - break; - case '*': - // Is it an alias? - fetchAlias(); - return; - case '&': - // Is it an anchor? - fetchAnchor(); - return; - case '!': - // Is it a tag? - fetchTag(); - return; - case '|': - // Is it a literal scalar? - if (this.flowLevel == 0) { - fetchLiteral(); - return; - } - break; - case '>': - // Is it a folded scalar? - if (this.flowLevel == 0) { - fetchFolded(); - return; - } - break; - case '\'': - // Is it a single quoted scalar? - fetchSingle(); - return; - case '"': - // Is it a double quoted scalar? - fetchDouble(); - return; - } - // It must be a plain scalar then. - if (checkPlain()) { - fetchPlain(); - return; - } - // No? It's an error. Let's produce a nice error message.We do this by - // converting escaped characters into their escape sequences. This is a - // backwards use of the ESCAPE_REPLACEMENTS map. - String chRepresentation = String.valueOf(ch); - for (Character s : ESCAPE_REPLACEMENTS.keySet()) { - String v = ESCAPE_REPLACEMENTS.get(s); - if (v.equals(chRepresentation)) { - chRepresentation = "\\" + s;// ' ' -> '\t' - break; - } - } - if (ch == '\t') - chRepresentation += "(TAB)"; - String text = String - .format("found character '%s' that cannot start any token. (Do not use %s for indentation)", - chRepresentation, chRepresentation); - throw new ScannerException("while scanning for the next token", null, text, - reader.getMark()); - } - - // Simple keys treatment. - - /** - * Return the number of the nearest possible simple key. Actually we don't - * need to loop through the whole dictionary. - */ - private int nextPossibleSimpleKey() { - /* - * the implementation is not as in PyYAML. Because - * this.possibleSimpleKeys is ordered we can simply take the first key - */ - if (!this.possibleSimpleKeys.isEmpty()) { - return this.possibleSimpleKeys.values().iterator().next().getTokenNumber(); - } - return -1; - } - - /** - * <pre> - * Remove entries that are no longer possible simple keys. According to - * the YAML specification, simple keys - * - should be limited to a single line, - * - should be no longer than 1024 characters. - * Disabling this procedure will allow simple keys of any length and - * height (may cause problems if indentation is broken though). - * </pre> - */ - private void stalePossibleSimpleKeys() { - if (!this.possibleSimpleKeys.isEmpty()) { - for (Iterator<SimpleKey> iterator = this.possibleSimpleKeys.values().iterator(); iterator - .hasNext();) { - SimpleKey key = iterator.next(); - if ((key.getLine() != reader.getLine()) - || (reader.getIndex() - key.getIndex() > 1024)) { - // If the key is not on the same line as the current - // position OR the difference in column between the token - // start and the current position is more than the maximum - // simple key length, then this cannot be a simple key. - if (key.isRequired()) { - // If the key was required, this implies an error - // condition. - throw new ScannerException("while scanning a simple key", key.getMark(), - "could not find expected ':'", reader.getMark()); - } - iterator.remove(); - } - } - } - } - - /** - * The next token may start a simple key. We check if it's possible and save - * its position. This function is called for ALIAS, ANCHOR, TAG, - * SCALAR(flow), '[', and '{'. - */ - private void savePossibleSimpleKey() { - // The next token may start a simple key. We check if it's possible - // and save its position. This function is called for - // ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'. - - // Check if a simple key is required at the current position. - // A simple key is required if this position is the root flowLevel, AND - // the current indentation level is the same as the last indent-level. - boolean required = (this.flowLevel == 0) && (this.indent == this.reader.getColumn()); - - if (allowSimpleKey || !required) { - // A simple key is required only if it is the first token in the - // current line. Therefore it is always allowed. - } else { - throw new YAMLException( - "A simple key is required only if it is the first token in the current line"); - } - - // The next token might be a simple key. Let's save it's number and - // position. - if (this.allowSimpleKey) { - removePossibleSimpleKey(); - int tokenNumber = this.tokensTaken + this.tokens.size(); - SimpleKey key = new SimpleKey(tokenNumber, required, reader.getIndex(), - reader.getLine(), this.reader.getColumn(), this.reader.getMark()); - this.possibleSimpleKeys.put(this.flowLevel, key); + /** + * A regular expression matching characters which are not in the hexadecimal set (0-9, A-F, a-f). + */ + private static final Pattern NOT_HEXA = Pattern.compile("[^0-9A-Fa-f]"); + + /** + * A mapping from an escaped character in the input stream to the string representation that they + * should be replaced with. + * + * YAML defines several common and a few uncommon escape sequences. + * + * @see <a href="http://www.yaml.org/spec/current.html#id2517668">4.1.6. Escape Sequences</a> + */ + public static final Map<Character, String> ESCAPE_REPLACEMENTS = new HashMap<Character, String>(); + + /** + * A mapping from a character to a number of bytes to read-ahead for that escape sequence. These + * escape sequences are used to handle unicode escaping in the following formats, where H is a + * hexadecimal character: + * + * <pre> + * \xHH : escaped 8-bit Unicode character + * \uHHHH : escaped 16-bit Unicode character + * \UHHHHHHHH : escaped 32-bit Unicode character + * </pre> + * + * @see <a href="http://yaml.org/spec/1.1/current.html#id872840">5.6. Escape Sequences</a> + */ + public static final Map<Character, Integer> ESCAPE_CODES = new HashMap<Character, Integer>(); + + static { + // ASCII null + ESCAPE_REPLACEMENTS.put(Character.valueOf('0'), "\0"); + // ASCII bell + ESCAPE_REPLACEMENTS.put(Character.valueOf('a'), "\u0007"); + // ASCII backspace + ESCAPE_REPLACEMENTS.put(Character.valueOf('b'), "\u0008"); + // ASCII horizontal tab + ESCAPE_REPLACEMENTS.put(Character.valueOf('t'), "\u0009"); + // ASCII newline (line feed; \n maps to 0x0A) + ESCAPE_REPLACEMENTS.put(Character.valueOf('n'), "\n"); + // ASCII vertical tab + ESCAPE_REPLACEMENTS.put(Character.valueOf('v'), "\u000B"); + // ASCII form-feed + ESCAPE_REPLACEMENTS.put(Character.valueOf('f'), "\u000C"); + // carriage-return (\r maps to 0x0D) + ESCAPE_REPLACEMENTS.put(Character.valueOf('r'), "\r"); + // ASCII escape character (Esc) + ESCAPE_REPLACEMENTS.put(Character.valueOf('e'), "\u001B"); + // ASCII space + ESCAPE_REPLACEMENTS.put(Character.valueOf(' '), "\u0020"); + // ASCII double-quote + ESCAPE_REPLACEMENTS.put(Character.valueOf('"'), "\""); + // ASCII backslash + ESCAPE_REPLACEMENTS.put(Character.valueOf('\\'), "\\"); + // Unicode next line + ESCAPE_REPLACEMENTS.put(Character.valueOf('N'), "\u0085"); + // Unicode non-breaking-space + ESCAPE_REPLACEMENTS.put(Character.valueOf('_'), "\u00A0"); + // Unicode line-separator + ESCAPE_REPLACEMENTS.put(Character.valueOf('L'), "\u2028"); + // Unicode paragraph separator + ESCAPE_REPLACEMENTS.put(Character.valueOf('P'), "\u2029"); + + // 8-bit Unicode + ESCAPE_CODES.put(Character.valueOf('x'), 2); + // 16-bit Unicode + ESCAPE_CODES.put(Character.valueOf('u'), 4); + // 32-bit Unicode (Supplementary characters are supported) + ESCAPE_CODES.put(Character.valueOf('U'), 8); + } + + private final StreamReader reader; + // Had we reached the end of the stream? + private boolean done = false; + + // The number of unclosed '{' and '['. `flow_level == 0` means block context. + private int flowLevel = 0; + + // List of processed tokens that are not yet emitted. + private final List<Token> tokens; + + // The last added token + private Token lastToken; + + // Number of tokens that were emitted through the `getToken()` method. + private int tokensTaken = 0; + + // The current indentation level. + private int indent = -1; + + // Past indentation levels. + private final ArrayStack<Integer> indents; + + // A flag that indicates if comments should be parsed + private boolean parseComments; + + private final LoaderOptions loaderOptions; + + // Variables related to simple keys treatment. See PyYAML. + + /** + * <pre> + * A simple key is a key that is not denoted by the '?' indicator. + * Example of simple keys: + * --- + * block simple key: value + * ? not a simple key: + * : { flow simple key: value } + * We emit the KEY token before all keys, so when we find a potential + * simple key, we try to locate the corresponding ':' indicator. + * Simple keys should be limited to a single line and 1024 characters. + * + * Can a simple key start at the current position? A simple key may + * start: + * - at the beginning of the line, not counting indentation spaces + * (in block context), + * - after '{', '[', ',' (in the flow context), + * - after '?', ':', '-' (in the block context). + * In the block context, this flag also signifies if a block collection + * may start at the current position. + * </pre> + */ + private boolean allowSimpleKey = true; + + /* + * Keep track of possible simple keys. This is a dictionary. The key is `flow_level`; there can be + * no more than one possible simple key for each level. The value is a SimpleKey record: + * (token_number, required, index, line, column, mark) A simple key may start with ALIAS, ANCHOR, + * TAG, SCALAR(flow), '[', or '{' tokens. + */ + private final Map<Integer, SimpleKey> possibleSimpleKeys; + + public ScannerImpl(StreamReader reader) { + this(reader, new LoaderOptions()); + } + + public ScannerImpl(StreamReader reader, LoaderOptions options) { + this.parseComments = options.isProcessComments(); + this.reader = reader; + this.tokens = new ArrayList<Token>(100); + this.indents = new ArrayStack<Integer>(10); + // The order in possibleSimpleKeys is kept for nextPossibleSimpleKey() + this.possibleSimpleKeys = new LinkedHashMap<Integer, SimpleKey>(); + this.loaderOptions = options; + fetchStreamStart();// Add the STREAM-START token. + } + + /** + * Please use LoaderOptions instead Set the scanner to ignore comments or parse them as a + * <code>CommentToken</code>. + * + * @param parseComments <code>true</code> to parse; <code>false</code> to ignore + */ + @Deprecated + public ScannerImpl setParseComments(boolean parseComments) { + this.parseComments = parseComments; + return this; + } + + @Deprecated + public boolean isParseComments() { + return parseComments; + } + + /** + * Check whether the next token is one of the given types. + */ + public boolean checkToken(Token.ID... choices) { + while (needMoreTokens()) { + fetchMoreTokens(); + } + if (!this.tokens.isEmpty()) { + if (choices.length == 0) { + return true; + } + // since profiler puts this method on top (it is used a lot), we + // should not use 'foreach' here because of the performance reasons + Token.ID first = this.tokens.get(0).getTokenId(); + for (int i = 0; i < choices.length; i++) { + if (first == choices[i]) { + return true; + } + } + } + return false; + } + + /** + * Return the next token, but do not delete it from the queue. + */ + public Token peekToken() { + while (needMoreTokens()) { + fetchMoreTokens(); + } + return this.tokens.get(0); + } + + /** + * Return the next token, removing it from the queue. + */ + public Token getToken() { + this.tokensTaken++; + return this.tokens.remove(0); + } + + // Private methods. + + private void addToken(Token token) { + lastToken = token; + this.tokens.add(token); + } + + private void addToken(int index, Token token) { + if (index == this.tokens.size()) { + lastToken = token; + } + this.tokens.add(index, token); + } + + private void addAllTokens(List<Token> tokens) { + lastToken = tokens.get(tokens.size() - 1); + this.tokens.addAll(tokens); + } + + /** + * Returns true if more tokens should be scanned. + */ + private boolean needMoreTokens() { + // If we are done, we do not require more tokens. + if (this.done) { + return false; + } + // If we aren't done, but we have no tokens, we need to scan more. + if (this.tokens.isEmpty()) { + return true; + } + // The current token may be a potential simple key, so we + // need to look further. + stalePossibleSimpleKeys(); + return nextPossibleSimpleKey() == this.tokensTaken; + } + + /** + * Fetch one or more tokens from the StreamReader. + */ + private void fetchMoreTokens() { + if (reader.getIndex() > loaderOptions.getCodePointLimit()) { + throw new YAMLException("The incoming YAML document exceeds the limit: " + + loaderOptions.getCodePointLimit() + " code points."); + } + // Eat whitespaces and process comments until we reach the next token. + scanToNextToken(); + // Remove obsolete possible simple keys. + stalePossibleSimpleKeys(); + // Compare the current indentation and column. It may add some tokens + // and decrease the current indentation level. + unwindIndent(reader.getColumn()); + // Peek the next code point, to decide what the next group of tokens + // will look like. + int c = reader.peek(); + switch (c) { + case '\0': + // Is it the end of stream? + fetchStreamEnd(); + return; + case '%': + // Is it a directive? + if (checkDirective()) { + fetchDirective(); + return; + } + break; + case '-': + // Is it the document start? + if (checkDocumentStart()) { + fetchDocumentStart(); + return; + // Is it the block entry indicator? + } else if (checkBlockEntry()) { + fetchBlockEntry(); + return; + } + break; + case '.': + // Is it the document end? + if (checkDocumentEnd()) { + fetchDocumentEnd(); + return; + } + break; + // TODO support for BOM within a stream. (also not implemented in PyYAML) + case '[': + // Is it the flow sequence start indicator? + fetchFlowSequenceStart(); + return; + case '{': + // Is it the flow mapping start indicator? + fetchFlowMappingStart(); + return; + case ']': + // Is it the flow sequence end indicator? + fetchFlowSequenceEnd(); + return; + case '}': + // Is it the flow mapping end indicator? + fetchFlowMappingEnd(); + return; + case ',': + // Is it the flow entry indicator? + fetchFlowEntry(); + return; + // see block entry indicator above + case '?': + // Is it the key indicator? + if (checkKey()) { + fetchKey(); + return; + } + break; + case ':': + // Is it the value indicator? + if (checkValue()) { + fetchValue(); + return; + } + break; + case '*': + // Is it an alias? + fetchAlias(); + return; + case '&': + // Is it an anchor? + fetchAnchor(); + return; + case '!': + // Is it a tag? + fetchTag(); + return; + case '|': + // Is it a literal scalar? + if (this.flowLevel == 0) { + fetchLiteral(); + return; } - } - - /** - * Remove the saved possible key position at the current flow level. - */ - private void removePossibleSimpleKey() { - SimpleKey key = possibleSimpleKeys.remove(flowLevel); - if (key != null && key.isRequired()) { + break; + case '>': + // Is it a folded scalar? + if (this.flowLevel == 0) { + fetchFolded(); + return; + } + break; + case '\'': + // Is it a single quoted scalar? + fetchSingle(); + return; + case '"': + // Is it a double quoted scalar? + fetchDouble(); + return; + } + // It must be a plain scalar then. + if (checkPlain()) { + fetchPlain(); + return; + } + // No? It's an error. Let's produce a nice error message.We do this by + // converting escaped characters into their escape sequences. This is a + // backwards use of the ESCAPE_REPLACEMENTS map. + String chRepresentation = escapeChar(String.valueOf(Character.toChars(c))); + if (c == '\t') { + chRepresentation += "(TAB)"; + } + String text = String.format( + "found character '%s' that cannot start any token. (Do not use %s for indentation)", + chRepresentation, chRepresentation); + throw new ScannerException("while scanning for the next token", null, text, reader.getMark()); + } + + /** + * This is implemented in CharConstants in SnakeYAML Engine + */ + private String escapeChar(String chRepresentation) { + for (Character s : ESCAPE_REPLACEMENTS.keySet()) { + String v = ESCAPE_REPLACEMENTS.get(s); + if (v.equals(chRepresentation)) { + return "\\" + s;// ' ' -> '\t' + } + } + return chRepresentation; + } + + // Simple keys treatment. + + /** + * Return the number of the nearest possible simple key. Actually we don't need to loop through + * the whole dictionary. + */ + private int nextPossibleSimpleKey() { + /* + * the implementation is not as in PyYAML. Because this.possibleSimpleKeys is ordered we can + * simply take the first key + */ + if (!this.possibleSimpleKeys.isEmpty()) { + return this.possibleSimpleKeys.values().iterator().next().getTokenNumber(); + } + return -1; + } + + /** + * <pre> + * Remove entries that are no longer possible simple keys. According to + * the YAML specification, simple keys + * - should be limited to a single line, + * - should be no longer than 1024 characters. + * Disabling this procedure will allow simple keys of any length and + * height (may cause problems if indentation is broken though). + * </pre> + */ + private void stalePossibleSimpleKeys() { + if (!this.possibleSimpleKeys.isEmpty()) { + for (Iterator<SimpleKey> iterator = this.possibleSimpleKeys.values().iterator(); iterator + .hasNext();) { + SimpleKey key = iterator.next(); + if ((key.getLine() != reader.getLine()) || (reader.getIndex() - key.getIndex() > 1024)) { + // If the key is not on the same line as the current + // position OR the difference in column between the token + // start and the current position is more than the maximum + // simple key length, then this cannot be a simple key. + if (key.isRequired()) { + // If the key was required, this implies an error + // condition. throw new ScannerException("while scanning a simple key", key.getMark(), - "could not find expected ':'", reader.getMark()); - } - } - - // Indentation functions. - - /** - * * Handle implicitly ending multiple levels of block nodes by decreased - * indentation. This function becomes important on lines 4 and 7 of this - * example: - * - * <pre> - * 1) book one: - * 2) part one: - * 3) chapter one - * 4) part two: - * 5) chapter one - * 6) chapter two - * 7) book two: - * </pre> - * - * In flow context, tokens should respect indentation. Actually the - * condition should be `self.indent >= column` according to the spec. But - * this condition will prohibit intuitively correct constructions such as - * key : { } </pre> - */ - private void unwindIndent(int col) { - // In the flow context, indentation is ignored. We make the scanner less - // restrictive then specification requires. - if (this.flowLevel != 0) { - return; - } - - // In block context, we may need to issue the BLOCK-END tokens. - while (this.indent > col) { - Mark mark = reader.getMark(); - this.indent = this.indents.pop(); - this.tokens.add(new BlockEndToken(mark, mark)); - } - } - - /** - * Check if we need to increase indentation. - */ - private boolean addIndent(int column) { - if (this.indent < column) { - this.indents.push(this.indent); - this.indent = column; - return true; - } - return false; - } - - // Fetchers. - - /** - * We always add STREAM-START as the first token and STREAM-END as the last - * token. - */ - private void fetchStreamStart() { - // Read the token. + "could not find expected ':'", reader.getMark()); + } + iterator.remove(); + } + } + } + } + + /** + * The next token may start a simple key. We check if it's possible and save its position. This + * function is called for ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'. + */ + private void savePossibleSimpleKey() { + // The next token may start a simple key. We check if it's possible + // and save its position. This function is called for + // ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'. + + // Check if a simple key is required at the current position. + // A simple key is required if this position is the root flowLevel, AND + // the current indentation level is the same as the last indent-level. + boolean required = (this.flowLevel == 0) && (this.indent == this.reader.getColumn()); + + if (allowSimpleKey || !required) { + // A simple key is required only if it is the first token in the + // current line. Therefore it is always allowed. + } else { + throw new YAMLException( + "A simple key is required only if it is the first token in the current line"); + } + + // The next token might be a simple key. Let's save it's number and + // position. + if (this.allowSimpleKey) { + removePossibleSimpleKey(); + int tokenNumber = this.tokensTaken + this.tokens.size(); + SimpleKey key = new SimpleKey(tokenNumber, required, reader.getIndex(), reader.getLine(), + this.reader.getColumn(), this.reader.getMark()); + this.possibleSimpleKeys.put(this.flowLevel, key); + } + } + + /** + * Remove the saved possible key position at the current flow level. + */ + private void removePossibleSimpleKey() { + SimpleKey key = possibleSimpleKeys.remove(flowLevel); + if (key != null && key.isRequired()) { + throw new ScannerException("while scanning a simple key", key.getMark(), + "could not find expected ':'", reader.getMark()); + } + } + + // Indentation functions. + + /** + * * Handle implicitly ending multiple levels of block nodes by decreased indentation. This + * function becomes important on lines 4 and 7 of this example: + * + * <pre> + * 1) book one: + * 2) part one: + * 3) chapter one + * 4) part two: + * 5) chapter one + * 6) chapter two + * 7) book two: + * </pre> + * + * In flow context, tokens should respect indentation. Actually the condition should be + * `self.indent >= column` according to the spec. But this condition will prohibit intuitively + * correct constructions such as key : { } + * </pre> + */ + private void unwindIndent(int col) { + // In the flow context, indentation is ignored. We make the scanner less + // restrictive than specification requires. + if (this.flowLevel != 0) { + return; + } + + // In block context, we may need to issue the BLOCK-END tokens. + while (this.indent > col) { + Mark mark = reader.getMark(); + this.indent = this.indents.pop(); + addToken(new BlockEndToken(mark, mark)); + } + } + + /** + * Check if we need to increase indentation. + */ + private boolean addIndent(int column) { + if (this.indent < column) { + this.indents.push(this.indent); + this.indent = column; + return true; + } + return false; + } + + // Fetchers. + + /** + * We always add STREAM-START as the first token and STREAM-END as the last token. + */ + private void fetchStreamStart() { + // Read the token. + Mark mark = reader.getMark(); + + // Add STREAM-START. + Token token = new StreamStartToken(mark, mark); + addToken(token); + } + + private void fetchStreamEnd() { + // Set the current indentation to -1. + unwindIndent(-1); + + // Reset simple keys. + removePossibleSimpleKey(); + this.allowSimpleKey = false; + this.possibleSimpleKeys.clear(); + + // Read the token. + Mark mark = reader.getMark(); + + // Add STREAM-END. + Token token = new StreamEndToken(mark, mark); + addToken(token); + + // The stream is finished. + this.done = true; + } + + /** + * Fetch a YAML directive. Directives are presentation details that are interpreted as + * instructions to the processor. YAML defines two kinds of directives, YAML and TAG; all other + * types are reserved for future use. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id864824">3.2.3.4. Directives</a> + */ + private void fetchDirective() { + // Set the current indentation to -1. + unwindIndent(-1); + + // Reset simple keys. + removePossibleSimpleKey(); + this.allowSimpleKey = false; + + // Scan and add DIRECTIVE. + List<Token> tok = scanDirective(); + addAllTokens(tok); + } + + /** + * Fetch a document-start token ("---"). + */ + private void fetchDocumentStart() { + fetchDocumentIndicator(true); + } + + /** + * Fetch a document-end token ("..."). + */ + private void fetchDocumentEnd() { + fetchDocumentIndicator(false); + } + + /** + * Fetch a document indicator, either "---" for "document-start", or else "..." for "document-end. + * The type is chosen by the given boolean. + */ + private void fetchDocumentIndicator(boolean isDocumentStart) { + // Set the current indentation to -1. + unwindIndent(-1); + + // Reset simple keys. Note that there could not be a block collection + // after '---'. + removePossibleSimpleKey(); + this.allowSimpleKey = false; + + // Add DOCUMENT-START or DOCUMENT-END. + Mark startMark = reader.getMark(); + reader.forward(3); + Mark endMark = reader.getMark(); + Token token; + if (isDocumentStart) { + token = new DocumentStartToken(startMark, endMark); + } else { + token = new DocumentEndToken(startMark, endMark); + } + addToken(token); + } + + private void fetchFlowSequenceStart() { + fetchFlowCollectionStart(false); + } + + private void fetchFlowMappingStart() { + fetchFlowCollectionStart(true); + } + + /** + * Fetch a flow-style collection start, which is either a sequence or a mapping. The type is + * determined by the given boolean. + * + * A flow-style collection is in a format similar to JSON. Sequences are started by '[' and ended + * by ']'; mappings are started by '{' and ended by '}'. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + * + * @param isMappingStart + */ + private void fetchFlowCollectionStart(boolean isMappingStart) { + // '[' and '{' may start a simple key. + savePossibleSimpleKey(); + + // Increase the flow level. + this.flowLevel++; + + // Simple keys are allowed after '[' and '{'. + this.allowSimpleKey = true; + + // Add FLOW-SEQUENCE-START or FLOW-MAPPING-START. + Mark startMark = reader.getMark(); + reader.forward(1); + Mark endMark = reader.getMark(); + Token token; + if (isMappingStart) { + token = new FlowMappingStartToken(startMark, endMark); + } else { + token = new FlowSequenceStartToken(startMark, endMark); + } + addToken(token); + } + + private void fetchFlowSequenceEnd() { + fetchFlowCollectionEnd(false); + } + + private void fetchFlowMappingEnd() { + fetchFlowCollectionEnd(true); + } + + /** + * Fetch a flow-style collection end, which is either a sequence or a mapping. The type is + * determined by the given boolean. + * + * A flow-style collection is in a format similar to JSON. Sequences are started by '[' and ended + * by ']'; mappings are started by '{' and ended by '}'. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + */ + private void fetchFlowCollectionEnd(boolean isMappingEnd) { + // Reset possible simple key on the current level. + removePossibleSimpleKey(); + + // Decrease the flow level. + this.flowLevel--; + + // No simple keys after ']' or '}'. + this.allowSimpleKey = false; + + // Add FLOW-SEQUENCE-END or FLOW-MAPPING-END. + Mark startMark = reader.getMark(); + reader.forward(); + Mark endMark = reader.getMark(); + Token token; + if (isMappingEnd) { + token = new FlowMappingEndToken(startMark, endMark); + } else { + token = new FlowSequenceEndToken(startMark, endMark); + } + addToken(token); + } + + /** + * Fetch an entry in the flow style. Flow-style entries occur either immediately after the start + * of a collection, or else after a comma. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + */ + private void fetchFlowEntry() { + // Simple keys are allowed after ','. + this.allowSimpleKey = true; + + // Reset possible simple key on the current level. + removePossibleSimpleKey(); + + // Add FLOW-ENTRY. + Mark startMark = reader.getMark(); + reader.forward(); + Mark endMark = reader.getMark(); + Token token = new FlowEntryToken(startMark, endMark); + addToken(token); + } + + /** + * Fetch an entry in the block style. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + */ + private void fetchBlockEntry() { + // Block context needs additional checks. + if (this.flowLevel == 0) { + // Are we allowed to start a new entry? + if (!this.allowSimpleKey) { + throw new ScannerException(null, null, "sequence entries are not allowed here", + reader.getMark()); + } + + // We may need to add BLOCK-SEQUENCE-START. + if (addIndent(this.reader.getColumn())) { Mark mark = reader.getMark(); - - // Add STREAM-START. - Token token = new StreamStartToken(mark, mark); - this.tokens.add(token); - } - - private void fetchStreamEnd() { - // Set the current intendation to -1. - unwindIndent(-1); - - // Reset simple keys. - removePossibleSimpleKey(); - this.allowSimpleKey = false; - this.possibleSimpleKeys.clear(); - - // Read the token. + addToken(new BlockSequenceStartToken(mark, mark)); + } + } else { + // It's an error for the block entry to occur in the flow + // context,but we let the parser detect this. + } + // Simple keys are allowed after '-'. + this.allowSimpleKey = true; + + // Reset possible simple key on the current level. + removePossibleSimpleKey(); + + // Add BLOCK-ENTRY. + Mark startMark = reader.getMark(); + reader.forward(); + Mark endMark = reader.getMark(); + Token token = new BlockEntryToken(startMark, endMark); + addToken(token); + } + + /** + * Fetch a key in a block-style mapping. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + */ + private void fetchKey() { + // Block context needs additional checks. + if (this.flowLevel == 0) { + // Are we allowed to start a key (not necessary a simple)? + if (!this.allowSimpleKey) { + throw new ScannerException(null, null, "mapping keys are not allowed here", + reader.getMark()); + } + // We may need to add BLOCK-MAPPING-START. + if (addIndent(this.reader.getColumn())) { Mark mark = reader.getMark(); - - // Add STREAM-END. - Token token = new StreamEndToken(mark, mark); - this.tokens.add(token); - - // The stream is finished. - this.done = true; - } - - /** - * Fetch a YAML directive. Directives are presentation details that are - * interpreted as instructions to the processor. YAML defines two kinds of - * directives, YAML and TAG; all other types are reserved for future use. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id864824"></a> - */ - private void fetchDirective() { - // Set the current intendation to -1. - unwindIndent(-1); - - // Reset simple keys. - removePossibleSimpleKey(); - this.allowSimpleKey = false; - - // Scan and add DIRECTIVE. - Token tok = scanDirective(); - this.tokens.add(tok); - } - - /** - * Fetch a document-start token ("---"). - */ - private void fetchDocumentStart() { - fetchDocumentIndicator(true); - } - - /** - * Fetch a document-end token ("..."). - */ - private void fetchDocumentEnd() { - fetchDocumentIndicator(false); - } - - /** - * Fetch a document indicator, either "---" for "document-start", or else - * "..." for "document-end. The type is chosen by the given boolean. - */ - private void fetchDocumentIndicator(boolean isDocumentStart) { - // Set the current intendation to -1. - unwindIndent(-1); - - // Reset simple keys. Note that there could not be a block collection - // after '---'. - removePossibleSimpleKey(); - this.allowSimpleKey = false; - - // Add DOCUMENT-START or DOCUMENT-END. - Mark startMark = reader.getMark(); - reader.forward(3); - Mark endMark = reader.getMark(); - Token token; - if (isDocumentStart) { - token = new DocumentStartToken(startMark, endMark); - } else { - token = new DocumentEndToken(startMark, endMark); - } - this.tokens.add(token); - } - - private void fetchFlowSequenceStart() { - fetchFlowCollectionStart(false); - } - - private void fetchFlowMappingStart() { - fetchFlowCollectionStart(true); - } - + addToken(new BlockMappingStartToken(mark, mark)); + } + } + // Simple keys are allowed after '?' in the block context. + this.allowSimpleKey = this.flowLevel == 0; + + // Reset possible simple key on the current level. + removePossibleSimpleKey(); + + // Add KEY. + Mark startMark = reader.getMark(); + reader.forward(); + Mark endMark = reader.getMark(); + Token token = new KeyToken(startMark, endMark); + addToken(token); + } + + /** + * Fetch a value in a block-style mapping. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + */ + private void fetchValue() { + // Do we determine a simple key? + SimpleKey key = this.possibleSimpleKeys.remove(this.flowLevel); + if (key != null) { + // Add KEY. + addToken(key.getTokenNumber() - this.tokensTaken, new KeyToken(key.getMark(), key.getMark())); + + // If this key starts a new block mapping, we need to add + // BLOCK-MAPPING-START. + if (this.flowLevel == 0) { + if (addIndent(key.getColumn())) { + addToken(key.getTokenNumber() - this.tokensTaken, + new BlockMappingStartToken(key.getMark(), key.getMark())); + } + } + // There cannot be two simple keys one after another. + this.allowSimpleKey = false; + + } else { + // It must be a part of a complex key. + // Block context needs additional checks. Do we really need them? + // They will be caught by the parser anyway. + if (this.flowLevel == 0) { + + // We are allowed to start a complex value if and only if we can + // start a simple key. + if (!this.allowSimpleKey) { + throw new ScannerException(null, null, "mapping values are not allowed here", + reader.getMark()); + } + } + + // If this value starts a new block mapping, we need to add + // BLOCK-MAPPING-START. It will be detected as an error later by + // the parser. + if (flowLevel == 0) { + if (addIndent(reader.getColumn())) { + Mark mark = reader.getMark(); + addToken(new BlockMappingStartToken(mark, mark)); + } + } + + // Simple keys are allowed after ':' in the block context. + allowSimpleKey = flowLevel == 0; + + // Reset possible simple key on the current level. + removePossibleSimpleKey(); + } + // Add VALUE. + Mark startMark = reader.getMark(); + reader.forward(); + Mark endMark = reader.getMark(); + Token token = new ValueToken(startMark, endMark); + addToken(token); + } + + /** + * Fetch an alias, which is a reference to an anchor. Aliases take the format: + * + * <pre> + * *(anchor name) + * </pre> + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863390">3.2.2.2. Anchors and Aliases</a> + */ + private void fetchAlias() { + // ALIAS could be a simple key. + savePossibleSimpleKey(); + + // No simple keys after ALIAS. + this.allowSimpleKey = false; + + // Scan and add ALIAS. + Token tok = scanAnchor(false); + addToken(tok); + } + + /** + * Fetch an anchor. Anchors take the form: + * + * <pre> + * &(anchor name) + * </pre> + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863390">3.2.2.2. Anchors and Aliases</a> + */ + private void fetchAnchor() { + // ANCHOR could start a simple key. + savePossibleSimpleKey(); + + // No simple keys after ANCHOR. + this.allowSimpleKey = false; + + // Scan and add ANCHOR. + Token tok = scanAnchor(true); + addToken(tok); + } + + /** + * Fetch a tag. Tags take a complex form. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id861700">3.2.1.2. Tags</a> + */ + private void fetchTag() { + // TAG could start a simple key. + savePossibleSimpleKey(); + + // No simple keys after TAG. + this.allowSimpleKey = false; + + // Scan and add TAG. + Token tok = scanTag(); + addToken(tok); + } + + /** + * Fetch a literal scalar, denoted with a vertical-bar. This is the type best used for source code + * and other content, such as binary data, which must be included verbatim. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + */ + private void fetchLiteral() { + fetchBlockScalar('|'); + } + + /** + * Fetch a folded scalar, denoted with a greater-than sign. This is the type best used for long + * content, such as the text of a chapter or description. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + */ + private void fetchFolded() { + fetchBlockScalar('>'); + } + + /** + * Fetch a block scalar (literal or folded). + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + * + * @param style + */ + private void fetchBlockScalar(char style) { + // A simple key may follow a block scalar. + this.allowSimpleKey = true; + + // Reset possible simple key on the current level. + removePossibleSimpleKey(); + + // Scan and add SCALAR. + List<Token> tok = scanBlockScalar(style); + addAllTokens(tok); + } + + /** + * Fetch a single-quoted (') scalar. + */ + private void fetchSingle() { + fetchFlowScalar('\''); + } + + /** + * Fetch a double-quoted (") scalar. + */ + private void fetchDouble() { + fetchFlowScalar('"'); + } + + /** + * Fetch a flow scalar (single- or double-quoted). + * + * @see <a href="http://www.yaml.org/spec/1.1/#id863975">3.2.3.1. Node Styles</a> + * + * @param style + */ + private void fetchFlowScalar(char style) { + // A flow scalar could be a simple key. + savePossibleSimpleKey(); + + // No simple keys after flow scalars. + this.allowSimpleKey = false; + + // Scan and add SCALAR. + Token tok = scanFlowScalar(style); + addToken(tok); + } + + /** + * Fetch a plain scalar. + */ + private void fetchPlain() { + // A plain scalar could be a simple key. + savePossibleSimpleKey(); + + // No simple keys after plain scalars. But note that `scan_plain` will + // change this flag if the scan is finished at the beginning of the + // line. + this.allowSimpleKey = false; + + // Scan and add SCALAR. May change `allow_simple_key`. + Token tok = scanPlain(); + addToken(tok); + } + + // Checkers. + + /** + * Returns true if the next thing on the reader is a directive, given that the leading '%' has + * already been checked. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id864824">3.2.3.4. Directives</a> + */ + private boolean checkDirective() { + // DIRECTIVE: ^ '%' ... + // The '%' indicator is already checked. + return reader.getColumn() == 0; + } + + /** + * Returns true if the next thing on the reader is a document-start ("---"). A document-start is + * always followed immediately by a new line. + */ + private boolean checkDocumentStart() { + // DOCUMENT-START: ^ '---' (' '|'\n') + if (reader.getColumn() == 0) { + return "---".equals(reader.prefix(3)) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3)); + } + return false; + } + + /** + * Returns true if the next thing on the reader is a document-end ("..."). A document-end is + * always followed immediately by a new line. + */ + private boolean checkDocumentEnd() { + // DOCUMENT-END: ^ '...' (' '|'\n') + if (reader.getColumn() == 0) { + return "...".equals(reader.prefix(3)) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3)); + } + return false; + } + + /** + * Returns true if the next thing on the reader is a block token. + */ + private boolean checkBlockEntry() { + // BLOCK-ENTRY: '-' (' '|'\n') + return Constant.NULL_BL_T_LINEBR.has(reader.peek(1)); + } + + /** + * Returns true if the next thing on the reader is a key token. + */ + private boolean checkKey() { + // KEY(flow context): '?' + if (this.flowLevel != 0) { + return true; + } else { + // KEY(block context): '?' (' '|'\n') + return Constant.NULL_BL_T_LINEBR.has(reader.peek(1)); + } + } + + /** + * Returns true if the next thing on the reader is a value token. + */ + private boolean checkValue() { + // VALUE(flow context): ':' + if (flowLevel != 0) { + return true; + } else { + // VALUE(block context): ':' (' '|'\n') + return Constant.NULL_BL_T_LINEBR.has(reader.peek(1)); + } + } + + /** + * Returns true if the next thing on the reader is a plain token. + */ + private boolean checkPlain() { /** - * Fetch a flow-style collection start, which is either a sequence or a - * mapping. The type is determined by the given boolean. - * - * A flow-style collection is in a format similar to JSON. Sequences are - * started by '[' and ended by ']'; mappings are started by '{' and ended by - * '}'. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - * - * @param isMappingStart + * <pre> + * A plain scalar may start with any non-space character except: + * '-', '?', ':', ',', '[', ']', '{', '}', + * '#', '&', '*', '!', '|', '>', '\'', '\"', + * '%', '@', '`'. + * + * It may also start with + * '-', '?', ':' + * if it is followed by a non-space character. + * + * Note that we limit the last rule to the block context (except the + * '-' character) because we want the flow context to be space + * independent. + * </pre> */ - private void fetchFlowCollectionStart(boolean isMappingStart) { - // '[' and '{' may start a simple key. - savePossibleSimpleKey(); - - // Increase the flow level. - this.flowLevel++; - - // Simple keys are allowed after '[' and '{'. - this.allowSimpleKey = true; - - // Add FLOW-SEQUENCE-START or FLOW-MAPPING-START. - Mark startMark = reader.getMark(); - reader.forward(1); - Mark endMark = reader.getMark(); - Token token; - if (isMappingStart) { - token = new FlowMappingStartToken(startMark, endMark); + int c = reader.peek(); + // If the next char is NOT one of the forbidden chars above or + // whitespace, then this is the start of a plain scalar. + return Constant.NULL_BL_T_LINEBR.hasNo(c, "-?:,[]{}#&*!|>'\"%@`") + || (Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(1)) + && (c == '-' || (this.flowLevel == 0 && "?:".indexOf(c) != -1))); + } + + // Scanners. + + /** + * <pre> + * We ignore spaces, line breaks and comments. + * If we find a line break in the block context, we set the flag + * `allow_simple_key` on. + * The byte order mark is stripped if it's the first character in the + * stream. We do not yet support BOM inside the stream as the + * specification requires. Any such mark will be considered as a part + * of the document. + * TODO: We need to make tab handling rules more sane. A good rule is + * Tabs cannot precede tokens + * BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END, + * KEY(block), VALUE(block), BLOCK-ENTRY + * So the checking code is + * if <TAB>: + * self.allow_simple_keys = False + * We also need to add the check for `allow_simple_keys == True` to + * `unwind_indent` before issuing BLOCK-END. + * Scanners for block, flow, and plain scalars need to be modified. + * </pre> + */ + private void scanToNextToken() { + // If there is a byte order mark (BOM) at the beginning of the stream, + // forward past it. + if (reader.getIndex() == 0 && reader.peek() == 0xFEFF) { + reader.forward(); + } + boolean found = false; + int inlineStartColumn = -1; + while (!found) { + Mark startMark = reader.getMark(); + int columnBeforeComment = reader.getColumn(); + boolean commentSeen = false; + int ff = 0; + // Peek ahead until we find the first non-space character, then + // move forward directly to that character. + while (reader.peek(ff) == ' ') { + ff++; + } + if (ff > 0) { + reader.forward(ff); + } + // If the character we have skipped forward to is a comment (#), + // then peek ahead until we find the next end of line. YAML + // comments are from a # to the next new-line. We then forward + // past the comment. + if (reader.peek() == '#') { + commentSeen = true; + CommentType type; + if (columnBeforeComment != 0 + && !(lastToken != null && lastToken.getTokenId() == Token.ID.BlockEntry)) { + type = CommentType.IN_LINE; + inlineStartColumn = reader.getColumn(); + } else if (inlineStartColumn == reader.getColumn()) { + type = CommentType.IN_LINE; } else { - token = new FlowSequenceStartToken(startMark, endMark); + inlineStartColumn = -1; + type = CommentType.BLOCK; + } + CommentToken token = scanComment(type); + if (parseComments) { + addToken(token); + } + } + // If we scanned a line break, then (depending on flow level), + // simple keys may be allowed. + String breaks = scanLineBreak(); + if (breaks.length() != 0) {// found a line-break + if (parseComments && !commentSeen) { + if (columnBeforeComment == 0) { + Mark endMark = reader.getMark(); + addToken(new CommentToken(CommentType.BLANK_LINE, breaks, startMark, endMark)); + } } - this.tokens.add(token); - } - - private void fetchFlowSequenceEnd() { - fetchFlowCollectionEnd(false); - } - - private void fetchFlowMappingEnd() { - fetchFlowCollectionEnd(true); - } - - /** - * Fetch a flow-style collection end, which is either a sequence or a - * mapping. The type is determined by the given boolean. - * - * A flow-style collection is in a format similar to JSON. Sequences are - * started by '[' and ended by ']'; mappings are started by '{' and ended by - * '}'. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - */ - private void fetchFlowCollectionEnd(boolean isMappingEnd) { - // Reset possible simple key on the current level. - removePossibleSimpleKey(); - - // Decrease the flow level. - this.flowLevel--; - - // No simple keys after ']' or '}'. - this.allowSimpleKey = false; - - // Add FLOW-SEQUENCE-END or FLOW-MAPPING-END. - Mark startMark = reader.getMark(); + if (this.flowLevel == 0) { + // Simple keys are allowed at flow-level 0 after a line + // break + this.allowSimpleKey = true; + } + } else { + found = true; + } + } + } + + private CommentToken scanComment(CommentType type) { + // See the specification for details. + Mark startMark = reader.getMark(); + reader.forward(); + int length = 0; + while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(length))) { + length++; + } + String value = reader.prefixForward(length); + Mark endMark = reader.getMark(); + return new CommentToken(type, value, startMark, endMark); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private List<Token> scanDirective() { + // See the specification for details. + Mark startMark = reader.getMark(); + Mark endMark; + reader.forward(); + String name = scanDirectiveName(startMark); + List<?> value = null; + if ("YAML".equals(name)) { + value = scanYamlDirectiveValue(startMark); + endMark = reader.getMark(); + } else if ("TAG".equals(name)) { + value = scanTagDirectiveValue(startMark); + endMark = reader.getMark(); + } else { + endMark = reader.getMark(); + int ff = 0; + while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) { + ff++; + } + if (ff > 0) { + reader.forward(ff); + } + } + CommentToken commentToken = scanDirectiveIgnoredLine(startMark); + DirectiveToken token = new DirectiveToken(name, value, startMark, endMark); + return makeTokenList(token, commentToken); + } + + /** + * Scan a directive name. Directive names are a series of non-space characters. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id895217">7.1. Directives</a> + */ + private String scanDirectiveName(Mark startMark) { + // See the specification for details. + int length = 0; + // A Directive-name is a sequence of alphanumeric characters + // (a-z,A-Z,0-9). We scan until we find something that isn't. + // FIXME this disagrees with the specification. + int c = reader.peek(length); + while (Constant.ALPHA.has(c)) { + length++; + c = reader.peek(length); + } + // If the name would be empty, an error occurs. + if (length == 0) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected alphabetic or numeric character, but found " + s + "(" + c + ")", + reader.getMark()); + } + String value = reader.prefixForward(length); + c = reader.peek(); + if (Constant.NULL_BL_LINEBR.hasNo(c)) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected alphabetic or numeric character, but found " + s + "(" + c + ")", + reader.getMark()); + } + return value; + } + + private List<Integer> scanYamlDirectiveValue(Mark startMark) { + // See the specification for details. + while (reader.peek() == ' ') { + reader.forward(); + } + Integer major = scanYamlDirectiveNumber(startMark); + int c = reader.peek(); + if (c != '.') { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected a digit or '.', but found " + s + "(" + c + ")", reader.getMark()); + } + reader.forward(); + Integer minor = scanYamlDirectiveNumber(startMark); + c = reader.peek(); + if (Constant.NULL_BL_LINEBR.hasNo(c)) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected a digit or ' ', but found " + s + "(" + c + ")", reader.getMark()); + } + List<Integer> result = new ArrayList<Integer>(2); + result.add(major); + result.add(minor); + return result; + } + + /** + * Read a %YAML directive number: this is either the major or the minor part. Stop reading at a + * non-digit character (usually either '.' or '\n'). + * + * @see <a href="http://www.yaml.org/spec/1.1/#id895631">7.1.1. โYAMLโ Directive</a> + * @see <a href="http://www.yaml.org/spec/1.1/#ns-dec-digit"></a> + */ + private Integer scanYamlDirectiveNumber(Mark startMark) { + // See the specification for details. + int c = reader.peek(); + if (!Character.isDigit(c)) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected a digit, but found " + s + "(" + (c) + ")", reader.getMark()); + } + int length = 0; + while (Character.isDigit(reader.peek(length))) { + length++; + } + Integer value = Integer.parseInt(reader.prefixForward(length)); + return value; + } + + /** + * <p> + * Read a %TAG directive value: + * + * <pre> + * s-ignored-space+ c-tag-handle s-ignored-space+ ns-tag-prefix s-l-comments + * </pre> + * + * </p> + * + * @see <a href="http://www.yaml.org/spec/1.1/#id896044">7.1.2. โTAGโ Directive</a> + */ + private List<String> scanTagDirectiveValue(Mark startMark) { + // See the specification for details. + while (reader.peek() == ' ') { + reader.forward(); + } + String handle = scanTagDirectiveHandle(startMark); + while (reader.peek() == ' ') { + reader.forward(); + } + String prefix = scanTagDirectivePrefix(startMark); + List<String> result = new ArrayList<String>(2); + result.add(handle); + result.add(prefix); + return result; + } + + /** + * Scan a %TAG directive's handle. This is YAML's c-tag-handle. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id896876">7.1.2.2. Tag Handles</a> + * @param startMark - beginning of the handle + * @return scanned handle + */ + private String scanTagDirectiveHandle(Mark startMark) { + // See the specification for details. + String value = scanTagHandle("directive", startMark); + int c = reader.peek(); + if (c != ' ') { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected ' ', but found " + s + "(" + c + ")", reader.getMark()); + } + return value; + } + + /** + * Scan a %TAG directive's prefix. This is YAML's ns-tag-prefix. + * + * @see <a href="http://www.yaml.org/spec/1.1/#ns-tag-prefix"></a> + */ + private String scanTagDirectivePrefix(Mark startMark) { + // See the specification for details. + String value = scanTagUri("directive", startMark); + int c = reader.peek(); + if (Constant.NULL_BL_LINEBR.hasNo(c)) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected ' ', but found " + s + "(" + c + ")", reader.getMark()); + } + return value; + } + + private CommentToken scanDirectiveIgnoredLine(Mark startMark) { + // See the specification for details. + while (reader.peek() == ' ') { + reader.forward(); + } + CommentToken commentToken = null; + if (reader.peek() == '#') { + CommentToken comment = scanComment(CommentType.IN_LINE); + if (parseComments) { + commentToken = comment; + } + } + int c = reader.peek(); + String lineBreak = scanLineBreak(); + if (lineBreak.length() == 0 && c != '\0') { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a directive", startMark, + "expected a comment or a line break, but found " + s + "(" + c + ")", reader.getMark()); + } + return commentToken; + } + + /** + * <pre> + * The YAML 1.1 specification does not restrict characters for anchors and + * aliases. This may lead to problems. + * see https://bitbucket.org/snakeyaml/snakeyaml/issues/485/alias-names-are-too-permissive-compared-to + * This implementation tries to follow https://github.com/yaml/yaml-spec/blob/master/rfc/RFC-0003.md + * </pre> + */ + private Token scanAnchor(boolean isAnchor) { + Mark startMark = reader.getMark(); + int indicator = reader.peek(); + String name = indicator == '*' ? "alias" : "anchor"; + reader.forward(); + int length = 0; + int c = reader.peek(length); + while (Constant.NULL_BL_T_LINEBR.hasNo(c, ":,[]{}/.*&")) { + length++; + c = reader.peek(length); + } + if (length == 0) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning an " + name, startMark, + "unexpected character found " + s + "(" + c + ")", reader.getMark()); + } + String value = reader.prefixForward(length); + c = reader.peek(); + if (Constant.NULL_BL_T_LINEBR.hasNo(c, "?:,]}%@`")) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning an " + name, startMark, + "unexpected character found " + s + "(" + c + ")", reader.getMark()); + } + Mark endMark = reader.getMark(); + Token tok; + if (isAnchor) { + tok = new AnchorToken(value, startMark, endMark); + } else { + tok = new AliasToken(value, startMark, endMark); + } + return tok; + } + + /** + * <p> + * Scan a Tag property. A Tag property may be specified in one of three ways: c-verbatim-tag, + * c-ns-shorthand-tag, or c-ns-non-specific-tag + * </p> + * + * <p> + * c-verbatim-tag takes the form !<ns-uri-char+> and must be delivered verbatim (as-is) to + * the application. In particular, verbatim tags are not subject to tag resolution. + * </p> + * + * <p> + * c-ns-shorthand-tag is a valid tag handle followed by a non-empty suffix. If the tag handle is a + * c-primary-tag-handle ('!') then the suffix must have all exclamation marks properly URI-escaped + * (%21); otherwise, the string will look like a named tag handle: !foo!bar would be interpreted + * as (handle="!foo!", suffix="bar"). + * </p> + * + * <p> + * c-ns-non-specific-tag is always a lone '!'; this is only useful for plain scalars, where its + * specification means that the scalar MUST be resolved to have type tag:yaml.org,2002:str. + * </p> + * + * TODO SnakeYaml incorrectly ignores c-ns-non-specific-tag right now. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id900262">8.2. Node Tags</a> + * + * TODO Note that this method does not enforce rules about local versus global tags! + */ + private Token scanTag() { + // See the specification for details. + Mark startMark = reader.getMark(); + // Determine the type of tag property based on the first character + // encountered + int c = reader.peek(1); + String handle = null; + String suffix = null; + // Verbatim tag! (c-verbatim-tag) + if (c == '<') { + // Skip the exclamation mark and >, then read the tag suffix (as + // a URI). + reader.forward(2); + suffix = scanTagUri("tag", startMark); + c = reader.peek(); + if (c != '>') { + // If there are any characters between the end of the tag-suffix + // URI and the closing >, then an error has occurred. + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a tag", startMark, + "expected '>', but found '" + s + "' (" + c + ")", reader.getMark()); + } + reader.forward(); + } else if (Constant.NULL_BL_T_LINEBR.has(c)) { + // A NUL, blank, tab, or line-break means that this was a + // c-ns-non-specific tag. + suffix = "!"; + reader.forward(); + } else { + // Any other character implies c-ns-shorthand-tag type. + + // Look ahead in the stream to determine whether this tag property + // is of the form !foo or !foo!bar. + int length = 1; + boolean useHandle = false; + while (Constant.NULL_BL_LINEBR.hasNo(c)) { + if (c == '!') { + useHandle = true; + break; + } + length++; + c = reader.peek(length); + } + // If we need to use a handle, scan it in; otherwise, the handle is + // presumed to be '!'. + if (useHandle) { + handle = scanTagHandle("tag", startMark); + } else { + handle = "!"; reader.forward(); - Mark endMark = reader.getMark(); - Token token; - if (isMappingEnd) { - token = new FlowMappingEndToken(startMark, endMark); + } + suffix = scanTagUri("tag", startMark); + } + c = reader.peek(); + // Check that the next character is allowed to follow a tag-property; + // if it is not, raise the error. + if (Constant.NULL_BL_LINEBR.hasNo(c)) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a tag", startMark, + "expected ' ', but found '" + s + "' (" + (c) + ")", reader.getMark()); + } + TagTuple value = new TagTuple(handle, suffix); + Mark endMark = reader.getMark(); + return new TagToken(value, startMark, endMark); + } + + private List<Token> scanBlockScalar(char style) { + // See the specification for details. + boolean folded; + // Depending on the given style, we determine whether the scalar is + // folded ('>') or literal ('|') + folded = style == '>'; + StringBuilder chunks = new StringBuilder(); + Mark startMark = reader.getMark(); + // Scan the header. + reader.forward(); + Chomping chompi = scanBlockScalarIndicators(startMark); + int increment = chompi.getIncrement(); + CommentToken commentToken = scanBlockScalarIgnoredLine(startMark); + + // Determine the indentation level and go to the first non-empty line. + int minIndent = this.indent + 1; + if (minIndent < 1) { + minIndent = 1; + } + String breaks; + int maxIndent; + int indent; + Mark endMark; + if (increment == -1) { + Object[] brme = scanBlockScalarIndentation(); + breaks = (String) brme[0]; + maxIndent = ((Integer) brme[1]).intValue(); + endMark = (Mark) brme[2]; + indent = Math.max(minIndent, maxIndent); + } else { + indent = minIndent + increment - 1; + Object[] brme = scanBlockScalarBreaks(indent); + breaks = (String) brme[0]; + endMark = (Mark) brme[1]; + } + + String lineBreak = ""; + + // Scan the inner part of the block scalar. + while (this.reader.getColumn() == indent && reader.peek() != '\0') { + chunks.append(breaks); + boolean leadingNonSpace = " \t".indexOf(reader.peek()) == -1; + int length = 0; + while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(length))) { + length++; + } + chunks.append(reader.prefixForward(length)); + lineBreak = scanLineBreak(); + Object[] brme = scanBlockScalarBreaks(indent); + breaks = (String) brme[0]; + endMark = (Mark) brme[1]; + if (this.reader.getColumn() == indent && reader.peek() != '\0') { + + // Unfortunately, folding rules are ambiguous. + // + // This is the folding according to the specification: + if (folded && "\n".equals(lineBreak) && leadingNonSpace + && " \t".indexOf(reader.peek()) == -1) { + if (breaks.length() == 0) { + chunks.append(" "); + } } else { - token = new FlowSequenceEndToken(startMark, endMark); + chunks.append(lineBreak); + } + // Clark Evans's interpretation (also in the spec examples) not + // imported from PyYAML + } else { + break; + } + } + // Chomp the tail. + if (chompi.chompTailIsNotFalse()) { + chunks.append(lineBreak); + } + if (chompi.chompTailIsTrue()) { + chunks.append(breaks); + } + // We are done. + ScalarToken scalarToken = new ScalarToken(chunks.toString(), false, startMark, endMark, + DumperOptions.ScalarStyle.createStyle(style)); + return makeTokenList(commentToken, scalarToken); + } + + /** + * Scan a block scalar indicator. The block scalar indicator includes two optional components, + * which may appear in either order. + * + * A block indentation indicator is a non-zero digit describing the indentation level of the block + * scalar to follow. This indentation is an additional number of spaces relative to the current + * indentation level. + * + * A block chomping indicator is a + or -, selecting the chomping mode away from the default + * (clip) to either -(strip) or +(keep). + * + * @see <a href="http://www.yaml.org/spec/1.1/#id868988">5.3. Indicator Characters</a> + * @see <a href="http://www.yaml.org/spec/1.1/#id927035">9.2.2. Block Indentation Indicator</a> + * @see <a href="http://www.yaml.org/spec/1.1/#id927557">9.2.3. Block Chomping Indicator</a> + */ + private Chomping scanBlockScalarIndicators(Mark startMark) { + // See the specification for details. + Boolean chomping = null; + int increment = -1; + int c = reader.peek(); + if (c == '-' || c == '+') { + if (c == '+') { + chomping = Boolean.TRUE; + } else { + chomping = Boolean.FALSE; + } + reader.forward(); + c = reader.peek(); + if (Character.isDigit(c)) { + final String s = String.valueOf(Character.toChars(c)); + increment = Integer.parseInt(s); + if (increment == 0) { + throw new ScannerException("while scanning a block scalar", startMark, + "expected indentation indicator in the range 1-9, but found 0", reader.getMark()); } - this.tokens.add(token); - } - - /** - * Fetch an entry in the flow style. Flow-style entries occur either - * immediately after the start of a collection, or else after a comma. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - */ - private void fetchFlowEntry() { - // Simple keys are allowed after ','. - this.allowSimpleKey = true; - - // Reset possible simple key on the current level. - removePossibleSimpleKey(); - - // Add FLOW-ENTRY. - Mark startMark = reader.getMark(); reader.forward(); - Mark endMark = reader.getMark(); - Token token = new FlowEntryToken(startMark, endMark); - this.tokens.add(token); - } - - /** - * Fetch an entry in the block style. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - */ - private void fetchBlockEntry() { - // Block context needs additional checks. - if (this.flowLevel == 0) { - // Are we allowed to start a new entry? - if (!this.allowSimpleKey) { - throw new ScannerException(null, null, "sequence entries are not allowed here", - reader.getMark()); - } - - // We may need to add BLOCK-SEQUENCE-START. - if (addIndent(this.reader.getColumn())) { - Mark mark = reader.getMark(); - this.tokens.add(new BlockSequenceStartToken(mark, mark)); - } + } + } else if (Character.isDigit(c)) { + final String s = String.valueOf(Character.toChars(c)); + increment = Integer.parseInt(s); + if (increment == 0) { + throw new ScannerException("while scanning a block scalar", startMark, + "expected indentation indicator in the range 1-9, but found 0", reader.getMark()); + } + reader.forward(); + c = reader.peek(); + if (c == '-' || c == '+') { + if (c == '+') { + chomping = Boolean.TRUE; } else { - // It's an error for the block entry to occur in the flow - // context,but we let the parser detect this. + chomping = Boolean.FALSE; } - // Simple keys are allowed after '-'. - this.allowSimpleKey = true; - - // Reset possible simple key on the current level. - removePossibleSimpleKey(); - - // Add BLOCK-ENTRY. - Mark startMark = reader.getMark(); reader.forward(); - Mark endMark = reader.getMark(); - Token token = new BlockEntryToken(startMark, endMark); - this.tokens.add(token); - } - - /** - * Fetch a key in a block-style mapping. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - */ - private void fetchKey() { - // Block context needs additional checks. - if (this.flowLevel == 0) { - // Are we allowed to start a key (not necessary a simple)? - if (!this.allowSimpleKey) { - throw new ScannerException(null, null, "mapping keys are not allowed here", - reader.getMark()); - } - // We may need to add BLOCK-MAPPING-START. - if (addIndent(this.reader.getColumn())) { - Mark mark = reader.getMark(); - this.tokens.add(new BlockMappingStartToken(mark, mark)); - } - } - // Simple keys are allowed after '?' in the block context. - this.allowSimpleKey = this.flowLevel == 0; - - // Reset possible simple key on the current level. - removePossibleSimpleKey(); - - // Add KEY. - Mark startMark = reader.getMark(); + } + } + c = reader.peek(); + if (Constant.NULL_BL_LINEBR.hasNo(c)) { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a block scalar", startMark, + "expected chomping or indentation indicators, but found " + s + "(" + c + ")", + reader.getMark()); + } + return new Chomping(chomping, increment); + } + + /** + * Scan to the end of the line after a block scalar has been scanned; the only things that are + * permitted at this time are comments and spaces. + */ + private CommentToken scanBlockScalarIgnoredLine(Mark startMark) { + // See the specification for details. + + // Forward past any number of trailing spaces + while (reader.peek() == ' ') { + reader.forward(); + } + + // If a comment occurs, scan to just before the end of line. + CommentToken commentToken = null; + if (reader.peek() == '#') { + commentToken = scanComment(CommentType.IN_LINE); + } + // If the next character is not a null or line break, an error has + // occurred. + int c = reader.peek(); + String lineBreak = scanLineBreak(); + if (lineBreak.length() == 0 && c != '\0') { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a block scalar", startMark, + "expected a comment or a line break, but found " + s + "(" + c + ")", reader.getMark()); + } + return commentToken; + } + + /** + * Scans for the indentation of a block scalar implicitly. This mechanism is used only if the + * block did not explicitly state an indentation to be used. + * + * @see <a href="http://www.yaml.org/spec/1.1/#id927035">9.2.2. Block Indentation Indicator</a> + */ + private Object[] scanBlockScalarIndentation() { + // See the specification for details. + StringBuilder chunks = new StringBuilder(); + int maxIndent = 0; + Mark endMark = reader.getMark(); + // Look ahead some number of lines until the first non-blank character + // occurs; the determined indentation will be the maximum number of + // leading spaces on any of these lines. + while (Constant.LINEBR.has(reader.peek(), " \r")) { + if (reader.peek() != ' ') { + // If the character isn't a space, it must be some kind of + // line-break; scan the line break and track it. + chunks.append(scanLineBreak()); + endMark = reader.getMark(); + } else { + // If the character is a space, move forward to the next + // character; if we surpass our previous maximum for indent + // level, update that too. reader.forward(); - Mark endMark = reader.getMark(); - Token token = new KeyToken(startMark, endMark); - this.tokens.add(token); - } - - /** - * Fetch a value in a block-style mapping. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - */ - private void fetchValue() { - // Do we determine a simple key? - SimpleKey key = this.possibleSimpleKeys.remove(this.flowLevel); - if (key != null) { - // Add KEY. - this.tokens.add(key.getTokenNumber() - this.tokensTaken, new KeyToken(key.getMark(), - key.getMark())); - - // If this key starts a new block mapping, we need to add - // BLOCK-MAPPING-START. - if (this.flowLevel == 0) { - if (addIndent(key.getColumn())) { - this.tokens.add(key.getTokenNumber() - this.tokensTaken, - new BlockMappingStartToken(key.getMark(), key.getMark())); - } - } - // There cannot be two simple keys one after another. - this.allowSimpleKey = false; - - } else { - // It must be a part of a complex key. - // Block context needs additional checks. Do we really need them? - // They will be caught by the parser anyway. - if (this.flowLevel == 0) { - - // We are allowed to start a complex value if and only if we can - // start a simple key. - if (!this.allowSimpleKey) { - throw new ScannerException(null, null, "mapping values are not allowed here", - reader.getMark()); - } - } - - // If this value starts a new block mapping, we need to add - // BLOCK-MAPPING-START. It will be detected as an error later by - // the parser. - if (flowLevel == 0) { - if (addIndent(reader.getColumn())) { - Mark mark = reader.getMark(); - this.tokens.add(new BlockMappingStartToken(mark, mark)); - } - } - - // Simple keys are allowed after ':' in the block context. - allowSimpleKey = flowLevel == 0; - - // Reset possible simple key on the current level. - removePossibleSimpleKey(); - } - // Add VALUE. - Mark startMark = reader.getMark(); - reader.forward(); - Mark endMark = reader.getMark(); - Token token = new ValueToken(startMark, endMark); - this.tokens.add(token); - } - - /** - * Fetch an alias, which is a reference to an anchor. Aliases take the - * format: - * - * <pre> - * *(anchor name) - * </pre> - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863390"></a> - */ - private void fetchAlias() { - // ALIAS could be a simple key. - savePossibleSimpleKey(); - - // No simple keys after ALIAS. - this.allowSimpleKey = false; - - // Scan and add ALIAS. - Token tok = scanAnchor(false); - this.tokens.add(tok); - } - - /** - * Fetch an anchor. Anchors take the form: - * - * <pre> - * &(anchor name) - * </pre> - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863390"></a> - */ - private void fetchAnchor() { - // ANCHOR could start a simple key. - savePossibleSimpleKey(); - - // No simple keys after ANCHOR. - this.allowSimpleKey = false; - - // Scan and add ANCHOR. - Token tok = scanAnchor(true); - this.tokens.add(tok); - } - - /** - * Fetch a tag. Tags take a complex form. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id861700"></a> - */ - private void fetchTag() { - // TAG could start a simple key. - savePossibleSimpleKey(); - - // No simple keys after TAG. - this.allowSimpleKey = false; - - // Scan and add TAG. - Token tok = scanTag(); - this.tokens.add(tok); - } - - /** - * Fetch a literal scalar, denoted with a vertical-bar. This is the type - * best used for source code and other content, such as binary data, which - * must be included verbatim. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - */ - private void fetchLiteral() { - fetchBlockScalar('|'); - } - - /** - * Fetch a folded scalar, denoted with a greater-than sign. This is the type - * best used for long content, such as the text of a chapter or description. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - */ - private void fetchFolded() { - fetchBlockScalar('>'); - } - - /** - * Fetch a block scalar (literal or folded). - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - * - * @param style - */ - private void fetchBlockScalar(char style) { - // A simple key may follow a block scalar. - this.allowSimpleKey = true; - - // Reset possible simple key on the current level. - removePossibleSimpleKey(); - - // Scan and add SCALAR. - Token tok = scanBlockScalar(style); - this.tokens.add(tok); - } - - /** - * Fetch a single-quoted (') scalar. - */ - private void fetchSingle() { - fetchFlowScalar('\''); - } - - /** - * Fetch a double-quoted (") scalar. - */ - private void fetchDouble() { - fetchFlowScalar('"'); - } - - /** - * Fetch a flow scalar (single- or double-quoted). - * - * @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a> - * - * @param style - */ - private void fetchFlowScalar(char style) { - // A flow scalar could be a simple key. - savePossibleSimpleKey(); - - // No simple keys after flow scalars. - this.allowSimpleKey = false; - - // Scan and add SCALAR. - Token tok = scanFlowScalar(style); - this.tokens.add(tok); - } - - /** - * Fetch a plain scalar. - */ - private void fetchPlain() { - // A plain scalar could be a simple key. - savePossibleSimpleKey(); - - // No simple keys after plain scalars. But note that `scan_plain` will - // change this flag if the scan is finished at the beginning of the - // line. - this.allowSimpleKey = false; - - // Scan and add SCALAR. May change `allow_simple_key`. - Token tok = scanPlain(); - this.tokens.add(tok); - } - - // Checkers. - /** - * Returns true if the next thing on the reader is a directive, given that - * the leading '%' has already been checked. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id864824"></a> - */ - private boolean checkDirective() { - // DIRECTIVE: ^ '%' ... - // The '%' indicator is already checked. - return reader.getColumn() == 0; - } - - /** - * Returns true if the next thing on the reader is a document-start ("---"). - * A document-start is always followed immediately by a new line. - */ - private boolean checkDocumentStart() { - // DOCUMENT-START: ^ '---' (' '|'\n') - if (reader.getColumn() == 0) { - if ("---".equals(reader.prefix(3)) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { - return true; - } - } - return false; - } - - /** - * Returns true if the next thing on the reader is a document-end ("..."). A - * document-end is always followed immediately by a new line. - */ - private boolean checkDocumentEnd() { - // DOCUMENT-END: ^ '...' (' '|'\n') - if (reader.getColumn() == 0) { - if ("...".equals(reader.prefix(3)) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { - return true; - } - } - return false; - } - - /** - * Returns true if the next thing on the reader is a block token. - */ - private boolean checkBlockEntry() { - // BLOCK-ENTRY: '-' (' '|'\n') - return Constant.NULL_BL_T_LINEBR.has(reader.peek(1)); - } - - /** - * Returns true if the next thing on the reader is a key token. - */ - private boolean checkKey() { - // KEY(flow context): '?' - if (this.flowLevel != 0) { - return true; - } else { - // KEY(block context): '?' (' '|'\n') - return Constant.NULL_BL_T_LINEBR.has(reader.peek(1)); - } - } - - /** - * Returns true if the next thing on the reader is a value token. - */ - private boolean checkValue() { - // VALUE(flow context): ':' - if (flowLevel != 0) { - return true; - } else { - // VALUE(block context): ':' (' '|'\n') - return Constant.NULL_BL_T_LINEBR.has(reader.peek(1)); - } - } - - /** - * Returns true if the next thing on the reader is a plain token. - */ - private boolean checkPlain() { - /** - * <pre> - * A plain scalar may start with any non-space character except: - * '-', '?', ':', ',', '[', ']', '{', '}', - * '#', '&', '*', '!', '|', '>', '\'', '\"', - * '%', '@', '`'. - * - * It may also start with - * '-', '?', ':' - * if it is followed by a non-space character. - * - * Note that we limit the last rule to the block context (except the - * '-' character) because we want the flow context to be space - * independent. - * </pre> - */ - char ch = reader.peek(); - // If the next char is NOT one of the forbidden chars above or - // whitespace, then this is the start of a plain scalar. - return Constant.NULL_BL_T_LINEBR.hasNo(ch, "-?:,[]{}#&*!|>\'\"%@`") - || (Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(1)) && (ch == '-' || (this.flowLevel == 0 && "?:" - .indexOf(ch) != -1))); - } - - // Scanners. - - /** - * <pre> - * We ignore spaces, line breaks and comments. - * If we find a line break in the block context, we set the flag - * `allow_simple_key` on. - * The byte order mark is stripped if it's the first character in the - * stream. We do not yet support BOM inside the stream as the - * specification requires. Any such mark will be considered as a part - * of the document. - * TODO: We need to make tab handling rules more sane. A good rule is - * Tabs cannot precede tokens - * BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END, - * KEY(block), VALUE(block), BLOCK-ENTRY - * So the checking code is - * if <TAB>: - * self.allow_simple_keys = False - * We also need to add the check for `allow_simple_keys == True` to - * `unwind_indent` before issuing BLOCK-END. - * Scanners for block, flow, and plain scalars need to be modified. - * </pre> - */ - private void scanToNextToken() { - // If there is a byte order mark (BOM) at the beginning of the stream, - // forward past it. - if (reader.getIndex() == 0 && reader.peek() == '\uFEFF') { - reader.forward(); - } - boolean found = false; - while (!found) { - int ff = 0; - // Peek ahead until we find the first non-space character, then - // move forward directly to that character. - while (reader.peek(ff) == ' ') { - ff++; - } - if (ff > 0) { - reader.forward(ff); - } - // If the character we have skipped forward to is a comment (#), - // then peek ahead until we find the next end of line. YAML - // comments are from a # to the next new-line. We then forward - // past the comment. - if (reader.peek() == '#') { - ff = 0; - while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) { - ff++; - } - if (ff > 0) { - reader.forward(ff); - } - } - // If we scanned a line break, then (depending on flow level), - // simple keys may be allowed. - if (scanLineBreak().length() != 0) {// found a line-break - if (this.flowLevel == 0) { - // Simple keys are allowed at flow-level 0 after a line - // break - this.allowSimpleKey = true; - } - } else { - found = true; - } - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private Token scanDirective() { - // See the specification for details. - Mark startMark = reader.getMark(); - Mark endMark; + if (this.reader.getColumn() > maxIndent) { + maxIndent = reader.getColumn(); + } + } + } + // Pass several results back together. + return new Object[] {chunks.toString(), maxIndent, endMark}; + } + + private Object[] scanBlockScalarBreaks(int indent) { + // See the specification for details. + StringBuilder chunks = new StringBuilder(); + Mark endMark = reader.getMark(); + int col = this.reader.getColumn(); + // Scan for up to the expected indentation-level of spaces, then move + // forward past that amount. + while (col < indent && reader.peek() == ' ') { + reader.forward(); + col++; + } + + // Consume one or more line breaks followed by any amount of spaces, + // until we find something that isn't a line-break. + String lineBreak = null; + while ((lineBreak = scanLineBreak()).length() != 0) { + chunks.append(lineBreak); + endMark = reader.getMark(); + // Scan past up to (indent) spaces on the next line, then forward + // past them. + col = this.reader.getColumn(); + while (col < indent && reader.peek() == ' ') { reader.forward(); - String name = scanDirectiveName(startMark); - List<?> value = null; - if ("YAML".equals(name)) { - value = scanYamlDirectiveValue(startMark); - endMark = reader.getMark(); - } else if ("TAG".equals(name)) { - value = scanTagDirectiveValue(startMark); - endMark = reader.getMark(); - } else { - endMark = reader.getMark(); - int ff = 0; - while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) { - ff++; - } - if (ff > 0) { - reader.forward(ff); - } - } - scanDirectiveIgnoredLine(startMark); - return new DirectiveToken(name, value, startMark, endMark); - } - - /** - * Scan a directive name. Directive names are a series of non-space - * characters. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id895217"></a> - */ - private String scanDirectiveName(Mark startMark) { - // See the specification for details. - int length = 0; - // A Directive-name is a sequence of alphanumeric characters - // (a-z,A-Z,0-9). We scan until we find something that isn't. - // FIXME this disagrees with the specification. - char ch = reader.peek(length); - while (Constant.ALPHA.has(ch)) { - length++; - ch = reader.peek(length); - } - // If the name would be empty, an error occurs. - if (length == 0) { - throw new ScannerException("while scanning a directive", startMark, - "expected alphabetic or numeric character, but found " + ch + "(" + ((int) ch) - + ")", reader.getMark()); - } - String value = reader.prefixForward(length); - ch = reader.peek(); - if (Constant.NULL_BL_LINEBR.hasNo(ch)) { - throw new ScannerException("while scanning a directive", startMark, - "expected alphabetic or numeric character, but found " + ch + "(" + ((int) ch) - + ")", reader.getMark()); - } - return value; - } - - private List<Integer> scanYamlDirectiveValue(Mark startMark) { - // See the specification for details. - while (reader.peek() == ' ') { - reader.forward(); - } - Integer major = scanYamlDirectiveNumber(startMark); - if (reader.peek() != '.') { - throw new ScannerException("while scanning a directive", startMark, - "expected a digit or '.', but found " + reader.peek() + "(" - + ((int) reader.peek()) + ")", reader.getMark()); - } + col++; + } + } + // Return both the assembled intervening string and the end-mark. + return new Object[] {chunks.toString(), endMark}; + } + + /** + * Scan a flow-style scalar. Flow scalars are presented in one of two forms; first, a flow scalar + * may be a double-quoted string; second, a flow scalar may be a single-quoted string. + * + * @see <a href="https://yaml.org/spec/1.1/#id904158">9.1. Flow Scalar Styles</a> style/syntax + * + * <pre> + * See the specification for details. + * Note that we loose indentation rules for quoted scalars. Quoted + * scalars don't need to adhere indentation because " and ' clearly + * mark the beginning and the end of them. Therefore we are less + * restrictive then the specification requires. We only need to check + * that document separators are not included in scalars. + * </pre> + */ + private Token scanFlowScalar(char style) { + boolean _double; + // The style will be either single- or double-quoted; we determine this + // by the first character in the entry (supplied) + _double = style == '"'; + StringBuilder chunks = new StringBuilder(); + Mark startMark = reader.getMark(); + int quote = reader.peek(); + reader.forward(); + chunks.append(scanFlowScalarNonSpaces(_double, startMark)); + while (reader.peek() != quote) { + chunks.append(scanFlowScalarSpaces(startMark)); + chunks.append(scanFlowScalarNonSpaces(_double, startMark)); + } + reader.forward(); + Mark endMark = reader.getMark(); + return new ScalarToken(chunks.toString(), false, startMark, endMark, + DumperOptions.ScalarStyle.createStyle(style)); + } + + /** + * Scan some number of flow-scalar non-space characters. + */ + private String scanFlowScalarNonSpaces(boolean doubleQuoted, Mark startMark) { + // See the specification for details. + StringBuilder chunks = new StringBuilder(); + while (true) { + // Scan through any number of characters which are not: NUL, blank, + // tabs, line breaks, single-quotes, double-quotes, or backslashes. + int length = 0; + while (Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(length), "'\"\\")) { + length++; + } + if (length != 0) { + chunks.append(reader.prefixForward(length)); + } + // Depending on our quoting-type, the characters ', " and \ have + // differing meanings. + int c = reader.peek(); + if (!doubleQuoted && c == '\'' && reader.peek(1) == '\'') { + chunks.append("'"); + reader.forward(2); + } else if ((doubleQuoted && c == '\'') || (!doubleQuoted && "\"\\".indexOf(c) != -1)) { + chunks.appendCodePoint(c); reader.forward(); - Integer minor = scanYamlDirectiveNumber(startMark); - if (Constant.NULL_BL_LINEBR.hasNo(reader.peek())) { - throw new ScannerException("while scanning a directive", startMark, - "expected a digit or ' ', but found " + reader.peek() + "(" - + ((int) reader.peek()) + ")", reader.getMark()); - } - List<Integer> result = new ArrayList<Integer>(2); - result.add(major); - result.add(minor); - return result; - } - - /** - * Read a %YAML directive number: this is either the major or the minor - * part. Stop reading at a non-digit character (usually either '.' or '\n'). - * - * @see <a href="http://www.yaml.org/spec/1.1/#id895631"></a> - * @see <a href="http://www.yaml.org/spec/1.1/#ns-dec-digit"></a> - */ - private Integer scanYamlDirectiveNumber(Mark startMark) { - // See the specification for details. - char ch = reader.peek(); - if (!Character.isDigit(ch)) { - throw new ScannerException("while scanning a directive", startMark, - "expected a digit, but found " + ch + "(" + ((int) ch) + ")", reader.getMark()); - } - int length = 0; - while (Character.isDigit(reader.peek(length))) { - length++; - } - Integer value = Integer.parseInt(reader.prefixForward(length)); - return value; - } - - /** - * <p> - * Read a %TAG directive value: - * - * <pre> - * s-ignored-space+ c-tag-handle s-ignored-space+ ns-tag-prefix s-l-comments - * </pre> - * - * </p> - * - * @see <a href="http://www.yaml.org/spec/1.1/#id896044"></a> - */ - private List<String> scanTagDirectiveValue(Mark startMark) { - // See the specification for details. - while (reader.peek() == ' ') { - reader.forward(); - } - String handle = scanTagDirectiveHandle(startMark); - while (reader.peek() == ' ') { - reader.forward(); - } - String prefix = scanTagDirectivePrefix(startMark); - List<String> result = new ArrayList<String>(2); - result.add(handle); - result.add(prefix); - return result; - } - - /** - * Scan a %TAG directive's handle. This is YAML's c-tag-handle. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id896876"></a> - * @param startMark - * @return - */ - private String scanTagDirectiveHandle(Mark startMark) { - // See the specification for details. - String value = scanTagHandle("directive", startMark); - char ch = reader.peek(); - if (ch != ' ') { - throw new ScannerException("while scanning a directive", startMark, - "expected ' ', but found " + reader.peek() + "(" + ch + ")", reader.getMark()); - } - return value; - } - - /** - * Scan a %TAG directive's prefix. This is YAML's ns-tag-prefix. - * - * @see <a href="http://www.yaml.org/spec/1.1/#ns-tag-prefix"></a> - */ - private String scanTagDirectivePrefix(Mark startMark) { - // See the specification for details. - String value = scanTagUri("directive", startMark); - if (Constant.NULL_BL_LINEBR.hasNo(reader.peek())) { - throw new ScannerException("while scanning a directive", startMark, - "expected ' ', but found " + reader.peek() + "(" + ((int) reader.peek()) + ")", - reader.getMark()); - } - return value; - } - - private String scanDirectiveIgnoredLine(Mark startMark) { - // See the specification for details. - int ff = 0; - while (reader.peek(ff) == ' ') { - ff++; - } - if (ff > 0) { - reader.forward(ff); - } - if (reader.peek() == '#') { - ff = 0; - while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) { - ff++; - } - reader.forward(ff); - } - char ch = reader.peek(); - String lineBreak = scanLineBreak(); - if (lineBreak.length() == 0 && ch != '\0') { - throw new ScannerException("while scanning a directive", startMark, - "expected a comment or a line break, but found " + ch + "(" + ((int) ch) + ")", - reader.getMark()); - } - return lineBreak; - } - - /** - * <pre> - * The specification does not restrict characters for anchors and - * aliases. This may lead to problems, for instance, the document: - * [ *alias, value ] - * can be interpreted in two ways, as - * [ "value" ] - * and - * [ *alias , "value" ] - * Therefore we restrict aliases to numbers and ASCII letters. - * </pre> - */ - private Token scanAnchor(boolean isAnchor) { - Mark startMark = reader.getMark(); - char indicator = reader.peek(); - String name = indicator == '*' ? "alias" : "anchor"; + } else if (doubleQuoted && c == '\\') { reader.forward(); - int length = 0; - char ch = reader.peek(length); - while (Constant.ALPHA.has(ch)) { - length++; - ch = reader.peek(length); - } - if (length == 0) { - throw new ScannerException("while scanning an " + name, startMark, - "expected alphabetic or numeric character, but found " + ch, - reader.getMark()); - } - String value = reader.prefixForward(length); - ch = reader.peek(); - if (Constant.NULL_BL_T_LINEBR.hasNo(ch, "?:,]}%@`")) { - throw new ScannerException("while scanning an " + name, startMark, - "expected alphabetic or numeric character, but found " + ch + "(" - + ((int) reader.peek()) + ")", reader.getMark()); - } - Mark endMark = reader.getMark(); - Token tok; - if (isAnchor) { - tok = new AnchorToken(value, startMark, endMark); - } else { - tok = new AliasToken(value, startMark, endMark); - } - return tok; - } - - /** - * <p> - * Scan a Tag property. A Tag property may be specified in one of three - * ways: c-verbatim-tag, c-ns-shorthand-tag, or c-ns-non-specific-tag - * </p> - * - * <p> - * c-verbatim-tag takes the form !<ns-uri-char+> and must be delivered - * verbatim (as-is) to the application. In particular, verbatim tags are not - * subject to tag resolution. - * </p> - * - * <p> - * c-ns-shorthand-tag is a valid tag handle followed by a non-empty suffix. - * If the tag handle is a c-primary-tag-handle ('!') then the suffix must - * have all exclamation marks properly URI-escaped (%21); otherwise, the - * string will look like a named tag handle: !foo!bar would be interpreted - * as (handle="!foo!", suffix="bar"). - * </p> - * - * <p> - * c-ns-non-specific-tag is always a lone '!'; this is only useful for plain - * scalars, where its specification means that the scalar MUST be resolved - * to have type tag:yaml.org,2002:str. - * </p> - * - * TODO SnakeYaml incorrectly ignores c-ns-non-specific-tag right now. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id900262"></a> - * - * TODO Note that this method does not enforce rules about local versus - * global tags! - */ - private Token scanTag() { - // See the specification for details. - Mark startMark = reader.getMark(); - // Determine the type of tag property based on the first character - // encountered - char ch = reader.peek(1); - String handle = null; - String suffix = null; - // Verbatim tag! (c-verbatim-tag) - if (ch == '<') { - // Skip the exclamation mark and >, then read the tag suffix (as - // a URI). - reader.forward(2); - suffix = scanTagUri("tag", startMark); - if (reader.peek() != '>') { - // If there are any characters between the end of the tag-suffix - // URI and the closing >, then an error has occurred. - throw new ScannerException("while scanning a tag", startMark, - "expected '>', but found '" + reader.peek() + "' (" + ((int) reader.peek()) - + ")", reader.getMark()); - } - reader.forward(); - } else if (Constant.NULL_BL_T_LINEBR.has(ch)) { - // A NUL, blank, tab, or line-break means that this was a - // c-ns-non-specific tag. - suffix = "!"; - reader.forward(); - } else { - // Any other character implies c-ns-shorthand-tag type. - - // Look ahead in the stream to determine whether this tag property - // is of the form !foo or !foo!bar. - int length = 1; - boolean useHandle = false; - while (Constant.NULL_BL_LINEBR.hasNo(ch)) { - if (ch == '!') { - useHandle = true; - break; - } - length++; - ch = reader.peek(length); - } - handle = "!"; - // If we need to use a handle, scan it in; otherwise, the handle is - // presumed to be '!'. - if (useHandle) { - handle = scanTagHandle("tag", startMark); - } else { - handle = "!"; - reader.forward(); - } - suffix = scanTagUri("tag", startMark); - } - ch = reader.peek(); - // Check that the next character is allowed to follow a tag-property; - // if it is not, raise the error. - if (Constant.NULL_BL_LINEBR.hasNo(ch)) { - throw new ScannerException("while scanning a tag", startMark, - "expected ' ', but found '" + ch + "' (" + ((int) ch) + ")", reader.getMark()); - } - TagTuple value = new TagTuple(handle, suffix); - Mark endMark = reader.getMark(); - return new TagToken(value, startMark, endMark); - } - - private Token scanBlockScalar(char style) { - // See the specification for details. - boolean folded; - // Depending on the given style, we determine whether the scalar is - // folded ('>') or literal ('|') - if (style == '>') { - folded = true; + c = reader.peek(); + if (!Character.isSupplementaryCodePoint(c) + && ESCAPE_REPLACEMENTS.containsKey(Character.valueOf((char) c))) { + // The character is one of the single-replacement + // types; these are replaced with a literal character + // from the mapping. + chunks.append(ESCAPE_REPLACEMENTS.get(Character.valueOf((char) c))); + reader.forward(); + } else if (!Character.isSupplementaryCodePoint(c) + && ESCAPE_CODES.containsKey(Character.valueOf((char) c))) { + // The character is a multi-digit escape sequence, with + // length defined by the value in the ESCAPE_CODES map. + length = ESCAPE_CODES.get(Character.valueOf((char) c)).intValue(); + reader.forward(); + String hex = reader.prefix(length); + if (NOT_HEXA.matcher(hex).find()) { + throw new ScannerException("while scanning a double-quoted scalar", startMark, + "expected escape sequence of " + length + " hexadecimal numbers, but found: " + hex, + reader.getMark()); + } + int decimal = Integer.parseInt(hex, 16); + String unicode = new String(Character.toChars(decimal)); + chunks.append(unicode); + reader.forward(length); + } else if (scanLineBreak().length() != 0) { + chunks.append(scanFlowScalarBreaks(startMark)); } else { - folded = false; + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a double-quoted scalar", startMark, + "found unknown escape character " + s + "(" + c + ")", reader.getMark()); } - StringBuilder chunks = new StringBuilder(); - Mark startMark = reader.getMark(); - // Scan the header. + } else { + return chunks.toString(); + } + } + } + + private String scanFlowScalarSpaces(Mark startMark) { + // See the specification for details. + StringBuilder chunks = new StringBuilder(); + int length = 0; + // Scan through any number of whitespace (space, tab) characters, + // consuming them. + while (" \t".indexOf(reader.peek(length)) != -1) { + length++; + } + String whitespaces = reader.prefixForward(length); + int c = reader.peek(); + if (c == '\0') { + // A flow scalar cannot end with an end-of-stream + throw new ScannerException("while scanning a quoted scalar", startMark, + "found unexpected end of stream", reader.getMark()); + } + // If we encounter a line break, scan it into our assembled string... + String lineBreak = scanLineBreak(); + if (lineBreak.length() != 0) { + String breaks = scanFlowScalarBreaks(startMark); + if (!"\n".equals(lineBreak)) { + chunks.append(lineBreak); + } else if (breaks.length() == 0) { + chunks.append(" "); + } + chunks.append(breaks); + } else { + chunks.append(whitespaces); + } + return chunks.toString(); + } + + private String scanFlowScalarBreaks(Mark startMark) { + // See the specification for details. + StringBuilder chunks = new StringBuilder(); + while (true) { + // Instead of checking indentation, we check for document + // separators. + String prefix = reader.prefix(3); + if (("---".equals(prefix) || "...".equals(prefix)) + && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { + throw new ScannerException("while scanning a quoted scalar", startMark, + "found unexpected document separator", reader.getMark()); + } + // Scan past any number of spaces and tabs, ignoring them + while (" \t".indexOf(reader.peek()) != -1) { reader.forward(); - Chomping chompi = scanBlockScalarIndicators(startMark); - int increment = chompi.getIncrement(); - scanBlockScalarIgnoredLine(startMark); - - // Determine the indentation level and go to the first non-empty line. - int minIndent = this.indent + 1; - if (minIndent < 1) { - minIndent = 1; - } - String breaks = null; - int maxIndent = 0; - int indent = 0; - Mark endMark; - if (increment == -1) { - Object[] brme = scanBlockScalarIndentation(); - breaks = (String) brme[0]; - maxIndent = ((Integer) brme[1]).intValue(); - endMark = (Mark) brme[2]; - indent = Math.max(minIndent, maxIndent); + } + // If we stopped at a line break, add that; otherwise, return the + // assembled set of scalar breaks. + String lineBreak = scanLineBreak(); + if (lineBreak.length() != 0) { + chunks.append(lineBreak); + } else { + return chunks.toString(); + } + } + } + + /** + * Scan a plain scalar. + * + * <pre> + * See the specification for details. + * We add an additional restriction for the flow context: + * plain scalars in the flow context cannot contain ',', ':' and '?'. + * We also keep track of the `allow_simple_key` flag here. + * Indentation rules are loosed for the flow context. + * </pre> + */ + private Token scanPlain() { + StringBuilder chunks = new StringBuilder(); + Mark startMark = reader.getMark(); + Mark endMark = startMark; + int indent = this.indent + 1; + String spaces = ""; + while (true) { + int c; + int length = 0; + // A comment indicates the end of the scalar. + if (reader.peek() == '#') { + break; + } + while (true) { + c = reader.peek(length); + if (Constant.NULL_BL_T_LINEBR.has(c) + || (c == ':' && Constant.NULL_BL_T_LINEBR.has(reader.peek(length + 1), + flowLevel != 0 ? ",[]{}" : "")) + || (this.flowLevel != 0 && ",?[]{}".indexOf(c) != -1)) { + break; + } + length++; + } + if (length == 0) { + break; + } + this.allowSimpleKey = false; + chunks.append(spaces); + chunks.append(reader.prefixForward(length)); + endMark = reader.getMark(); + spaces = scanPlainSpaces(); + // System.out.printf("spaces[%s]\n", spaces); + if (spaces.length() == 0 || reader.peek() == '#' + || (this.flowLevel == 0 && this.reader.getColumn() < indent)) { + break; + } + } + return new ScalarToken(chunks.toString(), startMark, endMark, true); + } + + // Helper for scanPlainSpaces method when comments are enabled. + // The ensures that blank lines and comments following a multi-line plain token are not swallowed + // up + private boolean atEndOfPlain() { + // peak ahead to find end of whitespaces and the column at which it occurs + int wsLength = 0; + int wsColumn = this.reader.getColumn(); + { + int c; + while ((c = reader.peek(wsLength)) != '\0' && Constant.NULL_BL_T_LINEBR.has(c)) { + wsLength++; + if (!Constant.LINEBR.has(c) && (c != '\r' || reader.peek(wsLength + 1) != '\n') + && c != 0xFEFF) { + wsColumn++; } else { - indent = minIndent + increment - 1; - Object[] brme = scanBlockScalarBreaks(indent); - breaks = (String) brme[0]; - endMark = (Mark) brme[1]; - } - - String lineBreak = ""; - - // Scan the inner part of the block scalar. - while (this.reader.getColumn() == indent && reader.peek() != '\0') { - chunks.append(breaks); - boolean leadingNonSpace = " \t".indexOf(reader.peek()) == -1; - int length = 0; - while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(length))) { - length++; - } - chunks.append(reader.prefixForward(length)); - lineBreak = scanLineBreak(); - Object[] brme = scanBlockScalarBreaks(indent); - breaks = (String) brme[0]; - endMark = (Mark) brme[1]; - if (this.reader.getColumn() == indent && reader.peek() != '\0') { - - // Unfortunately, folding rules are ambiguous. - // - // This is the folding according to the specification: - if (folded && "\n".equals(lineBreak) && leadingNonSpace - && " \t".indexOf(reader.peek()) == -1) { - if (breaks.length() == 0) { - chunks.append(" "); - } - } else { - chunks.append(lineBreak); - } - // Clark Evans's interpretation (also in the spec examples) not - // imported from PyYAML - } else { - break; - } - } - // Chomp the tail. - if (chompi.chompTailIsNotFalse()) { - chunks.append(lineBreak); + wsColumn = 0; } - if (chompi.chompTailIsTrue()) { - chunks.append(breaks); - } - // We are done. - return new ScalarToken(chunks.toString(), false, startMark, endMark, style); + } } - /** - * Scan a block scalar indicator. The block scalar indicator includes two - * optional components, which may appear in either order. - * - * A block indentation indicator is a non-zero digit describing the - * indentation level of the block scalar to follow. This indentation is an - * additional number of spaces relative to the current indentation level. - * - * A block chomping indicator is a + or -, selecting the chomping mode away - * from the default (clip) to either -(strip) or +(keep). - * - * @see <a href="http://www.yaml.org/spec/1.1/#id868988"></a> - * @see <a href="http://www.yaml.org/spec/1.1/#id927035"></a> - * @see <a href="http://www.yaml.org/spec/1.1/#id927557"></a> - */ - private Chomping scanBlockScalarIndicators(Mark startMark) { - // See the specification for details. - Boolean chomping = null; - int increment = -1; - char ch = reader.peek(); - if (ch == '-' || ch == '+') { - if (ch == '+') { - chomping = Boolean.TRUE; - } else { - chomping = Boolean.FALSE; - } - reader.forward(); - ch = reader.peek(); - if (Character.isDigit(ch)) { - increment = Integer.parseInt(String.valueOf(ch)); - if (increment == 0) { - throw new ScannerException("while scanning a block scalar", startMark, - "expected indentation indicator in the range 1-9, but found 0", - reader.getMark()); - } - reader.forward(); - } - } else if (Character.isDigit(ch)) { - increment = Integer.parseInt(String.valueOf(ch)); - if (increment == 0) { - throw new ScannerException("while scanning a block scalar", startMark, - "expected indentation indicator in the range 1-9, but found 0", - reader.getMark()); - } - reader.forward(); - ch = reader.peek(); - if (ch == '-' || ch == '+') { - if (ch == '+') { - chomping = Boolean.TRUE; - } else { - chomping = Boolean.FALSE; - } - reader.forward(); - } - } - ch = reader.peek(); - if (Constant.NULL_BL_LINEBR.hasNo(ch)) { - throw new ScannerException("while scanning a block scalar", startMark, - "expected chomping or indentation indicators, but found " + ch, - reader.getMark()); - } - return new Chomping(chomping, increment); + // if we see, a comment or end of string or change decrease in indent, we are done + // Do not chomp end of lines and blanks, they will be handled by the main loop. + if (reader.peek(wsLength) == '#' || reader.peek(wsLength + 1) == '\0' + || this.flowLevel == 0 && wsColumn < this.indent) { + return true; } - /** - * Scan to the end of the line after a block scalar has been scanned; the - * only things that are permitted at this time are comments and spaces. - */ - private String scanBlockScalarIgnoredLine(Mark startMark) { - // See the specification for details. - int ff = 0; - // Forward past any number of trailing spaces - while (reader.peek(ff) == ' ') { - ff++; - } - if (ff > 0) { - reader.forward(ff); - } - // If a comment occurs, scan to just before the end of line. - if (reader.peek() == '#') { - ff = 0; - while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) { - ff++; - } - if (ff > 0) { - reader.forward(ff); - } - } - // If the next character is not a null or line break, an error has - // occurred. - char ch = reader.peek(); - String lineBreak = scanLineBreak(); - if (lineBreak.length() == 0 && ch != '\0') { - throw new ScannerException("while scanning a block scalar", startMark, - "expected a comment or a line break, but found " + ch, reader.getMark()); + // if we see, after the space, a key-value followed by a ':', we are done + // Do not chomp end of lines and blanks, they will be handled by the main loop. + if (this.flowLevel == 0) { + int c; + for (int extra = 1; (c = reader.peek(wsLength + extra)) != 0 + && !Constant.NULL_BL_T_LINEBR.has(c); extra++) { + if (c == ':' && Constant.NULL_BL_T_LINEBR.has(reader.peek(wsLength + extra + 1))) { + return true; } - return lineBreak; + } } - /** - * Scans for the indentation of a block scalar implicitly. This mechanism is - * used only if the block did not explicitly state an indentation to be - * used. - * - * @see <a href="http://www.yaml.org/spec/1.1/#id927035"></a> - */ - private Object[] scanBlockScalarIndentation() { - // See the specification for details. - StringBuilder chunks = new StringBuilder(); - int maxIndent = 0; - Mark endMark = reader.getMark(); - // Look ahead some number of lines until the first non-blank character - // occurs; the determined indentation will be the maximum number of - // leading spaces on any of these lines. - while (Constant.LINEBR.has(reader.peek(), " \r")) { - if (reader.peek() != ' ') { - // If the character isn't a space, it must be some kind of - // line-break; scan the line break and track it. - chunks.append(scanLineBreak()); - endMark = reader.getMark(); - } else { - // If the character is a space, move forward to the next - // character; if we surpass our previous maximum for indent - // level, update that too. - reader.forward(); - if (this.reader.getColumn() > maxIndent) { - maxIndent = reader.getColumn(); - } - } - } - // Pass several results back together. - return new Object[] { chunks.toString(), maxIndent, endMark }; - } - - private Object[] scanBlockScalarBreaks(int indent) { - // See the specification for details. - StringBuilder chunks = new StringBuilder(); - Mark endMark = reader.getMark(); - int ff = 0; - int col = this.reader.getColumn(); - // Scan for up to the expected indentation-level of spaces, then move - // forward past that amount. - while (col < indent && reader.peek(ff) == ' ') { - ff++; - col++; - } - if (ff > 0) { - reader.forward(ff); - } - // Consume one or more line breaks followed by any amount of spaces, - // until we find something that isn't a line-break. - String lineBreak = null; - while ((lineBreak = scanLineBreak()).length() != 0) { - chunks.append(lineBreak); - endMark = reader.getMark(); - // Scan past up to (indent) spaces on the next line, then forward - // past them. - ff = 0; - col = this.reader.getColumn(); - while (col < indent && reader.peek(ff) == ' ') { - ff++; - col++; - } - if (ff > 0) { - reader.forward(ff); - } - } - // Return both the assembled intervening string and the end-mark. - return new Object[] { chunks.toString(), endMark }; - } + // None of the above so safe to chomp the spaces. + return false; + } - /** - * Scan a flow-style scalar. Flow scalars are presented in one of two forms; - * first, a flow scalar may be a double-quoted string; second, a flow scalar - * may be a single-quoted string. - * - * @see <a href="http://www.yaml.org/spec/1.1/#flow"></a> style/syntax - * - * <pre> - * See the specification for details. - * Note that we loose indentation rules for quoted scalars. Quoted - * scalars don't need to adhere indentation because " and ' clearly - * mark the beginning and the end of them. Therefore we are less - * restrictive then the specification requires. We only need to check - * that document separators are not included in scalars. - * </pre> - */ - private Token scanFlowScalar(char style) { - boolean _double; - // The style will be either single- or double-quoted; we determine this - // by the first character in the entry (supplied) - if (style == '"') { - _double = true; - } else { - _double = false; - } - StringBuilder chunks = new StringBuilder(); - Mark startMark = reader.getMark(); - char quote = reader.peek(); - reader.forward(); - chunks.append(scanFlowScalarNonSpaces(_double, startMark)); - while (reader.peek() != quote) { - chunks.append(scanFlowScalarSpaces(startMark)); - chunks.append(scanFlowScalarNonSpaces(_double, startMark)); - } - reader.forward(); - Mark endMark = reader.getMark(); - return new ScalarToken(chunks.toString(), false, startMark, endMark, style); + /** + * See the specification for details. SnakeYAML and libyaml allow tabs inside plain scalar + */ + private String scanPlainSpaces() { + int length = 0; + while (reader.peek(length) == ' ' || reader.peek(length) == '\t') { + length++; } - - /** - * Scan some number of flow-scalar non-space characters. - */ - private String scanFlowScalarNonSpaces(boolean doubleQuoted, Mark startMark) { - // See the specification for details. - StringBuilder chunks = new StringBuilder(); - while (true) { - // Scan through any number of characters which are not: NUL, blank, - // tabs, line breaks, single-quotes, double-quotes, or backslashes. - int length = 0; - while (Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(length), "\'\"\\")) { - length++; - } - if (length != 0) { - chunks.append(reader.prefixForward(length)); - } - // Depending on our quoting-type, the characters ', " and \ have - // differing meanings. - char ch = reader.peek(); - if (!doubleQuoted && ch == '\'' && reader.peek(1) == '\'') { - chunks.append("'"); - reader.forward(2); - } else if ((doubleQuoted && ch == '\'') || (!doubleQuoted && "\"\\".indexOf(ch) != -1)) { - chunks.append(ch); - reader.forward(); - } else if (doubleQuoted && ch == '\\') { - reader.forward(); - ch = reader.peek(); - if (ESCAPE_REPLACEMENTS.containsKey(Character.valueOf(ch))) { - // The character is one of the single-replacement - // types; these are replaced with a literal character - // from the mapping. - chunks.append(ESCAPE_REPLACEMENTS.get(Character.valueOf(ch))); - reader.forward(); - } else if (ESCAPE_CODES.containsKey(Character.valueOf(ch))) { - // The character is a multi-digit escape sequence, with - // length defined by the value in the ESCAPE_CODES map. - length = ESCAPE_CODES.get(Character.valueOf(ch)).intValue(); - reader.forward(); - String hex = reader.prefix(length); - if (NOT_HEXA.matcher(hex).find()) { - throw new ScannerException("while scanning a double-quoted scalar", - startMark, "expected escape sequence of " + length - + " hexadecimal numbers, but found: " + hex, - reader.getMark()); - } - int decimal = Integer.parseInt(hex, 16); - String unicode = new String(Character.toChars(decimal)); - chunks.append(unicode); - reader.forward(length); - } else if (scanLineBreak().length() != 0) { - chunks.append(scanFlowScalarBreaks(startMark)); - } else { - throw new ScannerException("while scanning a double-quoted scalar", startMark, - "found unknown escape character " + ch + "(" + ((int) ch) + ")", - reader.getMark()); - } - } else { - return chunks.toString(); - } - } - } - - private String scanFlowScalarSpaces(Mark startMark) { - // See the specification for details. - StringBuilder chunks = new StringBuilder(); - int length = 0; - // Scan through any number of whitespace (space, tab) characters, - // consuming them. - while (" \t".indexOf(reader.peek(length)) != -1) { - length++; - } - String whitespaces = reader.prefixForward(length); - char ch = reader.peek(); - if (ch == '\0') { - // A flow scalar cannot end with an end-of-stream - throw new ScannerException("while scanning a quoted scalar", startMark, - "found unexpected end of stream", reader.getMark()); - } - // If we encounter a line break, scan it into our assembled string... - String lineBreak = scanLineBreak(); - if (lineBreak.length() != 0) { - String breaks = scanFlowScalarBreaks(startMark); - if (!"\n".equals(lineBreak)) { - chunks.append(lineBreak); - } else if (breaks.length() == 0) { - chunks.append(" "); - } - chunks.append(breaks); + String whitespaces = reader.prefixForward(length); + String lineBreak = scanLineBreak(); + if (lineBreak.length() != 0) { + this.allowSimpleKey = true; + String prefix = reader.prefix(3); + if ("---".equals(prefix) + || "...".equals(prefix) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { + return ""; + } + if (parseComments && atEndOfPlain()) { + return ""; + } + StringBuilder breaks = new StringBuilder(); + while (true) { + if (reader.peek() == ' ') { + reader.forward(); } else { - chunks.append(whitespaces); - } - return chunks.toString(); - } - - private String scanFlowScalarBreaks(Mark startMark) { - // See the specification for details. - StringBuilder chunks = new StringBuilder(); - while (true) { - // Instead of checking indentation, we check for document - // separators. - String prefix = reader.prefix(3); - if (("---".equals(prefix) || "...".equals(prefix)) - && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { - throw new ScannerException("while scanning a quoted scalar", startMark, - "found unexpected document separator", reader.getMark()); - } - // Scan past any number of spaces and tabs, ignoring them - while (" \t".indexOf(reader.peek()) != -1) { - reader.forward(); + String lb = scanLineBreak(); + if (lb.length() != 0) { + breaks.append(lb); + prefix = reader.prefix(3); + if ("---".equals(prefix) + || "...".equals(prefix) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { + return ""; } - // If we stopped at a line break, add that; otherwise, return the - // assembled set of scalar breaks. - String lineBreak = scanLineBreak(); - if (lineBreak.length() != 0) { - chunks.append(lineBreak); - } else { - return chunks.toString(); - } - } + } else { + break; + } + } + } + if (!"\n".equals(lineBreak)) { + return lineBreak + breaks; + } else if (breaks.length() == 0) { + return " "; + } + return breaks.toString(); + } + return whitespaces; + } + + /** + * <p> + * Scan a Tag handle. A Tag handle takes one of three forms: + * + * <pre> + * "!" (c-primary-tag-handle) + * "!!" (ns-secondary-tag-handle) + * "!(name)!" (c-named-tag-handle) + * </pre> + * + * Where (name) must be formatted as an ns-word-char. + * </p> + * + * @see <a href="http://www.yaml.org/spec/1.1/#c-tag-handle"></a> + * @see <a href="http://www.yaml.org/spec/1.1/#ns-word-char"></a> + * + * <pre> + * See the specification for details. + * For some strange reasons, the specification does not allow '_' in + * tag handles. I have allowed it anyway. + * </pre> + */ + private String scanTagHandle(String name, Mark startMark) { + int c = reader.peek(); + if (c != '!') { + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a " + name, startMark, + "expected '!', but found " + s + "(" + (c) + ")", reader.getMark()); + } + // Look for the next '!' in the stream, stopping if we hit a + // non-word-character. If the first character is a space, then the + // tag-handle is a c-primary-tag-handle ('!'). + int length = 1; + c = reader.peek(length); + if (c != ' ') { + // Scan through 0+ alphabetic characters. + // FIXME According to the specification, these should be + // ns-word-char only, which prohibits '_'. This might be a + // candidate for a configuration option. + while (Constant.ALPHA.has(c)) { + length++; + c = reader.peek(length); + } + // Found the next non-word-char. If this is not a space and not an + // '!', then this is an error, as the tag-handle was specified as: + // !(name) or similar; the trailing '!' is missing. + if (c != '!') { + reader.forward(length); + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a " + name, startMark, + "expected '!', but found " + s + "(" + (c) + ")", reader.getMark()); + } + length++; + } + String value = reader.prefixForward(length); + return value; + } + + /** + * <p> + * Scan a Tag URI. This scanning is valid for both local and global tag directives, because both + * appear to be valid URIs as far as scanning is concerned. The difference may be distinguished + * later, in parsing. This method will scan for ns-uri-char*, which covers both cases. + * </p> + * + * <p> + * This method performs no verification that the scanned URI conforms to any particular kind of + * URI specification. + * </p> + * + * @see <a href="http://www.yaml.org/spec/1.1/#ns-uri-char"></a> + */ + private String scanTagUri(String name, Mark startMark) { + // See the specification for details. + // Note: we do not check if URI is well-formed. + StringBuilder chunks = new StringBuilder(); + // Scan through accepted URI characters, which includes the standard + // URI characters, plus the start-escape character ('%'). When we get + // to a start-escape, scan the escaped sequence, then return. + int length = 0; + int c = reader.peek(length); + while (Constant.URI_CHARS.has(c)) { + if (c == '%') { + chunks.append(reader.prefixForward(length)); + length = 0; + chunks.append(scanUriEscapes(name, startMark)); + } else { + length++; + } + c = reader.peek(length); + } + // Consume the last "chunk", which would not otherwise be consumed by + // the loop above. + if (length != 0) { + chunks.append(reader.prefixForward(length)); + } + if (chunks.length() == 0) { + // If no URI was found, an error has occurred. + final String s = String.valueOf(Character.toChars(c)); + throw new ScannerException("while scanning a " + name, startMark, + "expected URI, but found " + s + "(" + (c) + ")", reader.getMark()); + } + return chunks.toString(); + } + + /** + * <p> + * Scan a sequence of %-escaped URI escape codes and convert them into a String representing the + * unescaped values. + * </p> + * + * FIXME This method fails for more than 256 bytes' worth of URI-encoded characters in a row. Is + * this possible? Is this a use-case? + * + * @see <a href="http://www.ietf.org/rfc/rfc2396.txt">section 2.4, Escaped Encoding</a> + */ + private String scanUriEscapes(String name, Mark startMark) { + // First, look ahead to see how many URI-escaped characters we should + // expect, so we can use the correct buffer size. + int length = 1; + while (reader.peek(length * 3) == '%') { + length++; + } + // See the specification for details. + // URIs containing 16 and 32 bit Unicode characters are + // encoded in UTF-8, and then each octet is written as a + // separate character. + Mark beginningMark = reader.getMark(); + ByteBuffer buff = ByteBuffer.allocate(length); + while (reader.peek() == '%') { + reader.forward(); + try { + byte code = (byte) Integer.parseInt(reader.prefix(2), 16); + buff.put(code); + } catch (NumberFormatException nfe) { + int c1 = reader.peek(); + final String s1 = String.valueOf(Character.toChars(c1)); + int c2 = reader.peek(1); + final String s2 = String.valueOf(Character.toChars(c2)); + throw new ScannerException("while scanning a " + name, startMark, + "expected URI escape sequence of 2 hexadecimal numbers, but found " + s1 + "(" + c1 + + ") and " + s2 + "(" + c2 + ")", + reader.getMark()); + } + reader.forward(2); + } + buff.flip(); + try { + return UriEncoder.decode(buff); + } catch (CharacterCodingException e) { + throw new ScannerException("while scanning a " + name, startMark, + "expected URI in UTF-8: " + e.getMessage(), beginningMark); + } + } + + /** + * Scan a line break, transforming: + * + * <pre> + * '\r\n' : '\n' + * '\r' : '\n' + * '\n' : '\n' + * '\x85' : '\n' + * default : '' + * </pre> + */ + private String scanLineBreak() { + int c = reader.peek(); + if (c == '\r' || c == '\n' || c == '\u0085') { + if (c == '\r' && '\n' == reader.peek(1)) { + reader.forward(2); + } else { + reader.forward(); + } + return "\n"; + } else if (c == '\u2028' || c == '\u2029') { + reader.forward(); + return String.valueOf(Character.toChars(c)); } + return ""; + } - /** - * Scan a plain scalar. - * - * <pre> - * See the specification for details. - * We add an additional restriction for the flow context: - * plain scalars in the flow context cannot contain ',', ':' and '?'. - * We also keep track of the `allow_simple_key` flag here. - * Indentation rules are loosed for the flow context. - * </pre> - */ - private Token scanPlain() { - StringBuilder chunks = new StringBuilder(); - Mark startMark = reader.getMark(); - Mark endMark = startMark; - int indent = this.indent + 1; - String spaces = ""; - while (true) { - char ch; - int length = 0; - // A comment indicates the end of the scalar. - if (reader.peek() == '#') { - break; - } - while (true) { - ch = reader.peek(length); - if (Constant.NULL_BL_T_LINEBR.has(ch) - || (this.flowLevel == 0 && ch == ':' && Constant.NULL_BL_T_LINEBR - .has(reader.peek(length + 1))) - || (this.flowLevel != 0 && ",:?[]{}".indexOf(ch) != -1)) { - break; - } - length++; - } - // It's not clear what we should do with ':' in the flow context. - if (this.flowLevel != 0 && ch == ':' - && Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(length + 1), ",[]{}")) { - reader.forward(length); - throw new ScannerException("while scanning a plain scalar", startMark, - "found unexpected ':'", reader.getMark(), - "Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details."); - } - if (length == 0) { - break; - } - this.allowSimpleKey = false; - chunks.append(spaces); - chunks.append(reader.prefixForward(length)); - endMark = reader.getMark(); - spaces = scanPlainSpaces(); - // System.out.printf("spaces[%s]\n", spaces); - if (spaces.length() == 0 || reader.peek() == '#' - || (this.flowLevel == 0 && this.reader.getColumn() < indent)) { - break; - } - } - return new ScalarToken(chunks.toString(), startMark, endMark, true); + private List<Token> makeTokenList(Token... tokens) { + List<Token> tokenList = new ArrayList<>(); + for (int ix = 0; ix < tokens.length; ix++) { + if (tokens[ix] == null) { + continue; + } + if (!parseComments && (tokens[ix] instanceof CommentToken)) { + continue; + } + tokenList.add(tokens[ix]); } + return tokenList; + } - /** - * See the specification for details. SnakeYAML and libyaml allow tabs - * inside plain scalar - */ - private String scanPlainSpaces() { - int length = 0; - while (reader.peek(length) == ' ' || reader.peek(length) == '\t') { - length++; - } - String whitespaces = reader.prefixForward(length); - String lineBreak = scanLineBreak(); - if (lineBreak.length() != 0) { - this.allowSimpleKey = true; - String prefix = reader.prefix(3); - if ("---".equals(prefix) || "...".equals(prefix) - && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { - return ""; - } - StringBuilder breaks = new StringBuilder(); - while (true) { - if (reader.peek() == ' ') { - reader.forward(); - } else { - String lb = scanLineBreak(); - if (lb.length() != 0) { - breaks.append(lb); - prefix = reader.prefix(3); - if ("---".equals(prefix) || "...".equals(prefix) - && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) { - return ""; - } - } else { - break; - } - } - } - if (!"\n".equals(lineBreak)) { - return lineBreak + breaks; - } else if (breaks.length() == 0) { - return " "; - } - return breaks.toString(); - } - return whitespaces; - } + /** + * Chomping the tail may have 3 values - yes, no, not defined. + */ + private static class Chomping { - /** - * <p> - * Scan a Tag handle. A Tag handle takes one of three forms: - * - * <pre> - * "!" (c-primary-tag-handle) - * "!!" (ns-secondary-tag-handle) - * "!(name)!" (c-named-tag-handle) - * </pre> - * - * Where (name) must be formatted as an ns-word-char. - * </p> - * - * @see <a href="http://www.yaml.org/spec/1.1/#c-tag-handle"></a> - * @see <a href="http://www.yaml.org/spec/1.1/#ns-word-char"></a> - * - * <pre> - * See the specification for details. - * For some strange reasons, the specification does not allow '_' in - * tag handles. I have allowed it anyway. - * </pre> - */ - private String scanTagHandle(String name, Mark startMark) { - char ch = reader.peek(); - if (ch != '!') { - throw new ScannerException("while scanning a " + name, startMark, - "expected '!', but found " + ch + "(" + ((int) ch) + ")", reader.getMark()); - } - // Look for the next '!' in the stream, stopping if we hit a - // non-word-character. If the first character is a space, then the - // tag-handle is a c-primary-tag-handle ('!'). - int length = 1; - ch = reader.peek(length); - if (ch != ' ') { - // Scan through 0+ alphabetic characters. - // FIXME According to the specification, these should be - // ns-word-char only, which prohibits '_'. This might be a - // candidate for a configuration option. - while (Constant.ALPHA.has(ch)) { - length++; - ch = reader.peek(length); - } - // Found the next non-word-char. If this is not a space and not an - // '!', then this is an error, as the tag-handle was specified as: - // !(name) or similar; the trailing '!' is missing. - if (ch != '!') { - reader.forward(length); - throw new ScannerException("while scanning a " + name, startMark, - "expected '!', but found " + ch + "(" + ((int) ch) + ")", reader.getMark()); - } - length++; - } - String value = reader.prefixForward(length); - return value; - } + private final Boolean value; + private final int increment; - /** - * <p> - * Scan a Tag URI. This scanning is valid for both local and global tag - * directives, because both appear to be valid URIs as far as scanning is - * concerned. The difference may be distinguished later, in parsing. This - * method will scan for ns-uri-char*, which covers both cases. - * </p> - * - * <p> - * This method performs no verification that the scanned URI conforms to any - * particular kind of URI specification. - * </p> - * - * @see <a href="http://www.yaml.org/spec/1.1/#ns-uri-char"></a> - */ - private String scanTagUri(String name, Mark startMark) { - // See the specification for details. - // Note: we do not check if URI is well-formed. - StringBuilder chunks = new StringBuilder(); - // Scan through accepted URI characters, which includes the standard - // URI characters, plus the start-escape character ('%'). When we get - // to a start-escape, scan the escaped sequence, then return. - int length = 0; - char ch = reader.peek(length); - while (Constant.URI_CHARS.has(ch)) { - if (ch == '%') { - chunks.append(reader.prefixForward(length)); - length = 0; - chunks.append(scanUriEscapes(name, startMark)); - } else { - length++; - } - ch = reader.peek(length); - } - // Consume the last "chunk", which would not otherwise be consumed by - // the loop above. - if (length != 0) { - chunks.append(reader.prefixForward(length)); - length = 0; - } - if (chunks.length() == 0) { - // If no URI was found, an error has occurred. - throw new ScannerException("while scanning a " + name, startMark, - "expected URI, but found " + ch + "(" + ((int) ch) + ")", reader.getMark()); - } - return chunks.toString(); + public Chomping(Boolean value, int increment) { + this.value = value; + this.increment = increment; } - /** - * <p> - * Scan a sequence of %-escaped URI escape codes and convert them into a - * String representing the unescaped values. - * </p> - * - * FIXME This method fails for more than 256 bytes' worth of URI-encoded - * characters in a row. Is this possible? Is this a use-case? - * - * @see <a href="http://www.ietf.org/rfc/rfc2396.txt"></a>, section 2.4, Escaped Encoding. - */ - private String scanUriEscapes(String name, Mark startMark) { - // First, look ahead to see how many URI-escaped characters we should - // expect, so we can use the correct buffer size. - int length = 1; - while (reader.peek(length * 3) == '%') { - length++; - } - // See the specification for details. - // URIs containing 16 and 32 bit Unicode characters are - // encoded in UTF-8, and then each octet is written as a - // separate character. - Mark beginningMark = reader.getMark(); - ByteBuffer buff = ByteBuffer.allocate(length); - while (reader.peek() == '%') { - reader.forward(); - try { - byte code = (byte) Integer.parseInt(reader.prefix(2), 16); - buff.put(code); - } catch (NumberFormatException nfe) { - throw new ScannerException("while scanning a " + name, startMark, - "expected URI escape sequence of 2 hexadecimal numbers, but found " - + reader.peek() + "(" + ((int) reader.peek()) + ") and " - + reader.peek(1) + "(" + ((int) reader.peek(1)) + ")", - reader.getMark()); - } - reader.forward(2); - } - buff.flip(); - try { - return UriEncoder.decode(buff); - } catch (CharacterCodingException e) { - throw new ScannerException("while scanning a " + name, startMark, - "expected URI in UTF-8: " + e.getMessage(), beginningMark); - } + public boolean chompTailIsNotFalse() { + return value == null || value; } - /** - * Scan a line break, transforming: - * - * <pre> - * '\r\n' : '\n' - * '\r' : '\n' - * '\n' : '\n' - * '\x85' : '\n' - * default : '' - * </pre> - */ - private String scanLineBreak() { - // Transforms: - // '\r\n' : '\n' - // '\r' : '\n' - // '\n' : '\n' - // '\x85' : '\n' - // default : '' - char ch = reader.peek(); - if (ch == '\r' || ch == '\n' || ch == '\u0085') { - if (ch == '\r' && '\n' == reader.peek(1)) { - reader.forward(2); - } else { - reader.forward(); - } - return "\n"; - } else if (ch == '\u2028' || ch == '\u2029') { - reader.forward(); - return String.valueOf(ch); - } - return ""; + public boolean chompTailIsTrue() { + return value != null && value; } - /** - * Chomping the tail may have 3 values - yes, no, not defined. - */ - private static class Chomping { - private final Boolean value; - private final int increment; - - public Chomping(Boolean value, int increment) { - this.value = value; - this.increment = increment; - } - - public boolean chompTailIsNotFalse() { - return value == null || value; - } - - public boolean chompTailIsTrue() { - return value != null && value; - } - - public int getIncrement() { - return increment; - } + public int getIncrement() { + return increment; } + } } diff --git a/src/main/java/org/yaml/snakeyaml/scanner/SimpleKey.java b/src/main/java/org/yaml/snakeyaml/scanner/SimpleKey.java index 3fe710cc..931c4e03 100644 --- a/src/main/java/org/yaml/snakeyaml/scanner/SimpleKey.java +++ b/src/main/java/org/yaml/snakeyaml/scanner/SimpleKey.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; @@ -22,53 +20,54 @@ import org.yaml.snakeyaml.error.Mark; * <p> * Helper class for {@link ScannerImpl}. * </p> - * + * * @see ScannerImpl */ final class SimpleKey { - private int tokenNumber; - private boolean required; - private int index; - private int line; - private int column; - private Mark mark; - public SimpleKey(int tokenNumber, boolean required, int index, int line, int column, Mark mark) { - this.tokenNumber = tokenNumber; - this.required = required; - this.index = index; - this.line = line; - this.column = column; - this.mark = mark; - } + private final int tokenNumber; + private final boolean required; + private final int index; + private final int line; + private final int column; + private final Mark mark; + + public SimpleKey(int tokenNumber, boolean required, int index, int line, int column, Mark mark) { + this.tokenNumber = tokenNumber; + this.required = required; + this.index = index; + this.line = line; + this.column = column; + this.mark = mark; + } - public int getTokenNumber() { - return this.tokenNumber; - } + public int getTokenNumber() { + return this.tokenNumber; + } - public int getColumn() { - return this.column; - } + public int getColumn() { + return this.column; + } - public Mark getMark() { - return mark; - } + public Mark getMark() { + return mark; + } - public int getIndex() { - return index; - } + public int getIndex() { + return index; + } - public int getLine() { - return line; - } + public int getLine() { + return line; + } - public boolean isRequired() { - return required; - } + public boolean isRequired() { + return required; + } - @Override - public String toString() { - return "SimpleKey - tokenNumber=" + tokenNumber + " required=" + required + " index=" - + index + " line=" + line + " column=" + column; - } + @Override + public String toString() { + return "SimpleKey - tokenNumber=" + tokenNumber + " required=" + required + " index=" + index + + " line=" + line + " column=" + column; + } } diff --git a/src/main/java/org/yaml/snakeyaml/serializer/AnchorGenerator.java b/src/main/java/org/yaml/snakeyaml/serializer/AnchorGenerator.java index 2308eb59..6674901e 100644 --- a/src/main/java/org/yaml/snakeyaml/serializer/AnchorGenerator.java +++ b/src/main/java/org/yaml/snakeyaml/serializer/AnchorGenerator.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.serializer; @@ -19,5 +17,5 @@ import org.yaml.snakeyaml.nodes.Node; public interface AnchorGenerator { - String nextAnchor(Node node); + String nextAnchor(Node node); } diff --git a/src/main/java/org/yaml/snakeyaml/serializer/NumberAnchorGenerator.java b/src/main/java/org/yaml/snakeyaml/serializer/NumberAnchorGenerator.java index 2f316f88..b33ad9a1 100644 --- a/src/main/java/org/yaml/snakeyaml/serializer/NumberAnchorGenerator.java +++ b/src/main/java/org/yaml/snakeyaml/serializer/NumberAnchorGenerator.java @@ -1,39 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.serializer; -import org.yaml.snakeyaml.nodes.Node; - import java.text.NumberFormat; +import org.yaml.snakeyaml.nodes.Node; public class NumberAnchorGenerator implements AnchorGenerator { - private int lastAnchorId = 0; + private int lastAnchorId = 0; - public NumberAnchorGenerator(int lastAnchorId) { - this.lastAnchorId = lastAnchorId; - } + public NumberAnchorGenerator(int lastAnchorId) { + this.lastAnchorId = lastAnchorId; + } - public String nextAnchor(Node node) { - this.lastAnchorId++; - NumberFormat format = NumberFormat.getNumberInstance(); - format.setMinimumIntegerDigits(3); - format.setMaximumFractionDigits(0);// issue 172 - format.setGroupingUsed(false); - String anchorId = format.format(this.lastAnchorId); - return "id" + anchorId; - } + public String nextAnchor(Node node) { + this.lastAnchorId++; + NumberFormat format = NumberFormat.getNumberInstance(); + format.setMinimumIntegerDigits(3); + format.setMaximumFractionDigits(0);// issue 172 + format.setGroupingUsed(false); + String anchorId = format.format(this.lastAnchorId); + return "id" + anchorId; + } } diff --git a/src/main/java/org/yaml/snakeyaml/serializer/Serializer.java b/src/main/java/org/yaml/snakeyaml/serializer/Serializer.java index 2decf3f3..7d394308 100644 --- a/src/main/java/org/yaml/snakeyaml/serializer/Serializer.java +++ b/src/main/java/org/yaml/snakeyaml/serializer/Serializer.java @@ -1,32 +1,30 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.serializer; import java.io.IOException; -import java.text.NumberFormat; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.Version; +import org.yaml.snakeyaml.comments.CommentLine; import org.yaml.snakeyaml.emitter.Emitable; import org.yaml.snakeyaml.events.AliasEvent; +import org.yaml.snakeyaml.events.CommentEvent; import org.yaml.snakeyaml.events.DocumentEndEvent; import org.yaml.snakeyaml.events.DocumentStartEvent; import org.yaml.snakeyaml.events.ImplicitTuple; @@ -38,7 +36,6 @@ import org.yaml.snakeyaml.events.SequenceStartEvent; import org.yaml.snakeyaml.events.StreamEndEvent; import org.yaml.snakeyaml.events.StreamStartEvent; import org.yaml.snakeyaml.nodes.AnchorNode; -import org.yaml.snakeyaml.nodes.CollectionNode; import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeId; @@ -49,153 +46,181 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.resolver.Resolver; public final class Serializer { - private final Emitable emitter; - private final Resolver resolver; - private boolean explicitStart; - private boolean explicitEnd; - private Version useVersion; - private Map<String, String> useTags; - private Set<Node> serializedNodes; - private Map<Node, String> anchors; - private AnchorGenerator anchorGenerator; - private Boolean closed; - private Tag explicitRoot; - public Serializer(Emitable emitter, Resolver resolver, DumperOptions opts, Tag rootTag) { - this.emitter = emitter; - this.resolver = resolver; - this.explicitStart = opts.isExplicitStart(); - this.explicitEnd = opts.isExplicitEnd(); - if (opts.getVersion() != null) { - this.useVersion = opts.getVersion(); - } - this.useTags = opts.getTags(); - this.serializedNodes = new HashSet<Node>(); - this.anchors = new HashMap<Node, String>(); - this.anchorGenerator = opts.getAnchorGenerator(); - this.closed = null; - this.explicitRoot = rootTag; + private final Emitable emitter; + private final Resolver resolver; + private final boolean explicitStart; + private final boolean explicitEnd; + private Version useVersion; + private final Map<String, String> useTags; + private final Set<Node> serializedNodes; + private final Map<Node, String> anchors; + private final AnchorGenerator anchorGenerator; + private Boolean closed; + private final Tag explicitRoot; + + public Serializer(Emitable emitter, Resolver resolver, DumperOptions opts, Tag rootTag) { + this.emitter = emitter; + this.resolver = resolver; + this.explicitStart = opts.isExplicitStart(); + this.explicitEnd = opts.isExplicitEnd(); + if (opts.getVersion() != null) { + this.useVersion = opts.getVersion(); } + this.useTags = opts.getTags(); + this.serializedNodes = new HashSet<Node>(); + this.anchors = new HashMap<Node, String>(); + this.anchorGenerator = opts.getAnchorGenerator(); + this.closed = null; + this.explicitRoot = rootTag; + } - public void open() throws IOException { - if (closed == null) { - this.emitter.emit(new StreamStartEvent(null, null)); - this.closed = Boolean.FALSE; - } else if (Boolean.TRUE.equals(closed)) { - throw new SerializerException("serializer is closed"); - } else { - throw new SerializerException("serializer is already opened"); - } + public void open() throws IOException { + if (closed == null) { + this.emitter.emit(new StreamStartEvent(null, null)); + this.closed = Boolean.FALSE; + } else if (Boolean.TRUE.equals(closed)) { + throw new SerializerException("serializer is closed"); + } else { + throw new SerializerException("serializer is already opened"); } + } - public void close() throws IOException { - if (closed == null) { - throw new SerializerException("serializer is not opened"); - } else if (!Boolean.TRUE.equals(closed)) { - this.emitter.emit(new StreamEndEvent(null, null)); - this.closed = Boolean.TRUE; - } + public void close() throws IOException { + if (closed == null) { + throw new SerializerException("serializer is not opened"); + } else if (!Boolean.TRUE.equals(closed)) { + this.emitter.emit(new StreamEndEvent(null, null)); + this.closed = Boolean.TRUE; + // release unused resources + this.serializedNodes.clear(); + this.anchors.clear(); } + } - public void serialize(Node node) throws IOException { - if (closed == null) { - throw new SerializerException("serializer is not opened"); - } else if (closed) { - throw new SerializerException("serializer is closed"); - } - this.emitter.emit(new DocumentStartEvent(null, null, this.explicitStart, this.useVersion, - useTags)); - anchorNode(node); - if (explicitRoot != null) { - node.setTag(explicitRoot); - } - serializeNode(node, null); - this.emitter.emit(new DocumentEndEvent(null, null, this.explicitEnd)); - this.serializedNodes.clear(); - this.anchors.clear(); + public void serialize(Node node) throws IOException { + if (closed == null) { + throw new SerializerException("serializer is not opened"); + } else if (closed) { + throw new SerializerException("serializer is closed"); + } + this.emitter + .emit(new DocumentStartEvent(null, null, this.explicitStart, this.useVersion, useTags)); + anchorNode(node); + if (explicitRoot != null) { + node.setTag(explicitRoot); } + serializeNode(node, null); + this.emitter.emit(new DocumentEndEvent(null, null, this.explicitEnd)); + this.serializedNodes.clear(); + this.anchors.clear(); + } - private void anchorNode(Node node) { - if (node.getNodeId() == NodeId.anchor) { - node = ((AnchorNode) node).getRealNode(); - } - if (this.anchors.containsKey(node)) { - String anchor = this.anchors.get(node); - if (null == anchor) { - anchor = this.anchorGenerator.nextAnchor(node); - this.anchors.put(node, anchor); - } - } else { - this.anchors.put(node, null); - switch (node.getNodeId()) { - case sequence: - SequenceNode seqNode = (SequenceNode) node; - List<Node> list = seqNode.getValue(); - for (Node item : list) { - anchorNode(item); - } - break; - case mapping: - MappingNode mnode = (MappingNode) node; - List<NodeTuple> map = mnode.getValue(); - for (NodeTuple object : map) { - Node key = object.getKeyNode(); - Node value = object.getValueNode(); - anchorNode(key); - anchorNode(value); - } - break; - } - } + private void anchorNode(Node node) { + if (node.getNodeId() == NodeId.anchor) { + node = ((AnchorNode) node).getRealNode(); } + if (this.anchors.containsKey(node)) { + String anchor = this.anchors.get(node); + if (null == anchor) { + anchor = this.anchorGenerator.nextAnchor(node); + this.anchors.put(node, anchor); + } + } else { + this.anchors.put(node, + node.getAnchor() != null ? this.anchorGenerator.nextAnchor(node) : null); + switch (node.getNodeId()) { + case sequence: + SequenceNode seqNode = (SequenceNode) node; + List<Node> list = seqNode.getValue(); + for (Node item : list) { + anchorNode(item); + } + break; + case mapping: + MappingNode mnode = (MappingNode) node; + List<NodeTuple> map = mnode.getValue(); + for (NodeTuple object : map) { + Node key = object.getKeyNode(); + Node value = object.getValueNode(); + anchorNode(key); + anchorNode(value); + } + break; + } + } + } - private void serializeNode(Node node, Node parent) throws IOException { - if (node.getNodeId() == NodeId.anchor) { - node = ((AnchorNode) node).getRealNode(); - } - String tAlias = this.anchors.get(node); - if (this.serializedNodes.contains(node)) { - this.emitter.emit(new AliasEvent(tAlias, null, null)); - } else { - this.serializedNodes.add(node); - switch (node.getNodeId()) { - case scalar: - ScalarNode scalarNode = (ScalarNode) node; - Tag detectedTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), true); - Tag defaultTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), false); - ImplicitTuple tuple = new ImplicitTuple(node.getTag().equals(detectedTag), node - .getTag().equals(defaultTag)); - ScalarEvent event = new ScalarEvent(tAlias, node.getTag().getValue(), tuple, - scalarNode.getValue(), null, null, scalarNode.getStyle()); - this.emitter.emit(event); - break; - case sequence: - SequenceNode seqNode = (SequenceNode) node; - boolean implicitS = node.getTag().equals(this.resolver.resolve(NodeId.sequence, - null, true)); - this.emitter.emit(new SequenceStartEvent(tAlias, node.getTag().getValue(), - implicitS, null, null, seqNode.getFlowStyle())); - List<Node> list = seqNode.getValue(); - for (Node item : list) { - serializeNode(item, node); - } - this.emitter.emit(new SequenceEndEvent(null, null)); - break; - default:// instance of MappingNode - Tag implicitTag = this.resolver.resolve(NodeId.mapping, null, true); - boolean implicitM = node.getTag().equals(implicitTag); - this.emitter.emit(new MappingStartEvent(tAlias, node.getTag().getValue(), - implicitM, null, null, ((CollectionNode) node).getFlowStyle())); - MappingNode mnode = (MappingNode) node; - List<NodeTuple> map = mnode.getValue(); - for (NodeTuple row : map) { - Node key = row.getKeyNode(); - Node value = row.getValueNode(); - serializeNode(key, mnode); - serializeNode(value, mnode); - } - this.emitter.emit(new MappingEndEvent(null, null)); + // parent Node is not used but might be used in the future + private void serializeNode(Node node, Node parent) throws IOException { + if (node.getNodeId() == NodeId.anchor) { + node = ((AnchorNode) node).getRealNode(); + } + String tAlias = this.anchors.get(node); + if (this.serializedNodes.contains(node)) { + this.emitter.emit(new AliasEvent(tAlias, null, null)); + } else { + this.serializedNodes.add(node); + switch (node.getNodeId()) { + case scalar: + ScalarNode scalarNode = (ScalarNode) node; + serializeComments(node.getBlockComments()); + Tag detectedTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), true); + Tag defaultTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), false); + ImplicitTuple tuple = new ImplicitTuple(node.getTag().equals(detectedTag), + node.getTag().equals(defaultTag)); + ScalarEvent event = new ScalarEvent(tAlias, node.getTag().getValue(), tuple, + scalarNode.getValue(), null, null, scalarNode.getScalarStyle()); + this.emitter.emit(event); + serializeComments(node.getInLineComments()); + serializeComments(node.getEndComments()); + break; + case sequence: + SequenceNode seqNode = (SequenceNode) node; + serializeComments(node.getBlockComments()); + boolean implicitS = + node.getTag().equals(this.resolver.resolve(NodeId.sequence, null, true)); + this.emitter.emit(new SequenceStartEvent(tAlias, node.getTag().getValue(), implicitS, + null, null, seqNode.getFlowStyle())); + List<Node> list = seqNode.getValue(); + for (Node item : list) { + serializeNode(item, node); + } + this.emitter.emit(new SequenceEndEvent(null, null)); + serializeComments(node.getInLineComments()); + serializeComments(node.getEndComments()); + break; + default:// instance of MappingNode + serializeComments(node.getBlockComments()); + Tag implicitTag = this.resolver.resolve(NodeId.mapping, null, true); + boolean implicitM = node.getTag().equals(implicitTag); + MappingNode mnode = (MappingNode) node; + List<NodeTuple> map = mnode.getValue(); + if (mnode.getTag() != Tag.COMMENT) { + this.emitter.emit(new MappingStartEvent(tAlias, mnode.getTag().getValue(), implicitM, + null, null, mnode.getFlowStyle())); + for (NodeTuple row : map) { + Node key = row.getKeyNode(); + Node value = row.getValueNode(); + serializeNode(key, mnode); + serializeNode(value, mnode); } - } + this.emitter.emit(new MappingEndEvent(null, null)); + serializeComments(node.getInLineComments()); + serializeComments(node.getEndComments()); + } + } + } + } + + private void serializeComments(List<CommentLine> comments) throws IOException { + if (comments == null) { + return; + } + for (CommentLine line : comments) { + CommentEvent commentEvent = new CommentEvent(line.getCommentType(), line.getValue(), + line.getStartMark(), line.getEndMark()); + this.emitter.emit(commentEvent); } + } } diff --git a/src/main/java/org/yaml/snakeyaml/serializer/SerializerException.java b/src/main/java/org/yaml/snakeyaml/serializer/SerializerException.java index 0cb6e887..21e9f38f 100644 --- a/src/main/java/org/yaml/snakeyaml/serializer/SerializerException.java +++ b/src/main/java/org/yaml/snakeyaml/serializer/SerializerException.java @@ -1,26 +1,25 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.serializer; import org.yaml.snakeyaml.error.YAMLException; public class SerializerException extends YAMLException { - private static final long serialVersionUID = 2632638197498912433L; - public SerializerException(String message) { - super(message); - } + private static final long serialVersionUID = 2632638197498912433L; + + public SerializerException(String message) { + super(message); + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/AliasToken.java b/src/main/java/org/yaml/snakeyaml/tokens/AliasToken.java index df2ee2e9..be8a5144 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/AliasToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/AliasToken.java @@ -1,41 +1,35 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import org.yaml.snakeyaml.error.Mark; public final class AliasToken extends Token { - private final String value; - public AliasToken(String value, Mark startMark, Mark endMark) { - super(startMark, endMark); - this.value = value; - } + private final String value; - public String getValue() { - return this.value; - } + public AliasToken(String value, Mark startMark, Mark endMark) { + super(startMark, endMark); + this.value = value; + } - @Override - protected String getArguments() { - return "value=" + value; - } + public String getValue() { + return this.value; + } - @Override - public Token.ID getTokenId() { - return ID.Alias; - } + @Override + public Token.ID getTokenId() { + return ID.Alias; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/AnchorToken.java b/src/main/java/org/yaml/snakeyaml/tokens/AnchorToken.java index 3629eeae..6d10cf71 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/AnchorToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/AnchorToken.java @@ -1,41 +1,35 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import org.yaml.snakeyaml.error.Mark; public final class AnchorToken extends Token { - private final String value; - public AnchorToken(String value, Mark startMark, Mark endMark) { - super(startMark, endMark); - this.value = value; - } + private final String value; - public String getValue() { - return this.value; - } + public AnchorToken(String value, Mark startMark, Mark endMark) { + super(startMark, endMark); + this.value = value; + } - @Override - protected String getArguments() { - return "value=" + value; - } + public String getValue() { + return this.value; + } - @Override - public Token.ID getTokenId() { - return ID.Anchor; - } + @Override + public Token.ID getTokenId() { + return ID.Anchor; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/BlockEndToken.java b/src/main/java/org/yaml/snakeyaml/tokens/BlockEndToken.java index 3315bc40..0f994154 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/BlockEndToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/BlockEndToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class BlockEndToken extends Token { - public BlockEndToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public BlockEndToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.BlockEnd; - } + @Override + public Token.ID getTokenId() { + return ID.BlockEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/BlockEntryToken.java b/src/main/java/org/yaml/snakeyaml/tokens/BlockEntryToken.java index 574445f0..3657ae70 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/BlockEntryToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/BlockEntryToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class BlockEntryToken extends Token { - public BlockEntryToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public BlockEntryToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.BlockEntry; - } + @Override + public Token.ID getTokenId() { + return ID.BlockEntry; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/BlockMappingStartToken.java b/src/main/java/org/yaml/snakeyaml/tokens/BlockMappingStartToken.java index 95a61642..4a35c917 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/BlockMappingStartToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/BlockMappingStartToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class BlockMappingStartToken extends Token { - public BlockMappingStartToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public BlockMappingStartToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.BlockMappingStart; - } + @Override + public Token.ID getTokenId() { + return ID.BlockMappingStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/BlockSequenceStartToken.java b/src/main/java/org/yaml/snakeyaml/tokens/BlockSequenceStartToken.java index d70194c7..3ea7a20d 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/BlockSequenceStartToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/BlockSequenceStartToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class BlockSequenceStartToken extends Token { - public BlockSequenceStartToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public BlockSequenceStartToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.BlockSequenceStart; - } + @Override + public Token.ID getTokenId() { + return ID.BlockSequenceStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/CommentToken.java b/src/main/java/org/yaml/snakeyaml/tokens/CommentToken.java index 12c067ef..36fe079e 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/CommentToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/CommentToken.java @@ -1,29 +1,45 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; +import java.util.Objects; +import org.yaml.snakeyaml.comments.CommentType; import org.yaml.snakeyaml.error.Mark; -public class CommentToken extends Token { - public CommentToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } +public final class CommentToken extends Token { - @Override - public ID getTokenId() { - return ID.Comment; - } + private final CommentType type; + private final String value; + + public CommentToken(CommentType type, String value, Mark startMark, Mark endMark) { + super(startMark, endMark); + Objects.requireNonNull(type); + this.type = type; + Objects.requireNonNull(value); + this.value = value; + } + + public CommentType getCommentType() { + return this.type; + } + + public String getValue() { + return this.value; + } + + @Override + public Token.ID getTokenId() { + return ID.Comment; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/DirectiveToken.java b/src/main/java/org/yaml/snakeyaml/tokens/DirectiveToken.java index af1743f8..d6d53035 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/DirectiveToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/DirectiveToken.java @@ -1,58 +1,46 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import java.util.List; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; public final class DirectiveToken<T> extends Token { - private final String name; - private final List<T> value; - public DirectiveToken(String name, List<T> value, Mark startMark, Mark endMark) { - super(startMark, endMark); - this.name = name; - if (value != null && value.size() != 2) { - throw new YAMLException("Two strings must be provided instead of " - + String.valueOf(value.size())); - } - this.value = value; - } + private final String name; + private final List<T> value; - public String getName() { - return this.name; + public DirectiveToken(String name, List<T> value, Mark startMark, Mark endMark) { + super(startMark, endMark); + this.name = name; + if (value != null && value.size() != 2) { + throw new YAMLException("Two strings must be provided instead of " + value.size()); } + this.value = value; + } - public List<T> getValue() { - return this.value; - } + public String getName() { + return this.name; + } - @Override - protected String getArguments() { - if (value != null) { - return "name=" + name + ", value=[" + value.get(0) + ", " + value.get(1) + "]"; - } else { - return "name=" + name; - } - } + public List<T> getValue() { + return this.value; + } - @Override - public Token.ID getTokenId() { - return ID.Directive; - } + @Override + public Token.ID getTokenId() { + return ID.Directive; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/DocumentEndToken.java b/src/main/java/org/yaml/snakeyaml/tokens/DocumentEndToken.java index ee17dab1..4c2319c3 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/DocumentEndToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/DocumentEndToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class DocumentEndToken extends Token { - public DocumentEndToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public DocumentEndToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.DocumentEnd; - } + @Override + public Token.ID getTokenId() { + return ID.DocumentEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/DocumentStartToken.java b/src/main/java/org/yaml/snakeyaml/tokens/DocumentStartToken.java index 0b72deb3..1ce5445d 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/DocumentStartToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/DocumentStartToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class DocumentStartToken extends Token { - public DocumentStartToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public DocumentStartToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.DocumentStart; - } + @Override + public Token.ID getTokenId() { + return ID.DocumentStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/FlowEntryToken.java b/src/main/java/org/yaml/snakeyaml/tokens/FlowEntryToken.java index b1afb0f5..03e5c9ff 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/FlowEntryToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/FlowEntryToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class FlowEntryToken extends Token { - public FlowEntryToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public FlowEntryToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.FlowEntry; - } + @Override + public Token.ID getTokenId() { + return ID.FlowEntry; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingEndToken.java b/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingEndToken.java index 1659a9f0..8ec5dd4c 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingEndToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingEndToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class FlowMappingEndToken extends Token { - public FlowMappingEndToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public FlowMappingEndToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.FlowMappingEnd; - } + @Override + public Token.ID getTokenId() { + return ID.FlowMappingEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingStartToken.java b/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingStartToken.java index 5a984c72..8ee9814b 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingStartToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/FlowMappingStartToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class FlowMappingStartToken extends Token { - public FlowMappingStartToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public FlowMappingStartToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.FlowMappingStart; - } + @Override + public Token.ID getTokenId() { + return ID.FlowMappingStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceEndToken.java b/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceEndToken.java index 39b03c43..cc991d42 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceEndToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceEndToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class FlowSequenceEndToken extends Token { - public FlowSequenceEndToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public FlowSequenceEndToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.FlowSequenceEnd; - } + @Override + public Token.ID getTokenId() { + return ID.FlowSequenceEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceStartToken.java b/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceStartToken.java index da89785e..1e2de015 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceStartToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/FlowSequenceStartToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class FlowSequenceStartToken extends Token { - public FlowSequenceStartToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public FlowSequenceStartToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.FlowSequenceStart; - } + @Override + public Token.ID getTokenId() { + return ID.FlowSequenceStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/KeyToken.java b/src/main/java/org/yaml/snakeyaml/tokens/KeyToken.java index 0f880438..2b36521c 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/KeyToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/KeyToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class KeyToken extends Token { - public KeyToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public KeyToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.Key; - } + @Override + public Token.ID getTokenId() { + return ID.Key; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/ScalarToken.java b/src/main/java/org/yaml/snakeyaml/tokens/ScalarToken.java index 828189e8..5a6ccd51 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/ScalarToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/ScalarToken.java @@ -1,57 +1,56 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; public final class ScalarToken extends Token { - private final String value; - private final boolean plain; - private final char style; - public ScalarToken(String value, Mark startMark, Mark endMark, boolean plain) { - this(value, plain, startMark, endMark, (char) 0); + private final String value; + private final boolean plain; + private final DumperOptions.ScalarStyle style; + + public ScalarToken(String value, Mark startMark, Mark endMark, boolean plain) { + this(value, plain, startMark, endMark, DumperOptions.ScalarStyle.PLAIN); + } + + public ScalarToken(String value, boolean plain, Mark startMark, Mark endMark, + DumperOptions.ScalarStyle style) { + super(startMark, endMark); + this.value = value; + this.plain = plain; + if (style == null) { + throw new NullPointerException("Style must be provided."); } + this.style = style; + } - public ScalarToken(String value, boolean plain, Mark startMark, Mark endMark, char style) { - super(startMark, endMark); - this.value = value; - this.plain = plain; - this.style = style; - } - - public boolean getPlain() { - return this.plain; - } - - public String getValue() { - return this.value; - } + public boolean getPlain() { + return this.plain; + } - public char getStyle() { - return this.style; - } + public String getValue() { + return this.value; + } - @Override - protected String getArguments() { - return "value=" + value + ", plain=" + plain + ", style=" + style; - } + public DumperOptions.ScalarStyle getStyle() { + return this.style; + } - @Override - public Token.ID getTokenId() { - return ID.Scalar; - } + @Override + public Token.ID getTokenId() { + return ID.Scalar; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/StreamEndToken.java b/src/main/java/org/yaml/snakeyaml/tokens/StreamEndToken.java index ece87b95..4998ee32 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/StreamEndToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/StreamEndToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class StreamEndToken extends Token { - public StreamEndToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public StreamEndToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.StreamEnd; - } + @Override + public Token.ID getTokenId() { + return ID.StreamEnd; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/StreamStartToken.java b/src/main/java/org/yaml/snakeyaml/tokens/StreamStartToken.java index 4b5419a6..f085f45c 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/StreamStartToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/StreamStartToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class StreamStartToken extends Token { - public StreamStartToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public StreamStartToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.StreamStart; - } + @Override + public Token.ID getTokenId() { + return ID.StreamStart; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/TagToken.java b/src/main/java/org/yaml/snakeyaml/tokens/TagToken.java index 505a360f..affa00a1 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/TagToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/TagToken.java @@ -1,41 +1,35 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import org.yaml.snakeyaml.error.Mark; public final class TagToken extends Token { - private final TagTuple value; - public TagToken(TagTuple value, Mark startMark, Mark endMark) { - super(startMark, endMark); - this.value = value; - } + private final TagTuple value; - public TagTuple getValue() { - return this.value; - } + public TagToken(TagTuple value, Mark startMark, Mark endMark) { + super(startMark, endMark); + this.value = value; + } - @Override - protected String getArguments() { - return "value=[" + value.getHandle() + ", " + value.getSuffix() + "]"; - } + public TagTuple getValue() { + return this.value; + } - @Override - public Token.ID getTokenId() { - return ID.Tag; - } + @Override + public Token.ID getTokenId() { + return ID.Tag; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/TagTuple.java b/src/main/java/org/yaml/snakeyaml/tokens/TagTuple.java index b4ea0646..dd0ef388 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/TagTuple.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/TagTuple.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; public final class TagTuple { - private final String handle; - private final String suffix; - public TagTuple(String handle, String suffix) { - if (suffix == null) { - throw new NullPointerException("Suffix must be provided."); - } - this.handle = handle; - this.suffix = suffix; - } + private final String handle; + private final String suffix; - public String getHandle() { - return handle; + public TagTuple(String handle, String suffix) { + if (suffix == null) { + throw new NullPointerException("Suffix must be provided."); } + this.handle = handle; + this.suffix = suffix; + } - public String getSuffix() { - return suffix; - } + public String getHandle() { + return handle; + } + + public String getSuffix() { + return suffix; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/Token.java b/src/main/java/org/yaml/snakeyaml/tokens/Token.java index 8b583f5d..63a49271 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/Token.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/Token.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,64 +17,53 @@ import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; public abstract class Token { - public enum ID { - Alias, Anchor, BlockEnd, BlockEntry, BlockMappingStart, BlockSequenceStart, Directive, DocumentEnd, DocumentStart, FlowEntry, FlowMappingEnd, FlowMappingStart, FlowSequenceEnd, FlowSequenceStart, Key, Scalar, StreamEnd, StreamStart, Tag, Value, Whitespace, Comment, Error - } - private final Mark startMark; - private final Mark endMark; + public enum ID { + Alias("<alias>"), Anchor("<anchor>"), BlockEnd("<block end>"), BlockEntry( + "-"), BlockMappingStart("<block mapping start>"), BlockSequenceStart( + "<block sequence start>"), Directive("<directive>"), DocumentEnd( + "<document end>"), DocumentStart("<document start>"), FlowEntry( + ","), FlowMappingEnd("}"), FlowMappingStart("{"), FlowSequenceEnd( + "]"), FlowSequenceStart("["), Key("?"), Scalar("<scalar>"), StreamEnd( + "<stream end>"), StreamStart("<stream start>"), Tag("<tag>"), Value( + ":"), Whitespace("<whitespace>"), Comment("#"), Error("<error>"); - public Token(Mark startMark, Mark endMark) { - if (startMark == null || endMark == null) { - throw new YAMLException("Token requires marks."); - } - this.startMark = startMark; - this.endMark = endMark; - } + private final String description; - public String toString() { - return "<" + this.getClass().getName() + "(" + getArguments() + ")>"; + ID(String s) { + description = s; } - public Mark getStartMark() { - return startMark; + @Override + public String toString() { + return description; } + } - public Mark getEndMark() { - return endMark; - } + private final Mark startMark; + private final Mark endMark; - /** - * @see "__repr__ for Token in PyYAML" - */ - protected String getArguments() { - return ""; + public Token(Mark startMark, Mark endMark) { + if (startMark == null || endMark == null) { + throw new YAMLException("Token requires marks."); } + this.startMark = startMark; + this.endMark = endMark; + } - /** - * For error reporting. - * - * @see "class variable 'id' in PyYAML" - */ - public abstract Token.ID getTokenId(); + public Mark getStartMark() { + return startMark; + } - /* - * for tests only - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof Token) { - return toString().equals(obj.toString()); - } else { - return false; - } - } + public Mark getEndMark() { + return endMark; + } - /* - * for tests only - */ - @Override - public int hashCode() { - return toString().hashCode(); - } + /** + * For error reporting. + * + * @see "class variable 'id' in PyYAML" + * @return ID of this token + */ + public abstract Token.ID getTokenId(); } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/ValueToken.java b/src/main/java/org/yaml/snakeyaml/tokens/ValueToken.java index 58fe0576..504f1c6f 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/ValueToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/ValueToken.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; @@ -19,12 +17,12 @@ import org.yaml.snakeyaml.error.Mark; public final class ValueToken extends Token { - public ValueToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } + public ValueToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } - @Override - public Token.ID getTokenId() { - return ID.Value; - } + @Override + public Token.ID getTokenId() { + return ID.Value; + } } diff --git a/src/main/java/org/yaml/snakeyaml/tokens/WhitespaceToken.java b/src/main/java/org/yaml/snakeyaml/tokens/WhitespaceToken.java index 65af212d..f61de83e 100644 --- a/src/main/java/org/yaml/snakeyaml/tokens/WhitespaceToken.java +++ b/src/main/java/org/yaml/snakeyaml/tokens/WhitespaceToken.java @@ -1,29 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import org.yaml.snakeyaml.error.Mark; +/** + * @deprecated it will be removed because it is not used + */ +@Deprecated public class WhitespaceToken extends Token { - public WhitespaceToken(Mark startMark, Mark endMark) { - super(startMark, endMark); - } - @Override - public ID getTokenId() { - return ID.Whitespace; - } + public WhitespaceToken(Mark startMark, Mark endMark) { + super(startMark, endMark); + } + + @Override + public ID getTokenId() { + return ID.Whitespace; + } } diff --git a/src/main/java/org/yaml/snakeyaml/util/ArrayStack.java b/src/main/java/org/yaml/snakeyaml/util/ArrayStack.java index 4bab182a..d0782d15 100644 --- a/src/main/java/org/yaml/snakeyaml/util/ArrayStack.java +++ b/src/main/java/org/yaml/snakeyaml/util/ArrayStack.java @@ -1,42 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.util; import java.util.ArrayList; public class ArrayStack<T> { - private ArrayList<T> stack; - public ArrayStack(int initSize) { - stack = new ArrayList<T>(initSize); - } + private final ArrayList<T> stack; - public void push(T obj) { - stack.add(obj); - } + public ArrayStack(int initSize) { + stack = new ArrayList<T>(initSize); + } - public T pop() { - return stack.remove(stack.size() - 1); - } + public void push(T obj) { + stack.add(obj); + } - public boolean isEmpty() { - return stack.isEmpty(); - } + public T pop() { + return stack.remove(stack.size() - 1); + } - public void clear() { - stack.clear(); - } + public boolean isEmpty() { + return stack.isEmpty(); + } + + public void clear() { + stack.clear(); + } } diff --git a/src/main/java/org/yaml/snakeyaml/util/ArrayUtils.java b/src/main/java/org/yaml/snakeyaml/util/ArrayUtils.java new file mode 100644 index 00000000..9d0aa10d --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/util/ArrayUtils.java @@ -0,0 +1,109 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.util; + +import java.util.AbstractList; +import java.util.Collections; +import java.util.List; + +public class ArrayUtils { + + private ArrayUtils() {} + + /** + * Returns an unmodifiable {@code List} backed by the given array. The method doesn't copy the + * array, so the changes to the array will affect the {@code List} as well. + * + * @param <E> class of the elements in the array + * @param elements - array to convert + * @return {@code List} backed by the given array + */ + public static <E> List<E> toUnmodifiableList(E[] elements) { + return elements.length == 0 ? Collections.<E>emptyList() + : new UnmodifiableArrayList<E>(elements); + } + + /** + * Returns an unmodifiable {@code List} containing the second array appended to the first one. The + * method doesn't copy the arrays, so the changes to the arrays will affect the {@code List} as + * well. + * + * @param <E> class of the elements in the array + * @param array1 - the array to extend + * @param array2 - the array to add to the first + * @return {@code List} backed by the given arrays + */ + public static <E> List<E> toUnmodifiableCompositeList(E[] array1, E[] array2) { + List<E> result; + if (array1.length == 0) { + result = toUnmodifiableList(array2); + } else if (array2.length == 0) { + result = toUnmodifiableList(array1); + } else { + result = new CompositeUnmodifiableArrayList<E>(array1, array2); + } + return result; + } + + private static class UnmodifiableArrayList<E> extends AbstractList<E> { + + private final E[] array; + + UnmodifiableArrayList(E[] array) { + this.array = array; + } + + @Override + public E get(int index) { + if (index >= array.length) { + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); + } + return array[index]; + } + + @Override + public int size() { + return array.length; + } + } + + private static class CompositeUnmodifiableArrayList<E> extends AbstractList<E> { + + private final E[] array1; + private final E[] array2; + + CompositeUnmodifiableArrayList(E[] array1, E[] array2) { + this.array1 = array1; + this.array2 = array2; + } + + @Override + public E get(int index) { + E element; + if (index < array1.length) { + element = array1[index]; + } else if (index - array1.length < array2.length) { + element = array2[index - array1.length]; + } else { + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); + } + return element; + } + + @Override + public int size() { + return array1.length + array2.length; + } + } +} diff --git a/src/main/java/org/yaml/snakeyaml/util/EnumUtils.java b/src/main/java/org/yaml/snakeyaml/util/EnumUtils.java new file mode 100644 index 00000000..da2eb3ed --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/util/EnumUtils.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.util; + +public class EnumUtils { + + /** + * Looks for an enumeration constant that matches the string without being case sensitive + * + * @param enumType - the Class object of the enum type from which to return a constant + * @param name - the name of the constant to return + * @param <T> - the enum type whose constant is to be returned + * @return the enum constant of the specified enum type with the specified name, insensitive to + * case + * @throws IllegalArgumentException โ if the specified enum type has no constant with the + * specified name, insensitive case + */ + public static <T extends Enum<T>> T findEnumInsensitiveCase(Class<T> enumType, String name) { + for (T constant : enumType.getEnumConstants()) { + if (constant.name().compareToIgnoreCase(name) == 0) { + return constant; + } + } + throw new IllegalArgumentException( + "No enum constant " + enumType.getCanonicalName() + "." + name); + } +} diff --git a/src/main/java/org/yaml/snakeyaml/util/PlatformFeatureDetector.java b/src/main/java/org/yaml/snakeyaml/util/PlatformFeatureDetector.java new file mode 100644 index 00000000..8d8f0757 --- /dev/null +++ b/src/main/java/org/yaml/snakeyaml/util/PlatformFeatureDetector.java @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.util; + +public class PlatformFeatureDetector { + + private Boolean isRunningOnAndroid = null; + + public boolean isRunningOnAndroid() { + if (isRunningOnAndroid == null) { + String name = System.getProperty("java.runtime.name"); + isRunningOnAndroid = (name != null && name.startsWith("Android Runtime")); + } + return isRunningOnAndroid; + } +} diff --git a/src/main/java/org/yaml/snakeyaml/util/UriEncoder.java b/src/main/java/org/yaml/snakeyaml/util/UriEncoder.java index e23904ff..02c3e434 100644 --- a/src/main/java/org/yaml/snakeyaml/util/UriEncoder.java +++ b/src/main/java/org/yaml/snakeyaml/util/UriEncoder.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.util; @@ -20,43 +18,50 @@ import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; - +import java.nio.charset.StandardCharsets; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.external.com.google.gdata.util.common.base.Escaper; import org.yaml.snakeyaml.external.com.google.gdata.util.common.base.PercentEscaper; public abstract class UriEncoder { - private static final CharsetDecoder UTF8Decoder = Charset.forName("UTF-8").newDecoder() - .onMalformedInput(CodingErrorAction.REPORT); - // Include the [] chars to the SAFEPATHCHARS_URLENCODER to avoid - // its escape as required by spec. See - // http://yaml.org/spec/1.1/#escaping%20in%20URI/ - private static final String SAFE_CHARS = PercentEscaper.SAFEPATHCHARS_URLENCODER + "[]/"; - private static final Escaper escaper = new PercentEscaper(SAFE_CHARS, false); - /** - * Escape special characters with '%' - */ - public static String encode(String uri) { - return escaper.escape(uri); - } + private static final CharsetDecoder UTF8Decoder = + StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT); + // Include the [] chars to the SAFEPATHCHARS_URLENCODER to avoid + // its escape as required by spec. See + // http://yaml.org/spec/1.1/#escaping%20in%20URI/ + private static final String SAFE_CHARS = PercentEscaper.SAFEPATHCHARS_URLENCODER + "[]/"; + private static final Escaper escaper = new PercentEscaper(SAFE_CHARS, false); - /** - * Decode '%'-escaped characters. Decoding fails in case of invalid UTF-8 - */ - public static String decode(ByteBuffer buff) throws CharacterCodingException { - CharBuffer chars = UTF8Decoder.decode(buff); - return chars.toString(); - } + /** + * Escape special characters with '%' + * + * @param uri URI to be escaped + * @return encoded URI + */ + public static String encode(String uri) { + return escaper.escape(uri); + } + + /** + * Decode '%'-escaped characters. Decoding fails in case of invalid UTF-8 + * + * @param buff data to decode + * @return decoded data + * @throws CharacterCodingException if cannot be decoded + */ + public static String decode(ByteBuffer buff) throws CharacterCodingException { + CharBuffer chars = UTF8Decoder.decode(buff); + return chars.toString(); + } - public static String decode(String buff) { - try { - return URLDecoder.decode(buff, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new YAMLException(e); - } + public static String decode(String buff) { + try { + return URLDecoder.decode(buff, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new YAMLException(e); } + } } diff --git a/src/patches/android/CompactConstructor.patch b/src/patches/android/CompactConstructor.patch deleted file mode 100644 index c935ecdd..00000000 --- a/src/patches/android/CompactConstructor.patch +++ /dev/null @@ -1,22 +0,0 @@ -# HG changeset patch -# Parent 802af3ea9a2228c074259858b737e2cda0d22a7c -diff --git a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java ---- a/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java -+++ b/src/main/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructor.java -@@ -15,7 +15,6 @@ - */ - package org.yaml.snakeyaml.extensions.compactnotation; - --import java.beans.IntrospectionException; - import java.util.HashMap; - import java.util.Iterator; - import java.util.List; -@@ -186,7 +185,7 @@ - * - * @throws IntrospectionException - */ -- protected String getSequencePropertyName(Class<?> bean) throws IntrospectionException { -+ protected String getSequencePropertyName(Class<?> bean) { - Set<Property> properties = getPropertyUtils().getProperties(bean); - for (Iterator<Property> iterator = properties.iterator(); iterator.hasNext();) { - Property property = iterator.next(); diff --git a/src/patches/android/Constructor.patch b/src/patches/android/Constructor.patch deleted file mode 100644 index 15886668..00000000 --- a/src/patches/android/Constructor.patch +++ /dev/null @@ -1,24 +0,0 @@ -# HG changeset patch -# Parent 6211618dbbb85e16ccdfea2c1c68e098ac1bc333 - -diff --git a/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java b/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java ---- a/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java -+++ b/src/main/java/org/yaml/snakeyaml/constructor/Constructor.java -@@ -15,7 +15,6 @@ - */ - package org.yaml.snakeyaml.constructor; - --import java.beans.IntrospectionException; - import java.math.BigDecimal; - import java.math.BigInteger; - import java.util.ArrayList; -@@ -303,8 +302,7 @@ - return object; - } - -- protected Property getProperty(Class<? extends Object> type, String name) -- throws IntrospectionException { -+ protected Property getProperty(Class<? extends Object> type, String name) { - return getPropertyUtils().getProperty(type, name); - } - } diff --git a/src/patches/android/PropertyTest.patch b/src/patches/android/PropertyTest.patch new file mode 100644 index 00000000..b01f2df6 --- /dev/null +++ b/src/patches/android/PropertyTest.patch @@ -0,0 +1,21 @@ +diff --git a/src/test/java/org/yaml/snakeyaml/introspector/PropertyTest.java b/src/test/java/org/yaml/snakeyaml/introspector/PropertyTest.java +--- a/src/test/java/org/yaml/snakeyaml/introspector/PropertyTest.java (revision 9c05d7250e565df10bdf0da92bf89a1c39e5c073) ++++ b/src/test/java/org/yaml/snakeyaml/introspector/PropertyTest.java (date 1662964689659) +@@ -32,17 +32,6 @@ + + public class PropertyTest { + +- @Test +- public void testMethodPropertyToString() throws IntrospectionException { +- for (PropertyDescriptor property : Introspector.getBeanInfo(TestBean1.class) +- .getPropertyDescriptors()) { +- if (property.getName().equals("text")) { +- MethodProperty prop = new MethodProperty(property); +- assertEquals("text of class java.lang.String", prop.toString()); +- } +- } +- } +- + @Test + public void testGetFieldPropertyAnnotation() { + PropertyUtils propertyUtils = new PropertyUtils(); diff --git a/src/patches/android/PropertyUtils.patch b/src/patches/android/PropertyUtils.patch index dc72ef3c..9a9d6013 100644 --- a/src/patches/android/PropertyUtils.patch +++ b/src/patches/android/PropertyUtils.patch @@ -1,12 +1,12 @@ -# HG changeset patch -# Parent 698e9f1d6348fc1066ceaac7d264cbbf63bdcd21 diff --git a/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java b/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java +index 8afc5761..208c9351 100644 --- a/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java +++ b/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java -@@ -15,11 +15,7 @@ +@@ -13,12 +13,7 @@ */ package org.yaml.snakeyaml.introspector; +-import java.beans.FeatureDescriptor; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; @@ -15,104 +15,69 @@ diff --git a/src/main/java/org/yaml/snakeyaml/introspector/PropertyUtils.java b/ import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashMap; -@@ -37,64 +33,31 @@ - private BeanAccess beanAccess = BeanAccess.DEFAULT; - private boolean allowReadOnlyProperties = false; - -- protected Map<String, Property> getPropertiesMap(Class<?> type, BeanAccess bAccess) -- throws IntrospectionException { -+ protected Map<String, Property> getPropertiesMap(Class<?> type, BeanAccess bAccess) { - if (propertiesCache.containsKey(type)) { - return propertiesCache.get(type); - } - - Map<String, Property> properties = new LinkedHashMap<String, Property>(); -- boolean inaccessableFieldsExist = false; -- switch (bAccess) { -- case FIELD: -- for (Class<?> c = type; c != null; c = c.getSuperclass()) { -- for (Field field : c.getDeclaredFields()) { -- int modifiers = field.getModifiers(); -- if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) -- && !properties.containsKey(field.getName())) { -- properties.put(field.getName(), new FieldProperty(field)); -- } -+ for (Class<?> c = type; c != null; c = c.getSuperclass()) { -+ for (Field field : c.getDeclaredFields()) { -+ int modifiers = field.getModifiers(); -+ if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) -+ && !properties.containsKey(field.getName())) { -+ properties.put(field.getName(), new FieldProperty(field)); - } - } -- break; -- default: -- // add JavaBean properties -- for (PropertyDescriptor property : Introspector.getBeanInfo(type) -- .getPropertyDescriptors()) { -- Method readMethod = property.getReadMethod(); -- if (readMethod == null || !readMethod.getName().equals("getClass")) { -- properties.put(property.getName(), new MethodProperty(property)); -- } -- } -+ } +@@ -65,47 +60,14 @@ public class PropertyUtils { + } -- // add public fields -- for (Class<?> c = type; c != null; c = c.getSuperclass()) { -- for (Field field : c.getDeclaredFields()) { -- int modifiers = field.getModifiers(); -- if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { -- if (Modifier.isPublic(modifiers)) { -- properties.put(field.getName(), new FieldProperty(field)); -- } else { -- inaccessableFieldsExist = true; -- } -- } -- } -- } -- break; + Map<String, Property> properties = new LinkedHashMap<String, Property>(); +- boolean inaccessableFieldsExist = false; +- if (bAccess == BeanAccess.FIELD) { +- for (Class<?> c = type; c != null; c = c.getSuperclass()) { ++ for (Class<?> c = type; c != null; c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { +- int modifiers = field.getModifiers(); +- if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) +- && !properties.containsKey(field.getName())) { +- properties.put(field.getName(), new FieldProperty(field)); +- } - } -- if (properties.isEmpty() && inaccessableFieldsExist) { -- throw new YAMLException("No JavaBean properties found in " + type.getName()); +- } +- } else {// add JavaBean properties +- try { +- for (PropertyDescriptor property : Introspector.getBeanInfo(type) +- .getPropertyDescriptors()) { +- Method readMethod = property.getReadMethod(); +- if ((readMethod == null || !readMethod.getName().equals("getClass")) +- && !isTransient(property)) { +- properties.put(property.getName(), new MethodProperty(property)); +- } - } - propertiesCache.put(type, properties); - return properties; - } - -- public Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException { -+ public Set<Property> getProperties(Class<? extends Object> type) { - return getProperties(type, beanAccess); - } - -- public Set<Property> getProperties(Class<? extends Object> type, BeanAccess bAccess) -- throws IntrospectionException { -+ public Set<Property> getProperties(Class<? extends Object> type, BeanAccess bAccess) { - if (readableProperties.containsKey(type)) { - return readableProperties.get(type); - } -@@ -103,8 +66,7 @@ - return properties; - } - -- protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) -- throws IntrospectionException { -+ protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) { - Set<Property> properties = new TreeSet<Property>(); - Collection<Property> props = getPropertiesMap(type, bAccess).values(); - for (Property property : props) { -@@ -115,13 +77,11 @@ - return properties; +- } catch (IntrospectionException e) { +- throw new YAMLException(e); +- } +- +- // add public fields +- for (Class<?> c = type; c != null; c = c.getSuperclass()) { +- for (Field field : c.getDeclaredFields()) { +- int modifiers = field.getModifiers(); +- if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { +- if (Modifier.isPublic(modifiers)) { +- properties.put(field.getName(), new FieldProperty(field)); +- } else { +- inaccessableFieldsExist = true; +- } +- } +- } +- } +- } +- if (properties.isEmpty() && inaccessableFieldsExist) { +- throw new YAMLException("No JavaBean properties found in " + type.getName()); ++ int modifiers = field.getModifiers(); ++ if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) ++ && !properties.containsKey(field.getName())) { ++ properties.put(field.getName(), new FieldProperty(field)); ++ } ++ } } + propertiesCache.put(type, properties); + return properties; +@@ -113,10 +75,6 @@ public class PropertyUtils { -- public Property getProperty(Class<? extends Object> type, String name) -- throws IntrospectionException { -+ public Property getProperty(Class<? extends Object> type, String name) { - return getProperty(type, name, beanAccess); - } + private static final String TRANSIENT = "transient"; -- public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess) -- throws IntrospectionException { -+ public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess) { - Map<String, Property> properties = getPropertiesMap(type, bAccess); - Property property = properties.get(name); - if (property == null || !property.isWritable()) { +- private boolean isTransient(FeatureDescriptor fd) { +- return Boolean.TRUE.equals(fd.getValue(TRANSIENT)); +- } +- + public Set<Property> getProperties(Class<? extends Object> type) { + return getProperties(type, beanAccess); + } diff --git a/src/patches/android/Representer.patch b/src/patches/android/Representer.patch deleted file mode 100644 index 187853ea..00000000 --- a/src/patches/android/Representer.patch +++ /dev/null @@ -1,44 +0,0 @@ -# HG changeset patch -# Parent 44449b0d7ff73bbda13c28f2ebd4e8257c67a181 -diff --git a/src/main/java/org/yaml/snakeyaml/representer/Representer.java b/src/main/java/org/yaml/snakeyaml/representer/Representer.java ---- a/src/main/java/org/yaml/snakeyaml/representer/Representer.java -+++ b/src/main/java/org/yaml/snakeyaml/representer/Representer.java -@@ -15,7 +15,6 @@ - */ - package org.yaml.snakeyaml.representer; - --import java.beans.IntrospectionException; - import java.util.ArrayList; - import java.util.Arrays; - import java.util.Iterator; -@@ -24,7 +23,6 @@ - import java.util.Set; - - import org.yaml.snakeyaml.DumperOptions.FlowStyle; --import org.yaml.snakeyaml.error.YAMLException; - import org.yaml.snakeyaml.introspector.Property; - import org.yaml.snakeyaml.nodes.MappingNode; - import org.yaml.snakeyaml.nodes.Node; -@@ -45,11 +43,7 @@ - - protected class RepresentJavaBean implements Represent { - public Node representData(Object data) { -- try { -- return representJavaBean(getProperties(data.getClass()), data); -- } catch (IntrospectionException e) { -- throw new YAMLException(e); -- } -+ return representJavaBean(getProperties(data.getClass()), data); - } - } - -@@ -233,8 +227,7 @@ - * - JavaBean to inspect the properties - * @return properties to serialise - */ -- protected Set<Property> getProperties(Class<? extends Object> type) -- throws IntrospectionException { -+ protected Set<Property> getProperties(Class<? extends Object> type) { - return getPropertyUtils().getProperties(type); - } - } diff --git a/src/test/java/biz/source_code/base64Coder/Base64CoderTest.java b/src/test/java/biz/source_code/base64Coder/Base64CoderTest.java index 60f6d845..295eb729 100644 --- a/src/test/java/biz/source_code/base64Coder/Base64CoderTest.java +++ b/src/test/java/biz/source_code/base64Coder/Base64CoderTest.java @@ -1,73 +1,69 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package biz.source_code.base64Coder; import java.io.UnsupportedEncodingException; - +import java.nio.charset.StandardCharsets; import junit.framework.TestCase; - import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; public class Base64CoderTest extends TestCase { - public void testDecode() throws UnsupportedEncodingException { - check("Aladdin:open sesame", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); - check("a", "YQ=="); - check("aa", "YWE="); - check("a=", "YT0="); - check("", ""); - } + public void testDecode() throws UnsupportedEncodingException { + check("Aladdin:open sesame", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); + check("a", "YQ=="); + check("aa", "YWE="); + check("a=", "YT0="); + check("", ""); + } - public void testFailure1() throws UnsupportedEncodingException { - try { - Base64Coder.decode("YQ=".toCharArray()); - fail(); - } catch (Exception e) { - assertEquals("Length of Base64 encoded input string is not a multiple of 4.", - e.getMessage()); - } + public void testFailure1() throws UnsupportedEncodingException { + try { + Base64Coder.decode("YQ=".toCharArray()); + fail(); + } catch (Exception e) { + assertEquals("Length of Base64 encoded input string is not a multiple of 4.", e.getMessage()); } + } - public void testFailure2() throws UnsupportedEncodingException { - checkInvalid("\tWE="); - checkInvalid("Y\tE="); - checkInvalid("YW\t="); - checkInvalid("YWE\t"); - // - checkInvalid("ยฉWE="); - checkInvalid("YยฉE="); - checkInvalid("YWยฉ="); - checkInvalid("YWEยฉ"); - } + public void testFailure2() throws UnsupportedEncodingException { + checkInvalid("\tWE="); + checkInvalid("Y\tE="); + checkInvalid("YW\t="); + checkInvalid("YWE\t"); + // + checkInvalid("ยฉWE="); + checkInvalid("YยฉE="); + checkInvalid("YWยฉ="); + checkInvalid("YWEยฉ"); + } - private void checkInvalid(String encoded) { - try { - Base64Coder.decode(encoded.toCharArray()); - fail("Illegal chanracter."); - } catch (Exception e) { - assertEquals("Illegal character in Base64 encoded data.", e.getMessage()); - } + private void checkInvalid(String encoded) { + try { + Base64Coder.decode(encoded.toCharArray()); + fail("Illegal chanracter."); + } catch (Exception e) { + assertEquals("Illegal character in Base64 encoded data.", e.getMessage()); } + } - private void check(String text, String encoded) throws UnsupportedEncodingException { - char[] s1 = Base64Coder.encode(text.getBytes("UTF-8")); - String t1 = new String(s1); - assertEquals(encoded, t1); - byte[] s2 = Base64Coder.decode(encoded.toCharArray()); - String t2 = new String(s2, "UTF-8"); - assertEquals(text, t2); - } + private void check(String text, String encoded) throws UnsupportedEncodingException { + char[] s1 = Base64Coder.encode(text.getBytes(StandardCharsets.UTF_8)); + String t1 = new String(s1); + assertEquals(encoded, t1); + byte[] s2 = Base64Coder.decode(encoded.toCharArray()); + String t2 = new String(s2, StandardCharsets.UTF_8); + assertEquals(text, t2); + } } diff --git a/src/test/java/examples/AnyObjectExampleTest.java b/src/test/java/examples/AnyObjectExampleTest.java index 10ca00c7..6c03fea8 100644 --- a/src/test/java/examples/AnyObjectExampleTest.java +++ b/src/test/java/examples/AnyObjectExampleTest.java @@ -1,59 +1,56 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class AnyObjectExampleTest extends TestCase { - @SuppressWarnings("unchecked") - public void testLoad() { - String doc = Util.getLocalResource("examples/any-object-example.yaml"); - Yaml yaml = new Yaml(); - Map<String, Object> object = (Map<String, Object>) yaml.load(doc); - assertEquals(6, object.size()); - assertEquals("[null, null]", object.get("none").toString()); - List<?> list1 = (List<?>) object.get("none"); - assertEquals(2, list1.size()); - for (Object object2 : list1) { - assertNull(object2); - } - // - assertEquals("[true, false, true, false]", object.get("bool").toString()); - assertEquals(4, ((List<?>) object.get("bool")).size()); - // - assertEquals(new Integer(42), object.get("int")); - assertEquals(new Double(3.14159), object.get("float")); - // - assertEquals("[LITE, RES_ACID, SUS_DEXT]", object.get("list").toString()); - List<?> list2 = (List<?>) object.get("list"); - assertEquals(3, list2.size()); - for (Object object2 : list2) { - assertEquals(object2.toString(), object2.toString().toUpperCase()); - } - // - assertEquals("{hp=13, sp=5}", object.get("dict").toString()); - Map<String, Integer> map = (Map<String, Integer>) object.get("dict"); - assertEquals(2, map.keySet().size()); - assertEquals(new Integer(13), map.get("hp")); - assertEquals(new Integer(5), map.get("sp")); + + @SuppressWarnings("unchecked") + public void testLoad() { + String doc = Util.getLocalResource("examples/any-object-example.yaml"); + Yaml yaml = new Yaml(); + Map<String, Object> object = yaml.load(doc); + assertEquals(6, object.size()); + assertEquals("[null, null]", object.get("none").toString()); + List<?> list1 = (List<?>) object.get("none"); + assertEquals(2, list1.size()); + for (Object object2 : list1) { + assertNull(object2); + } + // + assertEquals("[true, false, true, false]", object.get("bool").toString()); + assertEquals(4, ((List<?>) object.get("bool")).size()); + // + assertEquals(Integer.valueOf(42), object.get("int")); + assertEquals(Double.valueOf(3.14159), object.get("float")); + // + assertEquals("[LITE, RES_ACID, SUS_DEXT]", object.get("list").toString()); + List<?> list2 = (List<?>) object.get("list"); + assertEquals(3, list2.size()); + for (Object object2 : list2) { + assertEquals(object2.toString(), object2.toString().toUpperCase()); } + // + assertEquals("{hp=13, sp=5}", object.get("dict").toString()); + Map<String, Integer> map = (Map<String, Integer>) object.get("dict"); + assertEquals(2, map.keySet().size()); + assertEquals(Integer.valueOf(13), map.get("hp")); + assertEquals(Integer.valueOf(5), map.get("sp")); + } } diff --git a/src/test/java/examples/CollectionStyleTest.java b/src/test/java/examples/CollectionStyleTest.java index 795f9d3a..9be16250 100644 --- a/src/test/java/examples/CollectionStyleTest.java +++ b/src/test/java/examples/CollectionStyleTest.java @@ -1,37 +1,35 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class CollectionStyleTest extends TestCase { - public void testNestedStyle() { - Yaml yaml = new Yaml(); - String document = " a: 1\n b:\n c: 3\n d: 4\n"; - assertEquals("a: 1\nb: {c: 3, d: 4}\n", yaml.dump(yaml.load(document))); - } - public void testNestedStyle2() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String document = " a: 1\n b:\n c: 3\n d: 4\n"; - assertEquals("a: 1\nb:\n c: 3\n d: 4\n", yaml.dump(yaml.load(document))); - } + public void testNestedStyle() { + Yaml yaml = new Yaml(); + String document = " a: 1\n b:\n c: 3\n d: 4\n"; + assertEquals("a: 1\nb: {c: 3, d: 4}\n", yaml.dump(yaml.load(document))); + } + + public void testNestedStyle2() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String document = " a: 1\n b:\n c: 3\n d: 4\n"; + assertEquals("a: 1\nb:\n c: 3\n d: 4\n", yaml.dump(yaml.load(document))); + } } diff --git a/src/test/java/examples/CustomBeanResolverTest.java b/src/test/java/examples/CustomBeanResolverTest.java index ce59ab40..2e1dbd49 100644 --- a/src/test/java/examples/CustomBeanResolverTest.java +++ b/src/test/java/examples/CustomBeanResolverTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.math.BigDecimal; import java.util.regex.Pattern; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.Node; @@ -30,54 +26,57 @@ import org.yaml.snakeyaml.nodes.ScalarNode; * http://code.google.com/p/snakeyaml/issues/detail?id=75 */ public class CustomBeanResolverTest extends TestCase { - private final Pattern CUSTOM_PATTERN = Pattern.compile("\\d+%"); - public void testOnlyBigDecimal() { - Yaml yaml = new Yaml(new BigBeanConstructor()); - Foo foo = (Foo) yaml.load("bar: 50\nbaz: 35%\nbas: 1250"); - assertEquals(50.0, foo.bar); - assertEquals("0.35", foo.baz.toString()); - assertEquals("1250", foo.bas); - } + private final Pattern CUSTOM_PATTERN = Pattern.compile("\\d+%"); + + public void testOnlyBigDecimal() { + Yaml yaml = new Yaml(new BigBeanConstructor()); + Foo foo = yaml.load("bar: 50\nbaz: 35%\nbas: 1250"); + assertEquals(50.0, foo.bar); + assertEquals("0.35", foo.baz.toString()); + assertEquals("1250", foo.bas); + } + + public void testPrimitive() { + Yaml yaml = new Yaml(new BigBeanConstructor()); + Foo foo = yaml.load("bar: 50%\nbaz: 35%\nbas: 1250%\nbaw: 35"); + assertEquals(0.5, foo.bar); + assertEquals("0.35", foo.baz.toString()); + assertEquals("1250%", foo.bas); + assertEquals("35", foo.baw.toString()); + } - public void testPrimitive() { - Yaml yaml = new Yaml(new BigBeanConstructor()); - Foo foo = (Foo) yaml.load("bar: 50%\nbaz: 35%\nbas: 1250%\nbaw: 35"); - assertEquals(0.5, foo.bar); - assertEquals("0.35", foo.baz.toString()); - assertEquals("1250%", foo.bas); - assertEquals("35", foo.baw.toString()); + class BigBeanConstructor extends Constructor { + + public BigBeanConstructor() { + super(Foo.class); + yamlClassConstructors.put(NodeId.scalar, new ConstructBig()); } - class BigBeanConstructor extends Constructor { - public BigBeanConstructor() { - super(Foo.class); - yamlClassConstructors.put(NodeId.scalar, new ConstructBig()); - } + private class ConstructBig extends ConstructScalar { - private class ConstructBig extends ConstructScalar { - public Object construct(Node node) { - if (node.getType().equals(BigDecimal.class)) { - String val = (String) constructScalar((ScalarNode) node); - if (CUSTOM_PATTERN.matcher(val).matches()) { - return new BigDecimal(val.substring(0, val.length() - 1)) - .divide(new BigDecimal(100)); - } - } else if (node.getType().isAssignableFrom(double.class)) { - String val = (String) constructScalar((ScalarNode) node); - if (CUSTOM_PATTERN.matcher(val).matches()) { - return new Double(val.substring(0, val.length() - 1)) / 100; - } - } - return super.construct(node); - } + public Object construct(Node node) { + if (node.getType().equals(BigDecimal.class)) { + String val = constructScalar((ScalarNode) node); + if (CUSTOM_PATTERN.matcher(val).matches()) { + return new BigDecimal(val.substring(0, val.length() - 1)).divide(new BigDecimal(100)); + } + } else if (node.getType().isAssignableFrom(double.class)) { + String val = constructScalar((ScalarNode) node); + if (CUSTOM_PATTERN.matcher(val).matches()) { + return Double.valueOf(val.substring(0, val.length() - 1)) / 100; + } } + return super.construct(node); + } } + } - public static class Foo { - public double bar = 0; - public BigDecimal baz; - public BigDecimal baw; - public String bas; - } + public static class Foo { + + public double bar = 0; + public BigDecimal baz; + public BigDecimal baw; + public String bas; + } } diff --git a/src/test/java/examples/CustomConstructor.java b/src/test/java/examples/CustomConstructor.java index 1d61a0a0..bf742b6f 100644 --- a/src/test/java/examples/CustomConstructor.java +++ b/src/test/java/examples/CustomConstructor.java @@ -1,34 +1,31 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.LinkedList; import java.util.List; - import org.yaml.snakeyaml.Invoice; import org.yaml.snakeyaml.constructor.Constructor; public class CustomConstructor extends Constructor { - public CustomConstructor() { - super(Invoice.class); - } + public CustomConstructor() { + super(Invoice.class); + } - @Override - protected List<Object> createDefaultList(int initSize) { - return new LinkedList<Object>(); - } -}
\ No newline at end of file + @Override + protected List<Object> createDefaultList(int initSize) { + return new LinkedList<Object>(); + } +} diff --git a/src/test/java/examples/CustomImplicitResolverTest.java b/src/test/java/examples/CustomImplicitResolverTest.java index c5c03150..b7217e5e 100644 --- a/src/test/java/examples/CustomImplicitResolverTest.java +++ b/src/test/java/examples/CustomImplicitResolverTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.math.BigDecimal; import java.util.Map; import java.util.regex.Pattern; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.SafeConstructor; @@ -33,40 +29,42 @@ import org.yaml.snakeyaml.nodes.Tag; * http://code.google.com/p/snakeyaml/issues/detail?id=75 */ public class CustomImplicitResolverTest extends TestCase { - private final Tag CUSTOM_TAG = new Tag("!BigDecimalDividedBy100"); - private final Pattern CUSTOM_PATTERN = Pattern.compile("\\d+%"); - @SuppressWarnings("unchecked") - public void testImplicit() { - Yaml yaml = new Yaml(new BigConstructor()); - yaml.addImplicitResolver(CUSTOM_TAG, CUSTOM_PATTERN, "-0123456789"); - Map<String, Object> obj = (Map<String, Object>) yaml.load("bar: 50%"); - assertEquals("0.5", obj.get("bar").toString()); - assertEquals(BigDecimal.class, obj.get("bar").getClass()); + private final Tag CUSTOM_TAG = new Tag("!BigDecimalDividedBy100"); + private final Pattern CUSTOM_PATTERN = Pattern.compile("\\d+%"); + + @SuppressWarnings("unchecked") + public void testImplicit() { + Yaml yaml = new Yaml(new BigConstructor()); + yaml.addImplicitResolver(CUSTOM_TAG, CUSTOM_PATTERN, "-0123456789"); + Map<String, Object> obj = yaml.load("bar: 50%"); + assertEquals("0.5", obj.get("bar").toString()); + assertEquals(BigDecimal.class, obj.get("bar").getClass()); + } + + public void testImplicitFailure() { + Yaml yaml = new Yaml(new BigConstructor()); + yaml.addImplicitResolver(CUSTOM_TAG, Pattern.compile("\\d+%"), "-0123456789"); + try { + yaml.load("bar: !!float 50%"); + fail("Both implicit and explicit are present."); + } catch (NumberFormatException e) { + assertEquals("For input string: \"50%\"", e.getMessage()); } + } + + class BigConstructor extends SafeConstructor { - public void testImplicitFailure() { - Yaml yaml = new Yaml(new BigConstructor()); - yaml.addImplicitResolver(CUSTOM_TAG, Pattern.compile("\\d+%"), "-0123456789"); - try { - yaml.load("bar: !!float 50%"); - fail("Both implicit and explicit are present."); - } catch (NumberFormatException e) { - assertEquals("For input string: \"50%\"", e.getMessage()); - } + public BigConstructor() { + this.yamlConstructors.put(CUSTOM_TAG, new ConstructBig()); } - class BigConstructor extends SafeConstructor { - public BigConstructor() { - this.yamlConstructors.put(CUSTOM_TAG, new ConstructBig()); - } + private class ConstructBig extends AbstractConstruct { - private class ConstructBig extends AbstractConstruct { - public Object construct(Node node) { - String val = (String) constructScalar((ScalarNode) node); - return new BigDecimal(val.substring(0, val.length() - 1)) - .divide(new BigDecimal(100)); - } - } + public Object construct(Node node) { + String val = constructScalar((ScalarNode) node); + return new BigDecimal(val.substring(0, val.length() - 1)).divide(new BigDecimal(100)); + } } + } } diff --git a/src/test/java/examples/CustomJavaObjectWithBinaryStringTest.java b/src/test/java/examples/CustomJavaObjectWithBinaryStringTest.java index 755be997..e7a9ffde 100644 --- a/src/test/java/examples/CustomJavaObjectWithBinaryStringTest.java +++ b/src/test/java/examples/CustomJavaObjectWithBinaryStringTest.java @@ -1,80 +1,81 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.io.StringReader; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class CustomJavaObjectWithBinaryStringTest extends TestCase { - public static class Pojo { - private String data; - public Pojo() { - } + public static class Pojo { - public Pojo(String data) { - this.data = data; - } + private String data; - public String getData() { - return data; - } + public Pojo() {} - public void setData(String data) { - this.data = data; - } + public Pojo(String data) { + this.data = data; + } - @Override public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - return result; - } + public String getData() { + return data; + } - @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Pojo other = (Pojo) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - return true; - } + public void setData(String data) { + this.data = data; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((data == null) ? 0 : data.hashCode()); + return result; } - public void testDump() { - Yaml yaml = new Yaml(); - Pojo expected = new Pojo(new String(new byte[] { 13, 14, 15, 16 })); - String output = yaml.dump(expected); + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Pojo other = (Pojo) obj; + if (data == null) { + return other.data == null; + } else { + return data.equals(other.data); + } + } - assertTrue(output.contains("data: !!binary |-")); - assertTrue(output.contains("DQ4PEA==")); + } - Pojo actual = (Pojo) yaml.load(new StringReader(output)); - assertEquals(expected, actual); - } + public void testDump() { + Yaml yaml = new Yaml(); + Pojo expected = new Pojo(new String(new byte[] {13, 14, 15, 16})); + String output = yaml.dump(expected); + + assertTrue(output.contains("data: !!binary |-")); + assertTrue(output.contains("DQ4PEA==")); + + Pojo actual = yaml.load(new StringReader(output)); + assertEquals(expected, actual); + } } diff --git a/src/test/java/examples/CustomListExampleTest.java b/src/test/java/examples/CustomListExampleTest.java index 11c98ca2..a703dafa 100644 --- a/src/test/java/examples/CustomListExampleTest.java +++ b/src/test/java/examples/CustomListExampleTest.java @@ -1,40 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.LinkedList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class CustomListExampleTest extends TestCase { - @SuppressWarnings("unchecked") - public void testList() { - Yaml yaml = new Yaml(new CustomConstructor()); - List<Integer> data = (List<Integer>) yaml.load("[1, 2, 3]"); - assertTrue(data instanceof LinkedList); - } - class CustomConstructor extends Constructor { - @Override - protected List<Object> createDefaultList(int initSize) { - return new LinkedList<Object>(); - } + @SuppressWarnings("unchecked") + public void testList() { + Yaml yaml = new Yaml(new CustomConstructor()); + List<Integer> data = yaml.load("[1, 2, 3]"); + assertTrue(data instanceof LinkedList); + } + + class CustomConstructor extends Constructor { + + @Override + protected List<Object> createDefaultList(int initSize) { + return new LinkedList<Object>(); } + } } diff --git a/src/test/java/examples/CustomMapExampleTest.java b/src/test/java/examples/CustomMapExampleTest.java index 95fe7fc2..5770896e 100644 --- a/src/test/java/examples/CustomMapExampleTest.java +++ b/src/test/java/examples/CustomMapExampleTest.java @@ -1,46 +1,43 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class CustomMapExampleTest extends TestCase { - public void testMap() { - Yaml yaml = new Yaml(new CustomConstructor()); - @SuppressWarnings("unchecked") - Map<Integer, String> data = (Map<Integer, String>) yaml - .load("{2: '222', 1: '111', 3: '333'}"); - assertTrue(data instanceof TreeMap); - Object[] keys = data.keySet().toArray(); - // must be sorted - assertEquals(new Integer(1), keys[0]); - assertEquals(new Integer(2), keys[1]); - assertEquals(new Integer(3), keys[2]); - } - class CustomConstructor extends Constructor { - @Override - protected Map<Object, Object> createDefaultMap() { - return new TreeMap<Object, Object>(); - } + public void testMap() { + Yaml yaml = new Yaml(new CustomConstructor()); + @SuppressWarnings("unchecked") + Map<Integer, String> data = yaml.load("{2: '222', 1: '111', 3: '333'}"); + assertTrue(data instanceof TreeMap); + Object[] keys = data.keySet().toArray(); + // must be sorted + assertEquals(Integer.valueOf(1), keys[0]); + assertEquals(Integer.valueOf(2), keys[1]); + assertEquals(Integer.valueOf(3), keys[2]); + } + + class CustomConstructor extends Constructor { + + @Override + protected Map<Object, Object> createDefaultMap(int initSize) { + return new TreeMap<Object, Object>(); } + } } diff --git a/src/test/java/examples/CustomNullConstructorTest.java b/src/test/java/examples/CustomNullConstructorTest.java new file mode 100644 index 00000000..f99d260a --- /dev/null +++ b/src/test/java/examples/CustomNullConstructorTest.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.AbstractConstruct; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.Tag; + +/** + * Issue 1 for snakeyaml-engine + * https://bitbucket.org/snakeyaml/snakeyaml-engine/issues/1/null-tag-constructor-not-called-when + */ +public class CustomNullConstructorTest extends TestCase { + + public void testEmpty() { + Yaml yaml = new Yaml(new NullConstructor()); + assertEquals(Integer.valueOf(1), yaml.load("")); + } + + public void testNull() { + Yaml yaml = new Yaml(new NullConstructor()); + assertEquals(Integer.valueOf(1), yaml.load("null")); + } + + public void testNullTag() { + Yaml yaml = new Yaml(new NullConstructor()); + assertEquals(Integer.valueOf(1), yaml.load("!!null null")); + } + + class NullConstructor extends SafeConstructor { + + public NullConstructor() { + this.yamlConstructors.put(Tag.NULL, new ConstructNull()); + } + + private class ConstructNull extends AbstractConstruct { + + public Object construct(Node node) { + return 1; + } + } + } +} diff --git a/src/test/java/examples/Dice.java b/src/test/java/examples/Dice.java index 62e92624..f3108977 100644 --- a/src/test/java/examples/Dice.java +++ b/src/test/java/examples/Dice.java @@ -1,53 +1,52 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; public class Dice { - private Integer a; - private Integer b; - public Dice(Integer a, Integer b) { - super(); - this.a = a; - this.b = b; - } + private final Integer a; + private final Integer b; - public Integer getA() { - return a; - } + public Dice(Integer a, Integer b) { + super(); + this.a = a; + this.b = b; + } - public Integer getB() { - return b; - } + public Integer getA() { + return a; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Dice) { - return toString().equals(obj.toString()); - } - return false; - } + public Integer getB() { + return b; + } - @Override - public int hashCode() { - return toString().hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Dice) { + return toString().equals(obj.toString()); } + return false; + } - @Override - public String toString() { - return "Dice " + a + "d" + b; - } + @Override + public int hashCode() { + return toString().hashCode(); + } + + @Override + public String toString() { + return "Dice " + a + "d" + b; + } } diff --git a/src/test/java/examples/DiceExampleTest.java b/src/test/java/examples/DiceExampleTest.java index c0d0b63a..b6bba717 100644 --- a/src/test/java/examples/DiceExampleTest.java +++ b/src/test/java/examples/DiceExampleTest.java @@ -1,31 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.regex.Pattern; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; import org.yaml.snakeyaml.nodes.Tag; @@ -33,129 +29,135 @@ import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; public class DiceExampleTest extends TestCase { - public void testRepresenter() { - Dice dice = new Dice(3, 6); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - String output = yaml.dump(dice); - assertEquals("!!examples.Dice {a: 3, b: 6}\n", output); - } - public void testDiceRepresenter() { - Dice dice = new Dice(3, 6); - Map<String, Dice> data = new HashMap<String, Dice>(); - data.put("gold", dice); - Yaml yaml = new Yaml(new DiceRepresenter(), new DumperOptions()); - String output = yaml.dump(data); - assertEquals("{gold: !dice '3d6'}\n", output); + public void testRepresenter() { + Dice dice = new Dice(3, 6); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + String output = yaml.dump(dice); + assertEquals("!!examples.Dice {a: 3, b: 6}\n", output); + } + + public void testDiceRepresenter() { + Dice dice = new Dice(3, 6); + Map<String, Dice> data = new HashMap<String, Dice>(); + data.put("gold", dice); + Yaml yaml = new Yaml(new DiceRepresenter(), new DumperOptions()); + String output = yaml.dump(data); + assertEquals("{gold: !dice '3d6'}\n", output); + } + + class DiceRepresenter extends Representer { + + public DiceRepresenter() { + this.representers.put(Dice.class, new RepresentDice()); } - class DiceRepresenter extends Representer { - public DiceRepresenter() { - this.representers.put(Dice.class, new RepresentDice()); - } - - private class RepresentDice implements Represent { - public Node representData(Object data) { - Dice dice = (Dice) data; - String value = dice.getA() + "d" + dice.getB(); - return representScalar(new Tag("!dice"), value); - } - } - } + private class RepresentDice implements Represent { - class DiceConstructor extends Constructor { - public DiceConstructor() { - this.yamlConstructors.put(new Tag("!dice"), new ConstructDice()); - } - - private class ConstructDice extends AbstractConstruct { - public Object construct(Node node) { - String val = (String) constructScalar((ScalarNode) node); - int position = val.indexOf('d'); - Integer a = new Integer(val.substring(0, position)); - Integer b = new Integer(val.substring(position + 1)); - return new Dice(a, b); - } - } + public Node representData(Object data) { + Dice dice = (Dice) data; + String value = dice.getA() + "d" + dice.getB(); + return representScalar(new Tag("!dice"), value); + } } + } - @SuppressWarnings("unchecked") - public void testConstructor() { - Yaml yaml = new Yaml(new DiceConstructor()); - Object data = yaml.load("{initial hit points: !dice '8d4'}"); - Map<String, Dice> map = (Map<String, Dice>) data; - assertEquals(new Dice(8, 4), map.get("initial hit points")); - } + class DiceConstructor extends Constructor { - // the tag must start with a digit - @SuppressWarnings("unchecked") - public void testImplicitResolver() { - Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter()); - // the tag must start with a digit - yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), "123456789"); - // dump - Map<String, Dice> treasure = new HashMap<String, Dice>(); - treasure.put("treasure", new Dice(10, 20)); - String output = yaml.dump(treasure); - assertEquals("{treasure: 10d20}\n", output); - // load - Object data = yaml.load("{damage: 5d10}"); - Map<String, Dice> map = (Map<String, Dice>) data; - assertEquals(new Dice(5, 10), map.get("damage")); + public DiceConstructor() { + this.yamlConstructors.put(new Tag("!dice"), new ConstructDice()); } + private class ConstructDice extends AbstractConstruct { + + public Object construct(Node node) { + String val = constructScalar((ScalarNode) node); + int position = val.indexOf('d'); + Integer a = Integer.valueOf(val.substring(0, position)); + Integer b = Integer.valueOf(val.substring(position + 1)); + return new Dice(a, b); + } + } + } + + @SuppressWarnings("unchecked") + public void testConstructor() { + Yaml yaml = new Yaml(new DiceConstructor()); + Object data = yaml.load("{initial hit points: !dice '8d4'}"); + Map<String, Dice> map = (Map<String, Dice>) data; + assertEquals(new Dice(8, 4), map.get("initial hit points")); + } + + // the tag must start with a digit + @SuppressWarnings("unchecked") + public void testImplicitResolver() { + Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter()); + // the tag must start with a digit + yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), "123456789"); + // dump + Map<String, Dice> treasure = new HashMap<String, Dice>(); + treasure.put("treasure", new Dice(10, 20)); + String output = yaml.dump(treasure); + assertEquals("{treasure: 10d20}\n", output); + // load + Object data = yaml.load("{damage: 5d10}"); + Map<String, Dice> map = (Map<String, Dice>) data; + assertEquals(new Dice(5, 10), map.get("damage")); + } + + // the tag may start with anything + @SuppressWarnings("unchecked") + public void testImplicitResolverWithNull() { + Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter()); // the tag may start with anything - @SuppressWarnings("unchecked") - public void testImplicitResolverWithNull() { - Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter()); - // the tag may start with anything - yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), null); - // dump - Map<String, Dice> treasure = new HashMap<String, Dice>(); - treasure.put("treasure", new Dice(10, 20)); - String output = yaml.dump(treasure); - assertEquals("{treasure: 10d20}\n", output); - // load - Object data = yaml.load("{damage: 5d10}"); - Map<String, Dice> map = (Map<String, Dice>) data; - assertEquals(new Dice(5, 10), map.get("damage")); + yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), null); + // dump + Map<String, Dice> treasure = new HashMap<String, Dice>(); + treasure.put("treasure", new Dice(10, 20)); + String output = yaml.dump(treasure); + assertEquals("{treasure: 10d20}\n", output); + // load + Object data = yaml.load("{damage: 5d10}"); + Map<String, Dice> map = (Map<String, Dice>) data; + assertEquals(new Dice(5, 10), map.get("damage")); + } + + static class DiceBean { + + public Dice treasure; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DiceBean)) { + return false; + } + + DiceBean diceBean = (DiceBean) o; + return Objects.equals(treasure, diceBean.treasure); } - static class DiceBean { - public Dice treasure; - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof DiceBean)) - return false; - - DiceBean diceBean = (DiceBean) o; - if (treasure != null ? !treasure.equals(diceBean.treasure) : diceBean.treasure != null) - return false; - return true; - } - - @Override - public int hashCode() { - return treasure != null ? treasure.hashCode() : 0; - } + @Override + public int hashCode() { + return treasure != null ? treasure.hashCode() : 0; } + } - public void testImplicitResolverJavaBean() { - Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter()); - // the tag must start with a digit - yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), "123456789"); - // dump - DiceBean bean = new DiceBean(); - bean.treasure = new Dice(10, 20); - String output = yaml.dump(bean); - assertEquals("!!examples.DiceExampleTest$DiceBean {treasure: 10d20}\n", output); - // load - Object loaded = yaml.load(output); - assertEquals(loaded, bean); - } + public void testImplicitResolverJavaBean() { + Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter()); + // the tag must start with a digit + yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), "123456789"); + // dump + DiceBean bean = new DiceBean(); + bean.treasure = new Dice(10, 20); + String output = yaml.dump(bean); + assertEquals("!!examples.DiceExampleTest$DiceBean {treasure: 10d20}\n", output); + // load + Object loaded = yaml.load(output); + assertEquals(loaded, bean); + } } diff --git a/src/test/java/examples/DumpExampleTest.java b/src/test/java/examples/DumpExampleTest.java index 358c55c8..952acf7f 100644 --- a/src/test/java/examples/DumpExampleTest.java +++ b/src/test/java/examples/DumpExampleTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; @@ -20,116 +18,115 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class DumpExampleTest extends TestCase { - public void testDump() { - Map<String, Object> data = new HashMap<String, Object>(); - data.put("name", "Silenthand Olleander"); - data.put("race", "Human"); - data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" }); - Yaml yaml = new Yaml(); - String output = yaml.dump(data); - assertTrue(output.contains("name: Silenthand Olleander")); - assertTrue(output.contains("race: Human")); - assertTrue(output.contains("traits: [ONE_HAND, ONE_EYE]")); - } - public void testDumpWriter() { - Map<String, Object> data = new HashMap<String, Object>(); - data.put("name", "Silenthand Olleander"); - data.put("race", "Human"); - data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" }); - Yaml yaml = new Yaml(); - StringWriter writer = new StringWriter(); - yaml.dump(data, writer); - assertTrue(writer.toString().contains("name: Silenthand Olleander")); - assertTrue(writer.toString().contains("race: Human")); - assertTrue(writer.toString().contains("traits: [ONE_HAND, ONE_EYE]")); - } + public void testDump() { + Map<String, Object> data = new HashMap<String, Object>(); + data.put("name", "Silenthand Olleander"); + data.put("race", "Human"); + data.put("traits", new String[] {"ONE_HAND", "ONE_EYE"}); + Yaml yaml = new Yaml(); + String output = yaml.dump(data); + assertTrue(output.contains("name: Silenthand Olleander")); + assertTrue(output.contains("race: Human")); + assertTrue(output.contains("traits: [ONE_HAND, ONE_EYE]")); + } - public void testDumpMany() { - List<Integer> docs = new ArrayList<Integer>(); - for (int i = 1; i < 4; i++) { - docs.add(i); - } - DumperOptions options = new DumperOptions(); - options.setExplicitStart(true); - Yaml yaml = new Yaml(options); - String result = yaml.dumpAll(docs.iterator()); - assertNotNull(result); - assertTrue(result.contains("--- 2")); - } + public void testDumpWriter() { + Map<String, Object> data = new HashMap<String, Object>(); + data.put("name", "Silenthand Olleander"); + data.put("race", "Human"); + data.put("traits", new String[] {"ONE_HAND", "ONE_EYE"}); + Yaml yaml = new Yaml(); + StringWriter writer = new StringWriter(); + yaml.dump(data, writer); + assertTrue(writer.toString().contains("name: Silenthand Olleander")); + assertTrue(writer.toString().contains("race: Human")); + assertTrue(writer.toString().contains("traits: [ONE_HAND, ONE_EYE]")); + } - public void testDumpCustomJavaClass() { - Hero hero = new Hero("Galain Ysseleg", -3, 2); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - String output = yaml.dump(hero); - assertEquals("!!examples.Hero {hp: -3, name: Galain Ysseleg, sp: 2}\n", output); + public void testDumpMany() { + List<Integer> docs = new ArrayList<Integer>(); + for (int i = 1; i < 4; i++) { + docs.add(i); } + DumperOptions options = new DumperOptions(); + options.setExplicitStart(true); + Yaml yaml = new Yaml(options); + String result = yaml.dumpAll(docs.iterator()); + assertNotNull(result); + assertTrue(result.contains("--- 2")); + } + + public void testDumpCustomJavaClass() { + Hero hero = new Hero("Galain Ysseleg", -3, 2); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + String output = yaml.dump(hero); + assertEquals("!!examples.Hero {hp: -3, name: Galain Ysseleg, sp: 2}\n", output); + } - public void testDumperOptions() { - List<Integer> data = new ArrayList<Integer>(); - for (int i = 0; i < 50; i++) { - data.add(i); - } - Yaml yaml = new Yaml(); - String output = yaml.dump(data); - assertTrue(output.contains("[0, 1, 2, 3, 4, 5, 6, 7, 8")); - // - DumperOptions options = new DumperOptions(); - options.setWidth(50); - options.setIndent(4); - yaml = new Yaml(options); - output = yaml.dump(data); - assertTrue(output.contains("1, 2")); + public void testDumperOptions() { + List<Integer> data = new ArrayList<Integer>(); + for (int i = 0; i < 50; i++) { + data.add(i); } + Yaml yaml = new Yaml(); + String output = yaml.dump(data); + assertTrue(output.contains("[0, 1, 2, 3, 4, 5, 6, 7, 8")); + // + DumperOptions options = new DumperOptions(); + options.setWidth(50); + options.setIndent(4); + yaml = new Yaml(options); + output = yaml.dump(data); + assertTrue(output.contains("1, 2")); + } - public void testDumperOptionsCanonical() { - List<Integer> data = new ArrayList<Integer>(); - for (int i = 0; i < 5; i++) { - data.add(i); - } - DumperOptions options = new DumperOptions(); - options.setCanonical(true); - Yaml yaml = new Yaml(options); - String output = yaml.dump(data); - assertTrue(output.contains("---")); - assertTrue(output.contains("!!seq [")); - assertTrue(output.contains("!!int \"3\",")); + public void testDumperOptionsCanonical() { + List<Integer> data = new ArrayList<Integer>(); + for (int i = 0; i < 5; i++) { + data.add(i); } + DumperOptions options = new DumperOptions(); + options.setCanonical(true); + Yaml yaml = new Yaml(options); + String output = yaml.dump(data); + assertTrue(output.contains("---")); + assertTrue(output.contains("!!seq [")); + assertTrue(output.contains("!!int \"3\",")); + } - public void testDumperOptionsFlowStyle() { - List<Integer> data = new ArrayList<Integer>(); - for (int i = 0; i < 5; i++) { - data.add(i); - } - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String output = yaml.dump(data); - assertTrue(output.contains("- 0\n")); - assertTrue(output.contains("- 1\n")); - assertTrue(output.contains("- 4\n")); + public void testDumperOptionsFlowStyle() { + List<Integer> data = new ArrayList<Integer>(); + for (int i = 0; i < 5; i++) { + data.add(i); } + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String output = yaml.dump(data); + assertTrue(output.contains("- 0\n")); + assertTrue(output.contains("- 1\n")); + assertTrue(output.contains("- 4\n")); + } - public void testDumperOptionsStyle() { - List<Integer> data = new ArrayList<Integer>(); - for (int i = 0; i < 5; i++) { - data.add(i); - } - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - Yaml yaml = new Yaml(options); - String output = yaml.dump(data); - assertTrue(output.contains("- !!int \"0\"")); - assertTrue(output.contains("- !!int \"1\"")); - assertTrue(output.contains("- !!int \"4\"")); + public void testDumperOptionsStyle() { + List<Integer> data = new ArrayList<Integer>(); + for (int i = 0; i < 5; i++) { + data.add(i); } + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + Yaml yaml = new Yaml(options); + String output = yaml.dump(data); + assertTrue(output.contains("- !!int \"0\"")); + assertTrue(output.contains("- !!int \"1\"")); + assertTrue(output.contains("- !!int \"4\"")); + } } diff --git a/src/test/java/examples/Hero.java b/src/test/java/examples/Hero.java index e309ed32..ded5f2bc 100644 --- a/src/test/java/examples/Hero.java +++ b/src/test/java/examples/Hero.java @@ -1,42 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; public class Hero { - private String name; - private Integer sp; - private Integer hp; - public Hero(String name, Integer hp, Integer sp) { - super(); - this.name = name; - this.sp = sp; - this.hp = hp; - } + private final String name; + private final Integer sp; + private final Integer hp; - public String getName() { - return name; - } + public Hero(String name, Integer hp, Integer sp) { + super(); + this.name = name; + this.sp = sp; + this.hp = hp; + } - public Integer getSp() { - return sp; - } + public String getName() { + return name; + } - public Integer getHp() { - return hp; - } + public Integer getSp() { + return sp; + } + + public Integer getHp() { + return hp; + } } diff --git a/src/test/java/examples/IgnoreTagsExampleTest.java b/src/test/java/examples/IgnoreTagsExampleTest.java index eb175eb3..36e308d0 100644 --- a/src/test/java/examples/IgnoreTagsExampleTest.java +++ b/src/test/java/examples/IgnoreTagsExampleTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; @@ -30,53 +26,56 @@ import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; public class IgnoreTagsExampleTest extends TestCase { - @SuppressWarnings("unchecked") - public void testLoad() { - String input = Util.getLocalResource("examples/unknown-tags-example.yaml"); - // System.out.println(input); - Yaml yaml = new Yaml(new MyConstructor()); - Map<String, Object> result = (Map<String, Object>) yaml.load(input); - // Check the result - assertNotNull(result); - assertEquals(3, result.size()); - assertEquals("123", result.get("aaa")); - // - List<Object> bbb = (List<Object>) result.get("bbb"); - assertEquals(2, bbb.size()); - assertEquals(new Integer(111), bbb.get(0)); - assertEquals("ddd", bbb.get(1)); - // - Map<String, Object> ccc = (Map<String, Object>) result.get("ccc"); - assertEquals(2, ccc.size()); - assertEquals(1.0, ccc.get("x")); - assertEquals(3.1416, ccc.get("y")); - } - private class MyConstructor extends Constructor { - private Construct original; + @SuppressWarnings("unchecked") + public void testLoad() { + String input = Util.getLocalResource("examples/unknown-tags-example.yaml"); + // System.out.println(input); + Yaml yaml = new Yaml(new MyConstructor()); + Map<String, Object> result = yaml.load(input); + // Check the result + assertNotNull(result); + assertEquals(3, result.size()); + assertEquals("123", result.get("aaa")); + // + List<Object> bbb = (List<Object>) result.get("bbb"); + assertEquals(2, bbb.size()); + assertEquals(Integer.valueOf(111), bbb.get(0)); + assertEquals("ddd", bbb.get(1)); + // + Map<String, Object> ccc = (Map<String, Object>) result.get("ccc"); + assertEquals(2, ccc.size()); + assertEquals(1.0, ccc.get("x")); + assertEquals(3.1416, ccc.get("y")); + } - public MyConstructor() { - original = this.yamlConstructors.get(null); - this.yamlConstructors.put(null, new IgnoringConstruct()); - } + private class MyConstructor extends Constructor { + + private final Construct original; + + public MyConstructor() { + original = this.yamlConstructors.get(null); + this.yamlConstructors.put(null, new IgnoringConstruct()); + } + + private class IgnoringConstruct extends AbstractConstruct { - private class IgnoringConstruct extends AbstractConstruct { - public Object construct(Node node) { - if (node.getTag().startsWith("!KnownTag")) { - return original.construct(node); - } else { - switch (node.getNodeId()) { - case scalar: - return yamlConstructors.get(Tag.STR).construct(node); - case sequence: - return yamlConstructors.get(Tag.SEQ).construct(node); - case mapping: - return yamlConstructors.get(Tag.MAP).construct(node); - default: - throw new YAMLException("Unexpected node"); - } - } - } + public Object construct(Node node) { + if (node.getTag().startsWith("!KnownTag")) { + return original.construct(node); + } else { + switch (node.getNodeId()) { + case scalar: + return yamlConstructors.get(Tag.STR).construct(node); + case sequence: + return yamlConstructors.get(Tag.SEQ).construct(node); + case mapping: + return yamlConstructors.get(Tag.MAP).construct(node); + default: + throw new YAMLException("Unexpected node"); + } } + } } + } } diff --git a/src/test/java/examples/KeyIsNotTheSameAsFieldTest.java b/src/test/java/examples/KeyIsNotTheSameAsFieldTest.java new file mode 100644 index 00000000..9d148415 --- /dev/null +++ b/src/test/java/examples/KeyIsNotTheSameAsFieldTest.java @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; + +public class KeyIsNotTheSameAsFieldTest { + + public static class Param { + + private String name; + private String inputPart; + private String more; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getInputPart() { + return inputPart; + } + + public void setInputPart(String inputPart) { + this.inputPart = inputPart; + } + + public String getMore() { + return more; + } + + public void setMore(String more) { + this.more = more; + } + } + + @Test + public void loadFromStr() { + Param p = createYaml().loadAs("name: \"Test\"\ninput_part: \"abc\"\ndefault: \"some value\"", + Param.class); + + assertEquals("Test", p.getName()); + assertEquals("abc", p.getInputPart()); + assertEquals("some value", p.getMore()); + } + + @Test + public void dumpNload() { + Param realParam = new Param(); + realParam.setName("Test"); + realParam.setInputPart("abc"); + realParam.setMore("some value"); + + String yamlStr = createYaml().dump(realParam); + Param loadedParam = createYaml().loadAs(yamlStr, Param.class); + + assertEquals(realParam.getName(), loadedParam.getName()); + assertEquals(realParam.getInputPart(), loadedParam.getInputPart()); + assertEquals(realParam.getMore(), loadedParam.getMore()); + } + + private Yaml createYaml() { + TypeDescription paramDesc = new TypeDescription(Param.class); + paramDesc.substituteProperty("input_part", String.class, "getInputPart", "setInputPart"); + paramDesc.substituteProperty("default", String.class, "getMore", "setMore"); + + /* + * Need to exclude real properties. Otherwise we get them in dump in addition to "generated" + * ones: + * + * {input_part: ?1?, default: ?2?, inputPart: ?1?, more: ?2?, name: ???} + * + * not just + * + * {input_part: ?1?, default: ?2?, name: ???} + */ + paramDesc.setExcludes("inputPart", "more"); + + Yaml yaml = new Yaml(); + yaml.addTypeDescription(paramDesc); + return yaml; + } +} diff --git a/src/test/java/examples/LoadExampleTest.java b/src/test/java/examples/LoadExampleTest.java index e66ee1a8..9c620ee9 100644 --- a/src/test/java/examples/LoadExampleTest.java +++ b/src/test/java/examples/LoadExampleTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; @@ -20,53 +18,91 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Iterator; import java.util.List; import java.util.Map; - +import java.util.NoSuchElementException; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class LoadExampleTest extends TestCase { + + @SuppressWarnings("unchecked") + public void testLoad() { + Yaml yaml = new Yaml(); + String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae"; + List<String> list = yaml.load(document); + assertEquals("[Hesperiidae, Papilionidae, Apatelodidae, Epiplemidae]", list.toString()); + } + + public void testLoadFromString() { + Yaml yaml = new Yaml(); + String document = "hello: 25"; @SuppressWarnings("unchecked") - public void testLoad() { - Yaml yaml = new Yaml(); - String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae"; - List<String> list = (List<String>) yaml.load(document); - assertEquals("[Hesperiidae, Papilionidae, Apatelodidae, Epiplemidae]", list.toString()); - } + Map<String, Integer> map = yaml.load(document); + assertEquals("{hello=25}", map.toString()); + assertEquals(Integer.valueOf(25), map.get("hello")); + } + + public void testLoadFromStream() throws IOException { + InputStream input = new FileInputStream(new File("src/test/resources/reader/utf-8.txt")); + Yaml yaml = new Yaml(); + Object data = yaml.load(input); + assertEquals("test", data); + // + data = yaml.load(new ByteArrayInputStream("test2".getBytes(StandardCharsets.UTF_8))); + assertEquals("test2", data); + input.close(); + } - public void testLoadFromString() { - Yaml yaml = new Yaml(); - String document = "hello: 25"; - @SuppressWarnings("unchecked") - Map<String, Integer> map = (Map<String, Integer>) yaml.load(document); - assertEquals("{hello=25}", map.toString()); - assertEquals(new Integer(25), map.get("hello")); + public void testLoadManyDocuments() throws IOException { + InputStream input = + new FileInputStream(new File("src/test/resources/specification/example2_28.yaml")); + Yaml yaml = new Yaml(); + int counter = 0; + for (Object data : yaml.loadAll(input)) { + assertNotNull(data); + assertTrue(data.toString().length() > 1); + counter++; } + assertEquals(3, counter); + input.close(); + } - public void testLoadFromStream() throws IOException { - InputStream input = new FileInputStream(new File("src/test/resources/reader/utf-8.txt")); - Yaml yaml = new Yaml(); - Object data = yaml.load(input); - assertEquals("test", data); - // - data = yaml.load(new ByteArrayInputStream("test2".getBytes("UTF-8"))); - assertEquals("test2", data); - input.close(); + public void testLoadManyDocumentsWithIterator() throws IOException { + InputStream input = + new FileInputStream(new File("src/test/resources/specification/example2_28.yaml")); + Yaml yaml = new Yaml(); + int counter = 0; + Iterator<Object> iter = yaml.loadAll(input).iterator(); + while (iter.hasNext()) { + Object data = iter.next(); + assertNotNull(data); + assertTrue(data.toString().length() > 1); + counter++; } + assertEquals(3, counter); + input.close(); + } - public void testLoadManyDocuments() throws IOException { - InputStream input = new FileInputStream(new File( - "src/test/resources/specification/example2_28.yaml")); - Yaml yaml = new Yaml(); - int counter = 0; - for (Object data : yaml.loadAll(input)) { - assertNotNull(data); - assertTrue(data.toString().length() > 1); - counter++; - } - assertEquals(3, counter); - input.close(); + public void testLoadManyDocumentsWithIterator2() throws IOException { + InputStream input = + new FileInputStream(new File("src/test/resources/specification/example2_28.yaml")); + Yaml yaml = new Yaml(); + Iterator<Object> iter = yaml.loadAll(input).iterator(); + Object data = iter.next(); + assertNotNull(data); + data = iter.next(); + assertNotNull(data); + data = iter.next(); + assertNotNull(data); + try { + iter.next(); + fail("Expect NoSuchElementException"); + } catch (NoSuchElementException e) { + assertEquals("No document is available.", e.getMessage()); } + input.close(); + } } diff --git a/src/test/java/examples/SafeConstructorExampleTest.java b/src/test/java/examples/SafeConstructorExampleTest.java index 80af4170..fc62c4c6 100644 --- a/src/test/java/examples/SafeConstructorExampleTest.java +++ b/src/test/java/examples/SafeConstructorExampleTest.java @@ -1,51 +1,49 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; public class SafeConstructorExampleTest extends TestCase { - @SuppressWarnings("unchecked") - public void testConstruct() { - String doc = "- 5\n- Person\n- true"; - Yaml yaml = new Yaml(new SafeConstructor()); - List<Object> list = (List<Object>) yaml.load(doc); - assertEquals(3, list.size()); - assertEquals(new Integer(5), list.get(0)); - assertEquals("Person", list.get(1)); - assertEquals(Boolean.TRUE, list.get(2)); - } - public void testSafeConstruct() { - String doc = "- 5\n- !org.yaml.snakeyaml.constructor.Person\n firstName: Andrey\n age: 99\n- true"; - Yaml yaml = new Yaml(new SafeConstructor()); - try { - yaml.load(doc); - fail("Custom Java classes should not be created."); - } catch (Exception e) { - assertEquals( - "could not determine a constructor for the tag !org.yaml.snakeyaml.constructor.Person\n" - + " in 'string', line 2, column 3:\n" - + " - !org.yaml.snakeyaml.constructor. ... \n" + " ^\n", - e.getMessage()); - } + @SuppressWarnings("unchecked") + public void testConstruct() { + String doc = "- 5\n- Person\n- true"; + Yaml yaml = new Yaml(new SafeConstructor()); + List<Object> list = yaml.load(doc); + assertEquals(3, list.size()); + assertEquals(Integer.valueOf(5), list.get(0)); + assertEquals("Person", list.get(1)); + assertEquals(Boolean.TRUE, list.get(2)); + } + + public void testSafeConstruct() { + String doc = + "- 5\n- !org.yaml.snakeyaml.constructor.Person\n firstName: Andrey\n age: 99\n- true"; + Yaml yaml = new Yaml(new SafeConstructor()); + try { + yaml.load(doc); + fail("Custom Java classes should not be created."); + } catch (Exception e) { + assertEquals( + "could not determine a constructor for the tag !org.yaml.snakeyaml.constructor.Person\n" + + " in 'string', line 2, column 3:\n" + + " - !org.yaml.snakeyaml.constructor. ... \n" + " ^\n", + e.getMessage()); } + } } diff --git a/src/test/java/examples/SelectiveConstructorTest.java b/src/test/java/examples/SelectiveConstructorTest.java index 1117d469..1a68ff1e 100644 --- a/src/test/java/examples/SelectiveConstructorTest.java +++ b/src/test/java/examples/SelectiveConstructorTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.MappingNode; @@ -29,73 +25,78 @@ import org.yaml.snakeyaml.nodes.NodeId; * Example for http://code.google.com/p/snakeyaml/wiki/howto */ public class SelectiveConstructorTest extends TestCase { - class SelectiveConstructor extends Constructor { - public SelectiveConstructor() { - // define a custom way to create a mapping node - yamlClassConstructors.put(NodeId.mapping, new MyPersistentObjectConstruct()); - } - class MyPersistentObjectConstruct extends Constructor.ConstructMapping { - @Override - protected Object constructJavaBean2ndStep(MappingNode node, Object object) { - Class<?> type = node.getType(); - if (type.equals(MyPersistentObject.class)) { - // create a map - Map<Object, Object> map = constructMapping(node); - String id = (String) map.get("id"); - return new MyPersistentObject(id, 17); - } else { - // create JavaBean - return super.constructJavaBean2ndStep(node, object); - } - } - } + class SelectiveConstructor extends Constructor { + + public SelectiveConstructor() { + // define a custom way to create a mapping node + yamlClassConstructors.put(NodeId.mapping, new MyPersistentObjectConstruct()); } - public void testConstructor() { - Yaml yaml = new Yaml(new SelectiveConstructor()); - List<?> data = (List<?>) yaml - .load("- 1\n- 2\n- !!examples.MyPersistentObject {amount: 222, id: persistent}"); - // System.out.println(data); - assertEquals(3, data.size()); - MyPersistentObject myObject = (MyPersistentObject) data.get(2); - assertEquals(17, myObject.getAmount()); - assertEquals("persistent", myObject.getId()); + class MyPersistentObjectConstruct extends Constructor.ConstructMapping { + + @Override + protected Object constructJavaBean2ndStep(MappingNode node, Object object) { + Class<?> type = node.getType(); + if (type.equals(MyPersistentObject.class)) { + // create a map + Map<Object, Object> map = constructMapping(node); + String id = (String) map.get("id"); + return new MyPersistentObject(id, 17); + } else { + // create JavaBean + return super.constructJavaBean2ndStep(node, object); + } + } } + } + + public void testConstructor() { + Yaml yaml = new Yaml(new SelectiveConstructor()); + List<?> data = + yaml.load("- 1\n- 2\n- !!examples.MyPersistentObject {amount: 222, id: persistent}"); + // System.out.println(data); + assertEquals(3, data.size()); + MyPersistentObject myObject = (MyPersistentObject) data.get(2); + assertEquals(17, myObject.getAmount()); + assertEquals("persistent", myObject.getId()); + } } + class MyPersistentObject { - private String id; - private int amount; - public MyPersistentObject() { - this.id = "noid"; - this.amount = 222; - } + private String id; + private int amount; - public MyPersistentObject(String id, int amount) { - this.id = id; - this.amount = amount; - } + public MyPersistentObject() { + this.id = "noid"; + this.amount = 222; + } - public String getId() { - return id; - } + public MyPersistentObject(String id, int amount) { + this.id = id; + this.amount = amount; + } - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public int getAmount() { - return amount; - } + public void setId(String id) { + this.id = id; + } - public void setAmount(int amount) { - this.amount = amount; - } + public int getAmount() { + return amount; + } - @Override - public String toString() { - return "MyPersistentObject [id=" + id + ", amount=" + amount + "]"; - } + public void setAmount(int amount) { + this.amount = amount; + } + + @Override + public String toString() { + return "MyPersistentObject [id=" + id + ", amount=" + amount + "]"; + } } diff --git a/src/test/java/examples/collections/ListFileldBeanTest.java b/src/test/java/examples/collections/ListFileldBeanTest.java index 0bea870d..7b5bb7b3 100644 --- a/src/test/java/examples/collections/ListFileldBeanTest.java +++ b/src/test/java/examples/collections/ListFileldBeanTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -28,94 +24,96 @@ import org.yaml.snakeyaml.Yaml; * Developer class must be properly recognised */ public class ListFileldBeanTest extends TestCase { - public void testDumpList() { - ListFieldBean bean = new ListFieldBean(); - List<String> list = new ArrayList<String>(); - list.add("aaa"); - list.add("bbb"); - bean.setChildren(list); - List<Developer> developers = new ArrayList<Developer>(); - developers.add(new Developer("Fred", "creator")); - developers.add(new Developer("John", "committer")); - bean.developers = developers; - bean.setName("Bean123"); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/list-bean-1.yaml"); - assertEquals(etalon, output); - } - public void testLoadList() { - String output = Util.getLocalResource("examples/list-bean-1.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - ListFieldBean parsed = beanLoader.loadAs(output, ListFieldBean.class); - assertNotNull(parsed); - List<String> list2 = parsed.getChildren(); - assertEquals(2, list2.size()); - assertEquals("aaa", list2.get(0)); - assertEquals("bbb", list2.get(1)); - List<Developer> developers = parsed.developers; - assertEquals(2, developers.size()); - assertEquals("Developer must be recognised.", Developer.class, developers.get(0).getClass()); - Developer fred = developers.get(0); - assertEquals("Fred", fred.getName()); - assertEquals("creator", fred.getRole()); + public void testDumpList() { + ListFieldBean bean = new ListFieldBean(); + List<String> list = new ArrayList<String>(); + list.add("aaa"); + list.add("bbb"); + bean.setChildren(list); + List<Developer> developers = new ArrayList<Developer>(); + developers.add(new Developer("Fred", "creator")); + developers.add(new Developer("John", "committer")); + bean.developers = developers; + bean.setName("Bean123"); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/list-bean-1.yaml"); + assertEquals(etalon, output); + } + + public void testLoadList() { + String output = Util.getLocalResource("examples/list-bean-1.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + ListFieldBean parsed = beanLoader.loadAs(output, ListFieldBean.class); + assertNotNull(parsed); + List<String> list2 = parsed.getChildren(); + assertEquals(2, list2.size()); + assertEquals("aaa", list2.get(0)); + assertEquals("bbb", list2.get(1)); + List<Developer> developers = parsed.developers; + assertEquals(2, developers.size()); + assertEquals("Developer must be recognised.", Developer.class, developers.get(0).getClass()); + Developer fred = developers.get(0); + assertEquals("Fred", fred.getName()); + assertEquals("creator", fred.getRole()); + } + + public static class ListFieldBean { + + private List<String> children; + private String name; + public List<Developer> developers; + + public ListFieldBean() { + name = "Bean456"; } - public static class ListFieldBean { - private List<String> children; - private String name; - public List<Developer> developers; - - public ListFieldBean() { - name = "Bean456"; - } - - public List<String> getChildren() { - return children; - } + public List<String> getChildren() { + return children; + } - public void setChildren(List<String> children) { - this.children = children; - } + public void setChildren(List<String> children) { + this.children = children; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; } + } + + public static class Developer { - public static class Developer { - private String name; - private String role; + private String name; + private String role; - public Developer() { - } + public Developer() {} - public Developer(String name, String role) { - this.name = name; - this.role = role; - } + public Developer(String name, String role) { + this.name = name; + this.role = role; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getRole() { - return role; - } + public String getRole() { + return role; + } - public void setRole(String role) { - this.role = role; - } + public void setRole(String role) { + this.role = role; } + } } diff --git a/src/test/java/examples/collections/TypeSafeListNoGerericsTest.java b/src/test/java/examples/collections/TypeSafeListNoGerericsTest.java index 63c38cdf..1ac6a285 100644 --- a/src/test/java/examples/collections/TypeSafeListNoGerericsTest.java +++ b/src/test/java/examples/collections/TypeSafeListNoGerericsTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; import java.util.ArrayList; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -29,102 +25,104 @@ import org.yaml.snakeyaml.Yaml; * Developer class cannot be properly recognised */ public class TypeSafeListNoGerericsTest extends TestCase { - public void testDumpList() { - ListBean bean = new ListBean(); - List<String> list = new ArrayList<String>(); - list.add("aaa"); - list.add("bbb"); - bean.setChildren(list); - List<Developer> developers = new ArrayList<Developer>(); - developers.add(new Developer("Fred", "creator")); - developers.add(new Developer("John", "committer")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/list-bean-4.yaml"); - assertEquals(etalon, output); - } - @SuppressWarnings("unchecked") - public void testLoadList() { - String output = Util.getLocalResource("examples/list-bean-1.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - ListBean parsed = beanLoader.loadAs(output, ListBean.class); - assertNotNull(parsed); - List<String> list2 = parsed.getChildren(); - assertEquals(2, list2.size()); - assertEquals("aaa", list2.get(0)); - assertEquals("bbb", list2.get(1)); - List<Map<String, String>> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - Map<String, String> fred = developers.get(0); - assertEquals("Fred", fred.get("name")); - assertEquals("creator", fred.get("role")); + public void testDumpList() { + ListBean bean = new ListBean(); + List<String> list = new ArrayList<String>(); + list.add("aaa"); + list.add("bbb"); + bean.setChildren(list); + List<Developer> developers = new ArrayList<Developer>(); + developers.add(new Developer("Fred", "creator")); + developers.add(new Developer("John", "committer")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/list-bean-4.yaml"); + assertEquals(etalon, output); + } + + @SuppressWarnings("unchecked") + public void testLoadList() { + String output = Util.getLocalResource("examples/list-bean-1.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + ListBean parsed = beanLoader.loadAs(output, ListBean.class); + assertNotNull(parsed); + List<String> list2 = parsed.getChildren(); + assertEquals(2, list2.size()); + assertEquals("aaa", list2.get(0)); + assertEquals("bbb", list2.get(1)); + List<Map<String, String>> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + Map<String, String> fred = developers.get(0); + assertEquals("Fred", fred.get("name")); + assertEquals("creator", fred.get("role")); + } + + @SuppressWarnings("rawtypes") + public static class ListBean { + + private List<String> children; + private String name; + private List developers; + + public ListBean() { + name = "Bean123"; } - @SuppressWarnings("rawtypes") - public static class ListBean { - private List<String> children; - private String name; - private List developers; - - public ListBean() { - name = "Bean123"; - } - - public List<String> getChildren() { - return children; - } + public List<String> getChildren() { + return children; + } - public void setChildren(List<String> children) { - this.children = children; - } + public void setChildren(List<String> children) { + this.children = children; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List getDevelopers() { - return developers; - } + public List getDevelopers() { + return developers; + } - public void setDevelopers(List developers) { - this.developers = developers; - } + public void setDevelopers(List developers) { + this.developers = developers; } + } - public static class Developer { - private String name; - private String role; + public static class Developer { - public Developer() { - } + private String name; + private String role; - public Developer(String name, String role) { - this.name = name; - this.role = role; - } + public Developer() {} - public String getName() { - return name; - } + public Developer(String name, String role) { + this.name = name; + this.role = role; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getRole() { - return role; - } + public void setName(String name) { + this.name = name; + } + + public String getRole() { + return role; + } - public void setRole(String role) { - this.role = role; - } + public void setRole(String role) { + this.role = role; } + } } diff --git a/src/test/java/examples/collections/TypeSafeListTest.java b/src/test/java/examples/collections/TypeSafeListTest.java index f6c9c45b..36d705db 100644 --- a/src/test/java/examples/collections/TypeSafeListTest.java +++ b/src/test/java/examples/collections/TypeSafeListTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -28,101 +24,103 @@ import org.yaml.snakeyaml.Yaml; * Developer class must be properly recognised */ public class TypeSafeListTest extends TestCase { - public void testDumpList() { - ListBean1 bean = new ListBean1(); - List<String> list = new ArrayList<String>(); - list.add("aaa"); - list.add("bbb"); - bean.setChildren(list); - List<Developer> developers = new ArrayList<Developer>(); - developers.add(new Developer("Fred", "creator")); - developers.add(new Developer("John", "committer")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/list-bean-1.yaml"); - assertEquals(etalon, output); - } - public void testLoadList() { - String output = Util.getLocalResource("examples/list-bean-1.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - ListBean1 parsed = beanLoader.loadAs(output, ListBean1.class); - assertNotNull(parsed); - List<String> list2 = parsed.getChildren(); - assertEquals(2, list2.size()); - assertEquals("aaa", list2.get(0)); - assertEquals("bbb", list2.get(1)); - List<Developer> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - assertEquals("Developer must be recognised.", Developer.class, developers.get(0).getClass()); - Developer fred = developers.get(0); - assertEquals("Fred", fred.getName()); - assertEquals("creator", fred.getRole()); + public void testDumpList() { + ListBean1 bean = new ListBean1(); + List<String> list = new ArrayList<String>(); + list.add("aaa"); + list.add("bbb"); + bean.setChildren(list); + List<Developer> developers = new ArrayList<Developer>(); + developers.add(new Developer("Fred", "creator")); + developers.add(new Developer("John", "committer")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/list-bean-1.yaml"); + assertEquals(etalon, output); + } + + public void testLoadList() { + String output = Util.getLocalResource("examples/list-bean-1.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + ListBean1 parsed = beanLoader.loadAs(output, ListBean1.class); + assertNotNull(parsed); + List<String> list2 = parsed.getChildren(); + assertEquals(2, list2.size()); + assertEquals("aaa", list2.get(0)); + assertEquals("bbb", list2.get(1)); + List<Developer> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + assertEquals("Developer must be recognised.", Developer.class, developers.get(0).getClass()); + Developer fred = developers.get(0); + assertEquals("Fred", fred.getName()); + assertEquals("creator", fred.getRole()); + } + + public static class ListBean1 { + + private List<String> children; + private String name; + private List<Developer> developers; + + public ListBean1() { + name = "Bean123"; } - public static class ListBean1 { - private List<String> children; - private String name; - private List<Developer> developers; - - public ListBean1() { - name = "Bean123"; - } - - public List<String> getChildren() { - return children; - } + public List<String> getChildren() { + return children; + } - public void setChildren(List<String> children) { - this.children = children; - } + public void setChildren(List<String> children) { + this.children = children; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List<Developer> getDevelopers() { - return developers; - } + public List<Developer> getDevelopers() { + return developers; + } - public void setDevelopers(List<Developer> developers) { - this.developers = developers; - } + public void setDevelopers(List<Developer> developers) { + this.developers = developers; } + } - public static class Developer { - private String name; - private String role; + public static class Developer { - public Developer() { - } + private String name; + private String role; - public Developer(String name, String role) { - this.name = name; - this.role = role; - } + public Developer() {} - public String getName() { - return name; - } + public Developer(String name, String role) { + this.name = name; + this.role = role; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getRole() { - return role; - } + public void setName(String name) { + this.name = name; + } + + public String getRole() { + return role; + } - public void setRole(String role) { - this.role = role; - } + public void setRole(String role) { + this.role = role; } + } } diff --git a/src/test/java/examples/collections/TypeSafeListWithInterfaceTest.java b/src/test/java/examples/collections/TypeSafeListWithInterfaceTest.java index 4f6c08cd..a2000574 100644 --- a/src/test/java/examples/collections/TypeSafeListWithInterfaceTest.java +++ b/src/test/java/examples/collections/TypeSafeListWithInterfaceTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -28,145 +24,147 @@ import org.yaml.snakeyaml.Yaml; * Human is an interface and the global tags are required */ public class TypeSafeListWithInterfaceTest extends TestCase { - public void testDumpList() { - ListBean bean = new ListBean(); - List<String> list = new ArrayList<String>(); - list.add("aaa"); - list.add("bbb"); - bean.setChildren(list); - List<Human> developers = new ArrayList<Human>(); - developers.add(new Developer("Fred", "creator")); - developers.add(new Committer("John", "committer", 34)); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/list-bean-2.yaml"); - assertEquals(etalon, output); - } - - public void testLoadWrongList() { - String output = Util.getLocalResource("examples/list-bean-1.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - try { - beanLoader.loadAs(output, ListBean.class); - fail("Global tags are required since Human is an interface."); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("Cannot create property=developers")); - } - } - - public void testLoadList() { - String output = Util.getLocalResource("examples/list-bean-2.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - ListBean parsed = beanLoader.loadAs(output, ListBean.class); - assertNotNull(parsed); - List<String> list2 = parsed.getChildren(); - assertEquals(2, list2.size()); - assertEquals("aaa", list2.get(0)); - assertEquals("bbb", list2.get(1)); - List<Human> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - assertEquals("Developer must be recognised.", Developer.class, developers.get(0).getClass()); - Developer fred = (Developer) developers.get(0); - assertEquals("Fred", fred.getName()); - assertEquals("creator", fred.getRole()); - Committer john = (Committer) developers.get(1); - assertEquals("John", john.getName()); - assertEquals("committer", john.getRole()); - assertEquals(34, john.getKey()); - } - - public static class ListBean { - private List<String> children; - private String name; - private List<Human> developers; - - public ListBean() { - name = "Bean123"; - } - - public List<String> getChildren() { - return children; - } - - public void setChildren(List<String> children) { - this.children = children; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List<Human> getDevelopers() { - return developers; - } - - public void setDevelopers(List<Human> developers) { - this.developers = developers; - } - } - - public static interface Human { - - public String getName(); - - public void setName(String name); - - } - - public static class Developer implements Human { - private String name; - private String role; - - public Developer() { - } - - public Developer(String name, String role) { - this.name = name; - this.role = role; - } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } + public void testDumpList() { + ListBean bean = new ListBean(); + List<String> list = new ArrayList<String>(); + list.add("aaa"); + list.add("bbb"); + bean.setChildren(list); + List<Human> developers = new ArrayList<Human>(); + developers.add(new Developer("Fred", "creator")); + developers.add(new Committer("John", "committer", 34)); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/list-bean-2.yaml"); + assertEquals(etalon, output); + } + + public void testLoadWrongList() { + String output = Util.getLocalResource("examples/list-bean-1.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + try { + beanLoader.loadAs(output, ListBean.class); + fail("Global tags are required since Human is an interface."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("Cannot create property=developers")); + } + } + + public void testLoadList() { + String output = Util.getLocalResource("examples/list-bean-2.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + ListBean parsed = beanLoader.loadAs(output, ListBean.class); + assertNotNull(parsed); + List<String> list2 = parsed.getChildren(); + assertEquals(2, list2.size()); + assertEquals("aaa", list2.get(0)); + assertEquals("bbb", list2.get(1)); + List<Human> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + assertEquals("Developer must be recognised.", Developer.class, developers.get(0).getClass()); + Developer fred = (Developer) developers.get(0); + assertEquals("Fred", fred.getName()); + assertEquals("creator", fred.getRole()); + Committer john = (Committer) developers.get(1); + assertEquals("John", john.getName()); + assertEquals("committer", john.getRole()); + assertEquals(34, john.getKey()); + } + + public static class ListBean { + + private List<String> children; + private String name; + private List<Human> developers; + + public ListBean() { + name = "Bean123"; + } - public String getRole() { - return role; - } + public List<String> getChildren() { + return children; + } + + public void setChildren(List<String> children) { + this.children = children; + } + + public String getName() { + return name; + } - public void setRole(String role) { - this.role = role; - } + public void setName(String name) { + this.name = name; } - public static class Committer extends Developer { - private int key; + public List<Human> getDevelopers() { + return developers; + } + + public void setDevelopers(List<Human> developers) { + this.developers = developers; + } + } + + public interface Human { + + String getName(); + + void setName(String name); + + } + + public static class Developer implements Human { - public Committer() { - } + private String name; + private String role; - public Committer(String string, String string2, int i) { - super(string, string2); - this.key = i; - } + public Developer() {} - public int getKey() { - return key; - } + public Developer(String name, String role) { + this.name = name; + this.role = role; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + } + + public static class Committer extends Developer { + + private int key; + + public Committer() {} + + public Committer(String string, String string2, int i) { + super(string, string2); + this.key = i; + } + + public int getKey() { + return key; + } - public void setKey(int key) { - this.key = key; - } + public void setKey(int key) { + this.key = key; } + } } diff --git a/src/test/java/examples/collections/TypeSafeMap2Test.java b/src/test/java/examples/collections/TypeSafeMap2Test.java index 74673b37..70e7051d 100644 --- a/src/test/java/examples/collections/TypeSafeMap2Test.java +++ b/src/test/java/examples/collections/TypeSafeMap2Test.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -29,202 +25,205 @@ import org.yaml.snakeyaml.Yaml; * Developer class must be properly recognised */ public class TypeSafeMap2Test extends TestCase { - public void testDumpMap() { - MapBean2 bean = new MapBean2(); - Map<Developer2, Color> data = new LinkedHashMap<Developer2, Color>(); - data.put(new Developer2("Andy", "tester"), Color.BLACK); - data.put(new Developer2("Lisa", "owner"), Color.RED); - bean.setData(data); - Map<Color, Developer2> developers = new LinkedHashMap<Color, Developer2>(); - developers.put(Color.WHITE, new Developer2("Fred", "creator")); - developers.put(Color.BLACK, new Developer2("John", "committer")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-bean-12.yaml"); - assertEquals(etalon, output); - } - - public void testMap2() { - MapBean2 bean = new MapBean2(); - Map<Developer2, Color> data = new LinkedHashMap<Developer2, Color>(); - data.put(new Developer2("Andy", "tester"), Color.BLACK); - data.put(new SuperMan("Bill", "cleaner", false), Color.BLACK); - data.put(new Developer2("Lisa", "owner"), Color.RED); - bean.setData(data); - Map<Color, Developer2> developers = new LinkedHashMap<Color, Developer2>(); - developers.put(Color.WHITE, new Developer2("Fred", "creator")); - developers.put(Color.RED, new SuperMan("Jason", "contributor", true)); - developers.put(Color.BLACK, new Developer2("John", "committer")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-bean-13.yaml"); - assertEquals(etalon, output); - // load - Yaml beanLoader = new Yaml(); - MapBean2 parsed = beanLoader.loadAs(etalon, MapBean2.class); - assertNotNull(parsed); - Map<Developer2, Color> parsedData = parsed.getData(); - assertEquals(3, parsedData.size()); - assertTrue(parsedData.containsKey(new SuperMan("Bill", "cleaner", false))); - assertEquals(Color.BLACK, parsedData.get(new SuperMan("Bill", "cleaner", false))); - // - Map<Color, Developer2> parsedDevelopers = parsed.getDevelopers(); - assertEquals(3, parsedDevelopers.size()); - assertEquals(new SuperMan("Jason", "contributor", true), parsedDevelopers.get(Color.RED)); - } - - public void testLoadMap() { - String output = Util.getLocalResource("examples/map-bean-12.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - MapBean2 parsed = beanLoader.loadAs(output, MapBean2.class); - assertNotNull(parsed); - Map<Developer2, Color> data = parsed.getData(); - assertEquals(2, data.size()); - Iterator<Developer2> iter = data.keySet().iterator(); - Developer2 first = iter.next(); - assertEquals("Andy", first.getName()); - assertEquals("tester", first.getRole()); - assertEquals(Color.BLACK, data.get(first)); - Developer2 second = iter.next(); - assertEquals("Lisa", second.getName()); - assertEquals("owner", second.getRole()); - assertEquals(Color.RED, data.get(second)); - // - Map<Color, Developer2> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - Iterator<Color> iter2 = developers.keySet().iterator(); - Color firstColor = iter2.next(); - assertEquals(Color.WHITE, firstColor); - Developer2 dev1 = developers.get(firstColor); - assertEquals("Fred", dev1.getName()); - assertEquals("creator", dev1.getRole()); - Color secondColor = iter2.next(); - assertEquals(Color.BLACK, secondColor); - Developer2 dev2 = developers.get(secondColor); - assertEquals("John", dev2.getName()); - assertEquals("committer", dev2.getRole()); - } - - public static enum Color { - WHITE, BLACK, RED; - } - - public static class MapBean2 { - private Map<Developer2, Color> data; - private String name; - private Map<Color, Developer2> developers; - - public MapBean2() { - name = "Bean123"; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Map<Color, Developer2> getDevelopers() { - return developers; - } - - public void setDevelopers(Map<Color, Developer2> developers) { - this.developers = developers; - } - - public Map<Developer2, Color> getData() { - return data; - } - - public void setData(Map<Developer2, Color> data) { - this.data = data; - } - - } - - public static class Developer2 implements Comparable<Developer2> { - private String name; - private String role; - - public Developer2() { - } - - private Developer2(String name, String role) { - this.name = name; - this.role = role; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } - - public int compareTo(Developer2 o) { - return name.compareTo(o.name); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Developer2) { - return toString().equals(obj.toString()); - } else { - return false; - } - } - - @Override - public int hashCode() { - return toString().hashCode(); - } - @Override - public String toString() { - return "Developer " + name + " " + role; - } + public void testDumpMap() { + MapBean2 bean = new MapBean2(); + Map<Developer2, Color> data = new LinkedHashMap<Developer2, Color>(); + data.put(new Developer2("Andy", "tester"), Color.BLACK); + data.put(new Developer2("Lisa", "owner"), Color.RED); + bean.setData(data); + Map<Color, Developer2> developers = new LinkedHashMap<Color, Developer2>(); + developers.put(Color.WHITE, new Developer2("Fred", "creator")); + developers.put(Color.BLACK, new Developer2("John", "committer")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/map-bean-12.yaml"); + assertEquals(etalon, output); + } + + public void testMap2() { + MapBean2 bean = new MapBean2(); + Map<Developer2, Color> data = new LinkedHashMap<Developer2, Color>(); + data.put(new Developer2("Andy", "tester"), Color.BLACK); + data.put(new SuperMan("Bill", "cleaner", false), Color.BLACK); + data.put(new Developer2("Lisa", "owner"), Color.RED); + bean.setData(data); + Map<Color, Developer2> developers = new LinkedHashMap<Color, Developer2>(); + developers.put(Color.WHITE, new Developer2("Fred", "creator")); + developers.put(Color.RED, new SuperMan("Jason", "contributor", true)); + developers.put(Color.BLACK, new Developer2("John", "committer")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/map-bean-13.yaml"); + assertEquals(etalon, output); + // load + Yaml beanLoader = new Yaml(); + MapBean2 parsed = beanLoader.loadAs(etalon, MapBean2.class); + assertNotNull(parsed); + Map<Developer2, Color> parsedData = parsed.getData(); + assertEquals(3, parsedData.size()); + assertTrue(parsedData.containsKey(new SuperMan("Bill", "cleaner", false))); + assertEquals(Color.BLACK, parsedData.get(new SuperMan("Bill", "cleaner", false))); + // + Map<Color, Developer2> parsedDevelopers = parsed.getDevelopers(); + assertEquals(3, parsedDevelopers.size()); + assertEquals(new SuperMan("Jason", "contributor", true), parsedDevelopers.get(Color.RED)); + } + + public void testLoadMap() { + String output = Util.getLocalResource("examples/map-bean-12.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + MapBean2 parsed = beanLoader.loadAs(output, MapBean2.class); + assertNotNull(parsed); + Map<Developer2, Color> data = parsed.getData(); + assertEquals(2, data.size()); + Iterator<Developer2> iter = data.keySet().iterator(); + Developer2 first = iter.next(); + assertEquals("Andy", first.getName()); + assertEquals("tester", first.getRole()); + assertEquals(Color.BLACK, data.get(first)); + Developer2 second = iter.next(); + assertEquals("Lisa", second.getName()); + assertEquals("owner", second.getRole()); + assertEquals(Color.RED, data.get(second)); + // + Map<Color, Developer2> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + Iterator<Color> iter2 = developers.keySet().iterator(); + Color firstColor = iter2.next(); + assertEquals(Color.WHITE, firstColor); + Developer2 dev1 = developers.get(firstColor); + assertEquals("Fred", dev1.getName()); + assertEquals("creator", dev1.getRole()); + Color secondColor = iter2.next(); + assertEquals(Color.BLACK, secondColor); + Developer2 dev2 = developers.get(secondColor); + assertEquals("John", dev2.getName()); + assertEquals("committer", dev2.getRole()); + } + + public enum Color { + WHITE, BLACK, RED + } + + public static class MapBean2 { + + private Map<Developer2, Color> data; + private String name; + private Map<Color, Developer2> developers; + + public MapBean2() { + name = "Bean123"; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; } - public static class SuperMan extends Developer2 { - private boolean smart; + public Map<Color, Developer2> getDevelopers() { + return developers; + } - public SuperMan() { - super(); - } + public void setDevelopers(Map<Color, Developer2> developers) { + this.developers = developers; + } + + public Map<Developer2, Color> getData() { + return data; + } + + public void setData(Map<Developer2, Color> data) { + this.data = data; + } - private SuperMan(String name, String role, boolean smart) { - super(name, role); - this.smart = smart; - } + } - public boolean isSmart() { - return smart; - } + public static class Developer2 implements Comparable<Developer2> { + + private String name; + private String role; + + public Developer2() {} + + private Developer2(String name, String role) { + this.name = name; + this.role = role; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRole() { + return role; + } - public void setSmart(boolean smart) { - this.smart = smart; - } + public void setRole(String role) { + this.role = role; + } + + public int compareTo(Developer2 o) { + return name.compareTo(o.name); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Developer2) { + return toString().equals(obj.toString()); + } else { + return false; + } + } + + @Override + public int hashCode() { + return toString().hashCode(); + } + + @Override + public String toString() { + return "Developer " + name + " " + role; + } + + } + + public static class SuperMan extends Developer2 { + + private boolean smart; + + public SuperMan() { + super(); + } + + private SuperMan(String name, String role, boolean smart) { + super(name, role); + this.smart = smart; + } + + public boolean isSmart() { + return smart; + } + + public void setSmart(boolean smart) { + this.smart = smart; + } - @Override - public String toString() { - return "Super" + super.toString(); - } + @Override + public String toString() { + return "Super" + super.toString(); } + } } diff --git a/src/test/java/examples/collections/TypeSafeMapImplementationsTest.java b/src/test/java/examples/collections/TypeSafeMapImplementationsTest.java index 2eff9868..dba3d9bf 100644 --- a/src/test/java/examples/collections/TypeSafeMapImplementationsTest.java +++ b/src/test/java/examples/collections/TypeSafeMapImplementationsTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; @@ -21,9 +19,7 @@ import java.util.Map; import java.util.Properties; import java.util.SortedMap; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -31,173 +27,179 @@ import org.yaml.snakeyaml.Yaml; * Test different Map implementations as JavaBean properties */ public class TypeSafeMapImplementationsTest extends TestCase { - public void testDumpMap() { - MapBean bean = new MapBean(); - SortedMap<String, String> sortedMap = new TreeMap<String, String>(); - sortedMap.put("2", "two"); - sortedMap.put("1", "one"); - bean.setSorted(sortedMap); - Properties props = new Properties(); - props.setProperty("key1", "value1"); - props.setProperty("key2", "value2"); - bean.setProperties(props); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-bean-1.yaml"); - assertEquals(etalon, output); - } - public void testLoadMap() { - String output = Util.getLocalResource("examples/map-bean-1.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - MapBean parsed = beanLoader.loadAs(output, MapBean.class); - assertNotNull(parsed); - SortedMap<String, String> sortedMap = parsed.getSorted(); - assertEquals(2, sortedMap.size()); - assertEquals("one", sortedMap.get("1")); - assertEquals("two", sortedMap.get("2")); - String first = sortedMap.keySet().iterator().next(); - assertEquals("1", first); - // - Properties props = parsed.getProperties(); - assertEquals(2, props.size()); - assertEquals("value1", props.getProperty("key1")); - assertEquals("value2", props.getProperty("key2")); + public void testDumpMap() { + MapBean bean = new MapBean(); + SortedMap<String, String> sortedMap = new TreeMap<String, String>(); + sortedMap.put("2", "two"); + sortedMap.put("1", "one"); + bean.setSorted(sortedMap); + Properties props = new Properties(); + props.setProperty("key1", "value1"); + props.setProperty("key2", "value2"); + bean.setProperties(props); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/map-bean-1.yaml"); + assertTrue("Lines are the same but the order may be different: " + output, + Util.compareAllLines(etalon, output)); + } + + public void testLoadMap() { + String output = Util.getLocalResource("examples/map-bean-1.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + MapBean parsed = beanLoader.loadAs(output, MapBean.class); + assertNotNull(parsed); + SortedMap<String, String> sortedMap = parsed.getSorted(); + assertEquals(2, sortedMap.size()); + assertEquals("one", sortedMap.get("1")); + assertEquals("two", sortedMap.get("2")); + String first = sortedMap.keySet().iterator().next(); + assertEquals("1", first); + // + Properties props = parsed.getProperties(); + assertEquals(2, props.size()); + assertEquals("value1", props.getProperty("key1")); + assertEquals("value2", props.getProperty("key2")); + } + + public static class MapBean { + + private SortedMap<String, String> sorted; + private Properties properties; + private String name; + + public MapBean() { + name = "Bean123"; } - public static class MapBean { - private SortedMap<String, String> sorted; - private Properties properties; - private String name; - - public MapBean() { - name = "Bean123"; - } - - public SortedMap<String, String> getSorted() { - return sorted; - } - - public void setSorted(SortedMap<String, String> sorted) { - this.sorted = sorted; - } - - public Properties getProperties() { - return properties; - } - - public void setProperties(Properties properties) { - this.properties = properties; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } + public SortedMap<String, String> getSorted() { + return sorted; } - @SuppressWarnings("unchecked") - public void testNoJavaBeanMap() { - List<Object> list = new ArrayList<Object>(3); - SortedMap<String, String> sortedMap = new TreeMap<String, String>(); - sortedMap.put("2", "two"); - sortedMap.put("1", "one"); - list.add(sortedMap); - Properties props = new Properties(); - props.setProperty("key1", "value1"); - props.setProperty("key2", "value2"); - list.add(props); - list.add("aaa"); - Yaml yaml = new Yaml(); - String output = yaml.dump(list); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-bean-2.yaml"); - assertEquals(etalon, output); - // load - List<Object> list2 = (List<Object>) yaml.load(output); - assertEquals(3, list2.size()); - Map<Object, Object> map1 = (Map<Object, Object>) list.get(0);// it was - // SortedMap - assertEquals(2, map1.size()); - assertEquals("one", map1.get("1")); - assertEquals("two", map1.get("2")); - Map<Object, Object> map2 = (Map<Object, Object>) list.get(1);// it was - // Properties - assertEquals(2, map2.size()); - assertEquals("value1", map2.get("key1")); - assertEquals("value2", map2.get("key2")); - assertEquals("aaa", list.get(2)); + public void setSorted(SortedMap<String, String> sorted) { + this.sorted = sorted; } - public void testRecursiveNoJavaBeanMap1() { - SortedMap<String, Object> sortedMap = new TreeMap<String, Object>(); - sortedMap.put("2", "two"); - sortedMap.put("1", "one"); - sortedMap.put("3", sortedMap); - Yaml yaml = new Yaml(); - String output = yaml.dump(sortedMap); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-recursive-1.yaml"); - assertEquals(etalon, output); - // load with different order - @SuppressWarnings("unchecked") - Map<Object, Object> map1 = (Map<Object, Object>) yaml.load(Util - .getLocalResource("examples/map-recursive-1_1.yaml")); - assertEquals(3, map1.size()); - assertEquals("one", map1.get("1")); - assertEquals("two", map1.get("2")); - // test that the order is taken from YAML instead of sorting - String first = (String) map1.keySet().iterator().next(); - assertEquals("2", first); + public Properties getProperties() { + return properties; } - @SuppressWarnings("unchecked") - public void testRecursiveNoJavaBeanProperties2() { - Properties props = new Properties(); - props.setProperty("key1", "value1"); - props.setProperty("key2", "value2"); - Map<Object, Object> map = props; - map.put("key3", props); - Yaml yaml = new Yaml(); - String output = yaml.dump(props); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-recursive-2.yaml"); - assertEquals(etalon, output); - // load - Map<Object, Object> map2 = (Map<Object, Object>) yaml.load(output); - assertEquals(3, map2.size()); - assertEquals("value1", map2.get("key1")); - assertEquals("value2", map2.get("key2")); + public void setProperties(Properties properties) { + this.properties = properties; } - public void testRecursiveNoJavaBeanMap3() { - Yaml yaml = new Yaml(); - String output = Util.getLocalResource("examples/map-recursive-3.yaml"); - // System.out.println(output); - @SuppressWarnings("unchecked") - SortedMap<Object, Object> map1 = (SortedMap<Object, Object>) yaml.load(output); - assertEquals(3, map1.size()); - assertEquals("one", map1.get("1")); - assertEquals("two", map1.get("2")); - // test that the order is NOT taken from YAML but sorted - String first = (String) map1.keySet().iterator().next(); - assertEquals("1", first); + public String getName() { + return name; } - public void testRecursiveNoJavaBeanProperties4() { - Yaml yaml = new Yaml(); - String output = Util.getLocalResource("examples/map-recursive-4.yaml"); - // System.out.println(output); - try { - yaml.load(output); - fail("Recursive Properties are not supported."); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("Properties must not be recursive.")); - } + public void setName(String name) { + this.name = name; } + } + + @SuppressWarnings("unchecked") + public void testNoJavaBeanMap() { + List<Object> list = new ArrayList<Object>(3); + SortedMap<String, String> sortedMap = new TreeMap<String, String>(); + sortedMap.put("2", "two"); + sortedMap.put("1", "one"); + list.add(sortedMap); + Properties props = new Properties(); + props.setProperty("key1", "value1"); + props.setProperty("key2", "value2"); + list.add(props); + list.add("aaa"); + Yaml yaml = new Yaml(); + String output = yaml.dump(list); + // System.out.println(output); + assertTrue("Row 1 expected: " + output, output.contains("- {'1': one, '2': two}")); + assertTrue("Row 3 expected: " + output, output.contains("- aaa")); + // the key order is not specified + assertTrue("Row 2 expected: " + output, output.contains("key1: value1")); + assertTrue("Row 2 expected: " + output, output.contains("key2: value2")); + // load + List<Object> list2 = yaml.load(output); + assertEquals(3, list2.size()); + Map<Object, Object> map1 = (Map<Object, Object>) list.get(0);// it was + // SortedMap + assertEquals(2, map1.size()); + assertEquals("one", map1.get("1")); + assertEquals("two", map1.get("2")); + Map<Object, Object> map2 = (Map<Object, Object>) list.get(1);// it was + // Properties + assertEquals(2, map2.size()); + assertEquals("value1", map2.get("key1")); + assertEquals("value2", map2.get("key2")); + assertEquals("aaa", list.get(2)); + } + + public void testRecursiveNoJavaBeanMap1() { + SortedMap<String, Object> sortedMap = new TreeMap<String, Object>(); + sortedMap.put("2", "two"); + sortedMap.put("1", "one"); + sortedMap.put("3", sortedMap); + Yaml yaml = new Yaml(); + String output = yaml.dump(sortedMap); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/map-recursive-1.yaml"); + assertEquals(etalon, output); + // load with different order + @SuppressWarnings("unchecked") + Map<Object, Object> map1 = yaml.load(Util.getLocalResource("examples/map-recursive-1_1.yaml")); + assertEquals(3, map1.size()); + assertEquals("one", map1.get("1")); + assertEquals("two", map1.get("2")); + // test that the order is taken from YAML instead of sorting + String first = (String) map1.keySet().iterator().next(); + assertEquals("2", first); + } + + @SuppressWarnings("unchecked") + public void testRecursiveNoJavaBeanProperties2() { + Properties props = new Properties(); + props.setProperty("key1", "value1"); + props.setProperty("key2", "value2"); + Map<Object, Object> map = props; + map.put("key3", props); + Yaml yaml = new Yaml(); + String output = yaml.dump(props); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/map-recursive-2.yaml"); + assertTrue("Lines are the same but the order may be different: " + output, + Util.compareAllLines(etalon, output)); + assertTrue("Should begin with anchor: " + output, output.startsWith("&id001\n")); + // load + Map<Object, Object> map2 = yaml.load(output); + assertEquals(3, map2.size()); + assertEquals("value1", map2.get("key1")); + assertEquals("value2", map2.get("key2")); + } + + public void testRecursiveNoJavaBeanMap3() { + Yaml yaml = new Yaml(); + String output = Util.getLocalResource("examples/map-recursive-3.yaml"); + // System.out.println(output); + @SuppressWarnings("unchecked") + SortedMap<Object, Object> map1 = yaml.load(output); + assertEquals(3, map1.size()); + assertEquals("one", map1.get("1")); + assertEquals("two", map1.get("2")); + // test that the order is NOT taken from YAML but sorted + String first = (String) map1.keySet().iterator().next(); + assertEquals("1", first); + } + + public void testRecursiveProperties4() { + Yaml yaml = new Yaml(); + String output = Util.getLocalResource("examples/map-recursive-4.yaml"); + // System.out.println(output); + Properties p = yaml.load(output); + assertEquals(3, p.size()); + assertEquals("value2", p.get("key2")); + assertEquals("value1", p.get("key1")); + assertSame(p, p.get("key3")); + } } diff --git a/src/test/java/examples/collections/TypeSafeMapTest.java b/src/test/java/examples/collections/TypeSafeMapTest.java index d21b9549..67cb5bbf 100644 --- a/src/test/java/examples/collections/TypeSafeMapTest.java +++ b/src/test/java/examples/collections/TypeSafeMapTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; import java.util.LinkedHashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -28,192 +24,196 @@ import org.yaml.snakeyaml.Yaml; * Developer class must be properly recognised */ public class TypeSafeMapTest extends TestCase { - public void testDumpMap() { - MapBean bean = new MapBean(); - Map<String, Integer> data = new LinkedHashMap<String, Integer>(); - data.put("aaa", 1); - data.put("bbb", 2); - data.put("zzz", 3); - bean.setData(data); - Map<String, Developer2> developers = new LinkedHashMap<String, Developer2>(); - developers.put("team1", new Developer2("Fred", "creator")); - developers.put("team2", new Developer2("John", "committer")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-bean-10.yaml"); - assertEquals(etalon, output); - } - - public void testDumpMap2() { - MapBean bean = new MapBean(); - Map<String, Integer> data = new LinkedHashMap<String, Integer>(); - data.put("aaa", 1); - data.put("bbb", 2); - bean.setData(data); - Map<String, Developer2> developers = new LinkedHashMap<String, Developer2>(); - developers.put("team1", new Developer2("Fred", "creator")); - developers.put("team2", new Developer2("John", "committer")); - developers.put("team3", new Developer222("Bill", "head")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/map-bean-11.yaml"); - assertEquals(etalon, output); - } - - public void testLoadMap() { - String output = Util.getLocalResource("examples/map-bean-10.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - MapBean parsed = beanLoader.loadAs(output, MapBean.class); - assertNotNull(parsed); - Map<String, Integer> data = parsed.getData(); - assertEquals(3, data.size()); - assertEquals(new Integer(1), data.get("aaa")); - assertEquals(new Integer(2), data.get("bbb")); - assertEquals(new Integer(3), data.get("zzz")); - Map<String, Developer2> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - assertEquals("Developer must be recognised.", Developer2.class, developers.get("team1") - .getClass()); - Developer2 fred = developers.get("team1"); - assertEquals("Fred", fred.getName()); - assertEquals("creator", fred.getRole()); - } - - public static class MapBean { - private Map<String, Integer> data; - private String name; - private Map<String, Developer2> developers; - - public MapBean() { - name = "Bean123"; - } - - public Map<String, Integer> getData() { - return data; - } - - public void setData(Map<String, Integer> data) { - this.data = data; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Map<String, Developer2> getDevelopers() { - return developers; - } - - public void setDevelopers(Map<String, Developer2> developers) { - this.developers = developers; - } - } - - public static class Developer2 { - private String name; - private String role; - - public Developer2() { - } - - public Developer2(String name, String role) { - this.name = name; - this.role = role; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } - } - - public static class Developer222 extends Developer2 { - public Developer222() { - super(); - } - - public Developer222(String name, String role) { - super(name, role); - } - } - - /* - * No generic collection - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testLoadMapWithObject() { - String output = Util.getLocalResource("examples/map-bean-10.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - MapBeanNoGenerics parsed = beanLoader.loadAs(output, MapBeanNoGenerics.class); - assertNotNull(parsed); - Map<String, Integer> data = parsed.getData(); - assertEquals(3, data.size()); - assertEquals(new Integer(1), data.get("aaa")); - assertEquals(new Integer(2), data.get("bbb")); - assertEquals(new Integer(3), data.get("zzz")); - Map developers = parsed.getDevelopers(); - assertNotNull(developers); - assertEquals(2, developers.size()); - Object o1 = developers.get("team1"); - // because of erasure we get simply Map - Map<String, String> developer = (Map<String, String>) o1; - assertEquals("Fred", developer.get("name")); - assertEquals("creator", developer.get("role")); - } - - @SuppressWarnings("rawtypes") - public static class MapBeanNoGenerics { - private Map data; - private String name; - private Map developers; - - public MapBeanNoGenerics() { - name = "Bean123"; - } - - public Map getData() { - return data; - } - - public void setData(Map data) { - this.data = data; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Map getDevelopers() { - return developers; - } - - public void setDevelopers(Map developers) { - this.developers = developers; - } + + public void testDumpMap() { + MapBean bean = new MapBean(); + Map<String, Integer> data = new LinkedHashMap<String, Integer>(); + data.put("aaa", 1); + data.put("bbb", 2); + data.put("zzz", 3); + bean.setData(data); + Map<String, Developer2> developers = new LinkedHashMap<String, Developer2>(); + developers.put("team1", new Developer2("Fred", "creator")); + developers.put("team2", new Developer2("John", "committer")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/map-bean-10.yaml"); + assertEquals(etalon, output); + } + + public void testDumpMap2() { + MapBean bean = new MapBean(); + Map<String, Integer> data = new LinkedHashMap<String, Integer>(); + data.put("aaa", 1); + data.put("bbb", 2); + bean.setData(data); + Map<String, Developer2> developers = new LinkedHashMap<String, Developer2>(); + developers.put("team1", new Developer2("Fred", "creator")); + developers.put("team2", new Developer2("John", "committer")); + developers.put("team3", new Developer222("Bill", "head")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/map-bean-11.yaml"); + assertEquals(etalon, output); + } + + public void testLoadMap() { + String output = Util.getLocalResource("examples/map-bean-10.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + MapBean parsed = beanLoader.loadAs(output, MapBean.class); + assertNotNull(parsed); + Map<String, Integer> data = parsed.getData(); + assertEquals(3, data.size()); + assertEquals(Integer.valueOf(1), data.get("aaa")); + assertEquals(Integer.valueOf(2), data.get("bbb")); + assertEquals(Integer.valueOf(3), data.get("zzz")); + Map<String, Developer2> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + assertEquals("Developer must be recognised.", Developer2.class, + developers.get("team1").getClass()); + Developer2 fred = developers.get("team1"); + assertEquals("Fred", fred.getName()); + assertEquals("creator", fred.getRole()); + } + + public static class MapBean { + + private Map<String, Integer> data; + private String name; + private Map<String, Developer2> developers; + + public MapBean() { + name = "Bean123"; + } + + public Map<String, Integer> getData() { + return data; + } + + public void setData(Map<String, Integer> data) { + this.data = data; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map<String, Developer2> getDevelopers() { + return developers; + } + + public void setDevelopers(Map<String, Developer2> developers) { + this.developers = developers; + } + } + + public static class Developer2 { + + private String name; + private String role; + + public Developer2() {} + + public Developer2(String name, String role) { + this.name = name; + this.role = role; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + } + + public static class Developer222 extends Developer2 { + + public Developer222() { + super(); + } + + public Developer222(String name, String role) { + super(name, role); + } + } + + /* + * No generic collection + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testLoadMapWithObject() { + String output = Util.getLocalResource("examples/map-bean-10.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + MapBeanNoGenerics parsed = beanLoader.loadAs(output, MapBeanNoGenerics.class); + assertNotNull(parsed); + Map<String, Integer> data = parsed.getData(); + assertEquals(3, data.size()); + assertEquals(Integer.valueOf(1), data.get("aaa")); + assertEquals(Integer.valueOf(2), data.get("bbb")); + assertEquals(Integer.valueOf(3), data.get("zzz")); + Map developers = parsed.getDevelopers(); + assertNotNull(developers); + assertEquals(2, developers.size()); + Object o1 = developers.get("team1"); + // because of erasure we get simply Map + Map<String, String> developer = (Map<String, String>) o1; + assertEquals("Fred", developer.get("name")); + assertEquals("creator", developer.get("role")); + } + + @SuppressWarnings("rawtypes") + public static class MapBeanNoGenerics { + + private Map data; + private String name; + private Map developers; + + public MapBeanNoGenerics() { + name = "Bean123"; + } + + public Map getData() { + return data; + } + + public void setData(Map data) { + this.data = data; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getDevelopers() { + return developers; + } + + public void setDevelopers(Map developers) { + this.developers = developers; } + } } diff --git a/src/test/java/examples/collections/TypeSafePriorityTest.java b/src/test/java/examples/collections/TypeSafePriorityTest.java index bbe390d3..18ed41c8 100644 --- a/src/test/java/examples/collections/TypeSafePriorityTest.java +++ b/src/test/java/examples/collections/TypeSafePriorityTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -30,89 +26,89 @@ import org.yaml.snakeyaml.constructor.Constructor; */ public class TypeSafePriorityTest extends TestCase { - /** - * explicit TypeDescription is more important then runtime class (which may - * be an interface) - */ - public void testLoadList2() { - String output = Util.getLocalResource("examples/list-bean-3.yaml"); - // System.out.println(output); - TypeDescription descr = new TypeDescription(ListBean.class); - descr.putListPropertyType("developers", Developer.class); - Yaml beanLoader = new Yaml(new Constructor(descr)); - ListBean parsed = beanLoader.loadAs(output, ListBean.class); - assertNotNull(parsed); - List<Human> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - assertEquals("Committer must be recognised.", Developer.class, developers.get(0).getClass()); - Developer fred = (Developer) developers.get(0); - assertEquals("Fred", fred.getName()); - assertEquals("creator", fred.getRole()); - Developer john = (Developer) developers.get(1); - assertEquals("John", john.getName()); - assertEquals("committer", john.getRole()); + /** + * explicit TypeDescription is more important then runtime class (which may be an interface) + */ + public void testLoadList2() { + String output = Util.getLocalResource("examples/list-bean-3.yaml"); + // System.out.println(output); + TypeDescription descr = new TypeDescription(ListBean.class); + descr.putListPropertyType("developers", Developer.class); + Yaml beanLoader = new Yaml(new Constructor(descr)); + ListBean parsed = beanLoader.loadAs(output, ListBean.class); + assertNotNull(parsed); + List<Human> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + assertEquals("Committer must be recognised.", Developer.class, developers.get(0).getClass()); + Developer fred = (Developer) developers.get(0); + assertEquals("Fred", fred.getName()); + assertEquals("creator", fred.getRole()); + Developer john = (Developer) developers.get(1); + assertEquals("John", john.getName()); + assertEquals("committer", john.getRole()); + } + + public static class ListBean { + + private String name; + private List<Human> developers; + + public ListBean() { + name = "Bean123"; } - public static class ListBean { - private String name; - private List<Human> developers; - - public ListBean() { - name = "Bean123"; - } - - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List<Human> getDevelopers() { - return developers; - } + public List<Human> getDevelopers() { + return developers; + } - public void setDevelopers(List<Human> developers) { - this.developers = developers; - } + public void setDevelopers(List<Human> developers) { + this.developers = developers; } + } - public static interface Human { + public interface Human { - public String getName(); + String getName(); - public void setName(String name); + void setName(String name); - } + } + + public static class Developer implements Human { - public static class Developer implements Human { - private String name; - private String role; + private String name; + private String role; - public Developer() { - } + public Developer() {} - public Developer(String name, String role) { - this.name = name; - this.role = role; - } + public Developer(String name, String role) { + this.name = name; + this.role = role; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getRole() { - return role; - } + public String getRole() { + return role; + } - public void setRole(String role) { - this.role = role; - } + public void setRole(String role) { + this.role = role; } + } } diff --git a/src/test/java/examples/collections/TypeSafeSetImplementationsTest.java b/src/test/java/examples/collections/TypeSafeSetImplementationsTest.java index 297db144..56ba7855 100644 --- a/src/test/java/examples/collections/TypeSafeSetImplementationsTest.java +++ b/src/test/java/examples/collections/TypeSafeSetImplementationsTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.collections; @@ -20,9 +18,7 @@ import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -30,241 +26,244 @@ import org.yaml.snakeyaml.Yaml; * Test different Map implementations as JavaBean properties */ public class TypeSafeSetImplementationsTest extends TestCase { - public void testDumpSet() { - SetBean bean = new SetBean(); - SortedSet<String> sortedSet = new TreeSet<String>(); - sortedSet.add("two"); - sortedSet.add("one"); - sortedSet.add("three"); - bean.setSorted(sortedSet); - SortedSet<Developer> developers = new TreeSet<Developer>(); - developers.add(new Developer("John", "founder")); - developers.add(new Developer("Karl", "user")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/set-bean-1.yaml"); - assertEquals(etalon, output); - } - public void testDumpSet2() { - SetBean bean = new SetBean(); - SortedSet<String> sortedSet = new TreeSet<String>(); - sortedSet.add("two"); - sortedSet.add("one"); - sortedSet.add("three"); - bean.setSorted(sortedSet); - SortedSet<Developer> developers = new TreeSet<Developer>(); - developers.add(new Developer("John", "founder")); - developers.add(new Developer("Karl", "user")); - developers.add(new SuperDeveloper("Bill", "super")); - bean.setDevelopers(developers); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - String etalon = Util.getLocalResource("examples/set-bean-6.yaml"); - assertEquals(etalon, output); + public void testDumpSet() { + SetBean bean = new SetBean(); + SortedSet<String> sortedSet = new TreeSet<String>(); + sortedSet.add("two"); + sortedSet.add("one"); + sortedSet.add("three"); + bean.setSorted(sortedSet); + SortedSet<Developer> developers = new TreeSet<Developer>(); + developers.add(new Developer("John", "founder")); + developers.add(new Developer("Karl", "user")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/set-bean-1.yaml"); + assertEquals(etalon, output); + } + + public void testDumpSet2() { + SetBean bean = new SetBean(); + SortedSet<String> sortedSet = new TreeSet<String>(); + sortedSet.add("two"); + sortedSet.add("one"); + sortedSet.add("three"); + bean.setSorted(sortedSet); + SortedSet<Developer> developers = new TreeSet<Developer>(); + developers.add(new Developer("John", "founder")); + developers.add(new Developer("Karl", "user")); + developers.add(new SuperDeveloper("Bill", "super")); + bean.setDevelopers(developers); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + String etalon = Util.getLocalResource("examples/set-bean-6.yaml"); + assertEquals(etalon, output); + } + + public void testLoadSet() { + String output = Util.getLocalResource("examples/set-bean-1.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + SetBean parsed = beanLoader.loadAs(output, SetBean.class); + assertNotNull(parsed); + SortedSet<String> sortedMap = parsed.getSorted(); + assertEquals(3, sortedMap.size()); + assertTrue(sortedMap.contains("one")); + assertTrue(sortedMap.contains("two")); + assertTrue(sortedMap.contains("three")); + String first = sortedMap.iterator().next(); + assertEquals("one", first); + // + SortedSet<Developer> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + assertEquals("John", developers.first().getName()); + assertEquals("Karl", developers.last().getName()); + } + + public void testLoadSetReversed() { + String output = Util.getLocalResource("examples/set-bean-2.yaml"); + // System.out.println(output); + Yaml beanLoader = new Yaml(); + SetBean parsed = beanLoader.loadAs(output, SetBean.class); + assertNotNull(parsed); + SortedSet<String> sortedMap = parsed.getSorted(); + assertEquals(3, sortedMap.size()); + assertTrue(sortedMap.contains("one")); + assertTrue(sortedMap.contains("two")); + assertTrue(sortedMap.contains("three")); + // alphabetically: one, three, two + assertEquals("one", sortedMap.first()); + assertEquals("two", sortedMap.last()); + // the order is not from YAML (must be sorted) + SortedSet<Developer> developers = parsed.getDevelopers(); + assertEquals(2, developers.size()); + assertEquals("John", developers.first().getName()); + assertEquals("Karl", developers.last().getName()); + } + + public static class SetBean { + + private SortedSet<String> sorted; + private SortedSet<Developer> developers; + private String name; + + public SetBean() { + name = "Bean123"; } - public void testLoadSet() { - String output = Util.getLocalResource("examples/set-bean-1.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - SetBean parsed = beanLoader.loadAs(output, SetBean.class); - assertNotNull(parsed); - SortedSet<String> sortedMap = parsed.getSorted(); - assertEquals(3, sortedMap.size()); - assertTrue(sortedMap.contains("one")); - assertTrue(sortedMap.contains("two")); - assertTrue(sortedMap.contains("three")); - String first = sortedMap.iterator().next(); - assertEquals("one", first); - // - SortedSet<Developer> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - assertEquals("John", developers.first().getName()); - assertEquals("Karl", developers.last().getName()); + public SortedSet<String> getSorted() { + return sorted; } - public void testLoadSetReversed() { - String output = Util.getLocalResource("examples/set-bean-2.yaml"); - // System.out.println(output); - Yaml beanLoader = new Yaml(); - SetBean parsed = beanLoader.loadAs(output, SetBean.class); - assertNotNull(parsed); - SortedSet<String> sortedMap = parsed.getSorted(); - assertEquals(3, sortedMap.size()); - assertTrue(sortedMap.contains("one")); - assertTrue(sortedMap.contains("two")); - assertTrue(sortedMap.contains("three")); - // alphabetically: one, three, two - assertEquals("one", sortedMap.first()); - assertEquals("two", sortedMap.last()); - // the order is not from YAML (must be sorted) - SortedSet<Developer> developers = parsed.getDevelopers(); - assertEquals(2, developers.size()); - assertEquals("John", developers.first().getName()); - assertEquals("Karl", developers.last().getName()); + public void setSorted(SortedSet<String> sorted) { + this.sorted = sorted; } - public static class SetBean { - private SortedSet<String> sorted; - private SortedSet<Developer> developers; - private String name; - - public SetBean() { - name = "Bean123"; - } - - public SortedSet<String> getSorted() { - return sorted; - } - - public void setSorted(SortedSet<String> sorted) { - this.sorted = sorted; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public SortedSet<Developer> getDevelopers() { - return developers; - } - - public void setDevelopers(SortedSet<Developer> developers) { - this.developers = developers; - } + public String getName() { + return name; } - public static class Developer implements Comparable<Developer> { - private String name; - private String role; - - public Developer() { - } + public void setName(String name) { + this.name = name; + } - public Developer(String name, String role) { - this.name = name; - this.role = role; - } + public SortedSet<Developer> getDevelopers() { + return developers; + } - public String getName() { - return name; - } + public void setDevelopers(SortedSet<Developer> developers) { + this.developers = developers; + } + } - public void setName(String name) { - this.name = name; - } + public static class Developer implements Comparable<Developer> { - public String getRole() { - return role; - } + private String name; + private String role; - public void setRole(String role) { - this.role = role; - } + public Developer() {} - public int compareTo(Developer o) { - return name.compareTo(o.name); - } + public Developer(String name, String role) { + this.name = name; + this.role = role; } - public static class SuperDeveloper extends Developer { + public String getName() { + return name; + } - public SuperDeveloper() { - super(); - } + public void setName(String name) { + this.name = name; + } - public SuperDeveloper(String string, String string2) { - super(string, string2); - } + public String getRole() { + return role; + } + public void setRole(String role) { + this.role = role; } - @SuppressWarnings("unchecked") - public void testNoJavaBeanSetRecursive() { - Set<Object> set = new HashSet<Object>(3); - set.add("aaa"); - set.add(111); - Box box = new Box(); - box.setId("id123"); - box.setSet(set); - set.add(box); - Yaml yaml = new Yaml(); - String output = yaml.dump(set); - // System.out.println(output); - // the order may differ on different JVMs - // String etalon = Util.getLocalResource("examples/set-bean-3.yaml"); - // assertEquals(etalon, output); - assertTrue(output.contains("&id001 !!set")); - assertTrue(output.contains("? !!examples.collections.TypeSafeSetImplementationsTest$Box")); - assertTrue(output.contains("set: *id001")); - assertTrue(output.contains("111: null")); - // load - Set<Object> list2 = (Set<Object>) yaml.load(output); - assertEquals(3, list2.size()); - assertTrue(list2.contains("aaa")); - assertTrue(list2.contains(111)); + public int compareTo(Developer o) { + return name.compareTo(o.name); } + } - public static class Box { - private String id; - private Set<Object> set; + public static class SuperDeveloper extends Developer { - public String getId() { - return id; - } + public SuperDeveloper() { + super(); + } - public void setId(String id) { - this.id = id; - } + public SuperDeveloper(String string, String string2) { + super(string, string2); + } - public Set<Object> getSet() { - return set; - } + } + + @SuppressWarnings("unchecked") + public void testNoJavaBeanSetRecursive() { + Set<Object> set = new HashSet<Object>(3); + set.add("aaa"); + set.add(111); + Box box = new Box(); + box.setId("id123"); + box.setSet(set); + set.add(box); + Yaml yaml = new Yaml(); + String output = yaml.dump(set); + // System.out.println(output); + // the order may differ on different JVMs + // String etalon = Util.getLocalResource("examples/set-bean-3.yaml"); + // assertEquals(etalon, output); + assertTrue(output.contains("&id001 !!set")); + assertTrue(output.contains("? !!examples.collections.TypeSafeSetImplementationsTest$Box")); + assertTrue(output.contains("set: *id001")); + assertTrue(output.contains("111: null")); + // load + Set<Object> list2 = yaml.load(output); + assertEquals(3, list2.size()); + assertTrue(list2.contains("aaa")); + assertTrue(list2.contains(111)); + } + + public static class Box { + + private String id; + private Set<Object> set; + + public String getId() { + return id; + } - public void setSet(Set<Object> set) { - this.set = set; - } + public void setId(String id) { + this.id = id; } - @SuppressWarnings("unchecked") - public void testNoJavaBeanSet() { - Yaml yaml = new Yaml(); - String output = Util.getLocalResource("examples/set-bean-4.yaml"); - // System.out.println(output); - // load - Set<String> set = (Set<String>) yaml.load(output); - assertEquals(3, set.size()); - assertTrue(set.contains("aaa")); - assertTrue(set.contains("bbb")); - assertTrue(set.contains("zzz")); - Iterator<String> iter = set.iterator(); - assertEquals("bbb", iter.next()); - assertEquals("aaa", iter.next()); - assertEquals("zzz", iter.next()); + public Set<Object> getSet() { + return set; } - @SuppressWarnings("unchecked") - public void testNoJavaBeanSet2() { - Yaml yaml = new Yaml(); - String output = Util.getLocalResource("examples/set-bean-5.yaml"); - // System.out.println(output); - // load and sort - Set<String> set = (Set<String>) yaml.load(output); - assertEquals(3, set.size()); - assertTrue(set.contains("aaa")); - assertTrue(set.contains("bbb")); - assertTrue(set.contains("zzz")); - Iterator<String> iter = set.iterator(); - assertEquals("aaa", iter.next()); - assertEquals("bbb", iter.next()); - assertEquals("zzz", iter.next()); + public void setSet(Set<Object> set) { + this.set = set; } + } + + @SuppressWarnings("unchecked") + public void testNoJavaBeanSet() { + Yaml yaml = new Yaml(); + String output = Util.getLocalResource("examples/set-bean-4.yaml"); + // System.out.println(output); + // load + Set<String> set = yaml.load(output); + assertEquals(3, set.size()); + assertTrue(set.contains("aaa")); + assertTrue(set.contains("bbb")); + assertTrue(set.contains("zzz")); + Iterator<String> iter = set.iterator(); + assertEquals("bbb", iter.next()); + assertEquals("aaa", iter.next()); + assertEquals("zzz", iter.next()); + } + + @SuppressWarnings("unchecked") + public void testNoJavaBeanSet2() { + Yaml yaml = new Yaml(); + String output = Util.getLocalResource("examples/set-bean-5.yaml"); + // System.out.println(output); + // load and sort + Set<String> set = yaml.load(output); + assertEquals(3, set.size()); + assertTrue(set.contains("aaa")); + assertTrue(set.contains("bbb")); + assertTrue(set.contains("zzz")); + Iterator<String> iter = set.iterator(); + assertEquals("aaa", iter.next()); + assertEquals("bbb", iter.next()); + assertEquals("zzz", iter.next()); + } } diff --git a/src/test/java/examples/enumset/Day.java b/src/test/java/examples/enumset/Day.java new file mode 100644 index 00000000..624cdb97 --- /dev/null +++ b/src/test/java/examples/enumset/Day.java @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples.enumset; + +public enum Day { + MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY +} diff --git a/src/test/java/examples/enumset/YamlEnumSetTest.java b/src/test/java/examples/enumset/YamlEnumSetTest.java new file mode 100644 index 00000000..d71e587d --- /dev/null +++ b/src/test/java/examples/enumset/YamlEnumSetTest.java @@ -0,0 +1,144 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples.enumset; + +import java.util.EnumSet; +import org.junit.Assert; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.nodes.Node; + +public class YamlEnumSetTest { + + Day day; + EnumSet<Day> setOfDays; + + public Day getDay() { + return this.day; + } + + public void setDay(Day day) { + this.day = day; + } + + public EnumSet<Day> getSetOfDays() { + return this.setOfDays; + } + + public void setSetOfDays(EnumSet<Day> setOfDays) { + this.setOfDays = setOfDays; + } + + @Test + public void enumSetDumpLoad() { + + YamlEnumSetTest yEST = new YamlEnumSetTest(); + yEST.day = Day.SUNDAY; + yEST.setOfDays = EnumSet.of(Day.MONDAY, Day.WEDNESDAY, Day.FRIDAY); + + String output = createYaml().dump(yEST); + YamlEnumSetTest loaded = createYaml().loadAs(output, YamlEnumSetTest.class); + Assert.assertSame(loaded.day, Day.SUNDAY); + + Object[] expected = yEST.setOfDays.toArray(); + Object[] actual = loaded.setOfDays.toArray(); + + Assert.assertArrayEquals(expected, actual); + Assert.assertEquals(yEST.setOfDays, loaded.setOfDays); + } + + @Test + public void enumSetLoadWithoutTags() { + + YamlEnumSetTest yEST = new YamlEnumSetTest(); + yEST.day = Day.SUNDAY; + yEST.setOfDays = EnumSet.of(Day.MONDAY, Day.WEDNESDAY, Day.FRIDAY); + + String yamlStr = "day: SUNDAY\nsetOfDays: { MONDAY, WEDNESDAY, FRIDAY }\n"; + YamlEnumSetTest loaded = createYaml().loadAs(yamlStr, YamlEnumSetTest.class); + Assert.assertSame(loaded.day, Day.SUNDAY); + + Object[] expected = yEST.setOfDays.toArray(); + Object[] actual = loaded.setOfDays.toArray(); + + Assert.assertArrayEquals(expected, actual); + Assert.assertEquals(yEST.setOfDays, loaded.setOfDays); + } + + @Test + public void enumSetLoadWithoutCaseSensitive() { + // given + LoaderOptions loaderOptions = new LoaderOptions(); + loaderOptions.setEnumCaseSensitive(false); + + YamlEnumSetTest yEST = new YamlEnumSetTest(); + yEST.day = Day.SUNDAY; + yEST.setOfDays = EnumSet.of(Day.MONDAY, Day.WEDNESDAY, Day.FRIDAY); + + String yamlStr = "day: SUNDAY\nsetOfDays: { MONDAY, wednesday, friDay }\n"; + + // when + YamlEnumSetTest loaded = createYaml(loaderOptions).loadAs(yamlStr, YamlEnumSetTest.class); + + // then + Assert.assertSame(loaded.day, Day.SUNDAY); + + Object[] expected = yEST.setOfDays.toArray(); + Object[] actual = loaded.setOfDays.toArray(); + + Assert.assertArrayEquals(expected, actual); + Assert.assertEquals(yEST.setOfDays, loaded.setOfDays); + } + + @Test(expected = YAMLException.class) + public void enumSetLoadWithCaseSensitive() { + YamlEnumSetTest yEST = new YamlEnumSetTest(); + yEST.day = Day.SUNDAY; + yEST.setOfDays = EnumSet.of(Day.MONDAY, Day.WEDNESDAY, Day.FRIDAY); + + String yamlStr = "day: SUNDAY\nsetOfDays: { MONDAY, wednesday, friDay }\n"; + + // when + createYaml().loadAs(yamlStr, YamlEnumSetTest.class); + } + + private Yaml createYaml(LoaderOptions loaderOptions) { + Yaml yaml = loaderOptions != null ? new Yaml(loaderOptions) : new Yaml(); + + TypeDescription yamlEnumSetTD = new TypeDescription(YamlEnumSetTest.class) { + + @Override + public Object newInstance(String propertyName, Node node) { + if ("setOfDays".equals(propertyName)) { + node.setTwoStepsConstruction(true); + return EnumSet.noneOf(Day.class); + } + return super.newInstance(propertyName, node); + } + }; + + yaml.addTypeDescription(yamlEnumSetTD); + + return yaml; + } + + private Yaml createYaml() { + return createYaml(null); + } + + +} diff --git a/src/test/java/examples/jodatime/JodaTimeExampleTest.java b/src/test/java/examples/jodatime/JodaTimeExampleTest.java index 0112608e..f5960031 100644 --- a/src/test/java/examples/jodatime/JodaTimeExampleTest.java +++ b/src/test/java/examples/jodatime/JodaTimeExampleTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.jodatime; import java.util.Date; - import junit.framework.TestCase; - import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -31,90 +27,95 @@ import org.yaml.snakeyaml.nodes.NodeId; import org.yaml.snakeyaml.nodes.Tag; public class JodaTimeExampleTest extends TestCase { - private static final long timestamp = 1000000000000L; - - public void testDump() { - DateTime time = new DateTime(timestamp, DateTimeZone.UTC); - Yaml yaml = new Yaml(new JodaTimeRepresenter()); - String joda = yaml.dump(time); - String date = new Yaml().dump(new Date(timestamp)); - assertEquals(date, joda); - assertEquals("2001-09-09T01:46:40Z\n", joda); - } - public void testLoad() { - Yaml yaml = new Yaml(new JodaTimeImplicitContructor()); - DateTime time = (DateTime) yaml.load("2001-09-09T01:46:40Z"); - assertEquals(new DateTime(timestamp, DateTimeZone.UTC), time); - } + private static final long timestamp = 1000000000000L; + + public void testDump() { + DateTime time = new DateTime(timestamp, DateTimeZone.UTC); + Yaml yaml = new Yaml(new JodaTimeRepresenter()); + String joda = yaml.dump(time); + String date = new Yaml().dump(new Date(timestamp)); + assertEquals(date, joda); + assertEquals("2001-09-09T01:46:40Z\n", joda); + } - /** - * test issue 109 - */ - public void test109() { - Date someDate = new DateMidnight(9, 2, 21, DateTimeZone.forID("Europe/Amsterdam")).toDate(); - Yaml yaml = new Yaml(); - String timestamp = yaml.dump(someDate); - assertEquals("0009-02-22T23:40:28Z\n", timestamp); - // System.out.println(timestamp); - Object o = yaml.load(timestamp); - assertEquals(someDate, o); + public void testLoad() { + Yaml yaml = new Yaml(new JodaTimeImplicitContructor()); + DateTime time = yaml.load("2001-09-09T01:46:40Z"); + assertEquals(new DateTime(timestamp, DateTimeZone.UTC), time); + } + + /** + * test issue 109 + */ + public void test109() { + Date someDate = new DateMidnight(9, 2, 21, DateTimeZone.forID("Europe/Amsterdam")).toDate(); + Yaml yaml = new Yaml(); + String timestamp = yaml.dump(someDate); + assertEquals("0009-02-22T23:40:28Z\n", timestamp); + // System.out.println(timestamp); + Object o = yaml.load(timestamp); + assertEquals(someDate, o); + } + + class JodaPropertyConstructor extends Constructor { + + public JodaPropertyConstructor() { + yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct()); } - class JodaPropertyConstructor extends Constructor { - public JodaPropertyConstructor() { - yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct()); - } + class TimeStampConstruct extends Constructor.ConstructScalar { - class TimeStampConstruct extends Constructor.ConstructScalar { - @Override - public Object construct(Node nnode) { - if (nnode.getTag().equals("tag:yaml.org,2002:timestamp")) { - Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP); - Date date = (Date) dateConstructor.construct(nnode); - return new DateTime(date, DateTimeZone.UTC); - } else { - return super.construct(nnode); - } - } + @Override + public Object construct(Node nnode) { + if (nnode.getTag().equals("tag:yaml.org,2002:timestamp")) { + Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP); + Date date = (Date) dateConstructor.construct(nnode); + return new DateTime(date, DateTimeZone.UTC); + } else { + return super.construct(nnode); } + } } + } - /** - * This class should be used if JodaTime may appear with a tag or as a - * JavaBean property - */ - public class JodaTimeConstructor extends Constructor { - private final Construct javaDateConstruct; - private final Construct jodaDateConstruct; - - public JodaTimeConstructor() { - javaDateConstruct = new ConstructYamlTimestamp(); - jodaDateConstruct = new ConstructJodaTimestamp(); - // Whenever we see an explicit timestamp tag, make a Joda Date - // instead - yamlConstructors.put(Tag.TIMESTAMP, jodaDateConstruct); - // See - // We need this to work around implicit construction. - yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct()); - } + /** + * This class should be used if JodaTime may appear with a tag or as a JavaBean property + */ + public class JodaTimeConstructor extends Constructor { - public class ConstructJodaTimestamp extends AbstractConstruct { - public Object construct(Node node) { - Date date = (Date) javaDateConstruct.construct(node); - return new DateTime(date, DateTimeZone.UTC); - } - } + private final Construct javaDateConstruct; + private final Construct jodaDateConstruct; + + public JodaTimeConstructor() { + javaDateConstruct = new ConstructYamlTimestamp(); + jodaDateConstruct = new ConstructJodaTimestamp(); + // Whenever we see an explicit timestamp tag, make a Joda Date + // instead + yamlConstructors.put(Tag.TIMESTAMP, jodaDateConstruct); + // See + // We need this to work around implicit construction. + yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct()); + } + + public class ConstructJodaTimestamp extends AbstractConstruct { + + public Object construct(Node node) { + Date date = (Date) javaDateConstruct.construct(node); + return new DateTime(date, DateTimeZone.UTC); + } + } + + class TimeStampConstruct extends Constructor.ConstructScalar { - class TimeStampConstruct extends Constructor.ConstructScalar { - @Override - public Object construct(Node nnode) { - if (nnode.getTag().equals(Tag.TIMESTAMP)) { - return jodaDateConstruct.construct(nnode); - } else { - return super.construct(nnode); - } - } + @Override + public Object construct(Node nnode) { + if (nnode.getTag().equals(Tag.TIMESTAMP)) { + return jodaDateConstruct.construct(nnode); + } else { + return super.construct(nnode); } + } } + } } diff --git a/src/test/java/examples/jodatime/JodaTimeFlowStylesTest.java b/src/test/java/examples/jodatime/JodaTimeFlowStylesTest.java index 901385a0..ce7ab2ec 100644 --- a/src/test/java/examples/jodatime/JodaTimeFlowStylesTest.java +++ b/src/test/java/examples/jodatime/JodaTimeFlowStylesTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.jodatime; import java.util.Date; import java.util.List; - import junit.framework.TestCase; - import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.yaml.snakeyaml.DumperOptions; @@ -34,121 +30,117 @@ import org.yaml.snakeyaml.nodes.NodeId; import org.yaml.snakeyaml.nodes.Tag; public class JodaTimeFlowStylesTest extends TestCase { - private static final long timestamp = 1000000000000L; - /** - * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=128"></a> - */ - public void testLoadBeanWithBlockFlow() { - MyBean bean = new MyBean(); - bean.setId("id123"); - DateTime etalon = new DateTime(timestamp, DateTimeZone.UTC); - bean.setDate(etalon); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml dumper = new Yaml(new JodaTimeRepresenter(), options); - // compare Nodes with flow style AUTO and flow style BLOCK - Node node1 = dumper.represent(bean); - DumperOptions options2 = new DumperOptions(); - options2.setDefaultFlowStyle(FlowStyle.AUTO); - Yaml dumper2 = new Yaml(new JodaTimeRepresenter(), options2); - Node node2 = dumper2.represent(bean); - assertEquals(node2.toString(), node1.toString()); - // compare Events with flow style AUTO and flow style BLOCK - List<Event> events1 = dumper.serialize(node1); - List<Event> events2 = dumper2.serialize(node2); - assertEquals(events2.size(), events1.size()); - int i = 0; - for (Event etalonEvent : events2) { - assertEquals(etalonEvent, events1.get(i++)); - if (etalonEvent instanceof ScalarEvent) { - ScalarEvent scalar = (ScalarEvent) etalonEvent; - if (scalar.getValue().equals("2001-09-09T01:46:40Z")) { - assertTrue(scalar.getImplicit().canOmitTagInPlainScalar()); - assertFalse(scalar.getImplicit().canOmitTagInNonPlainScalar()); - } - } - } - // Nodes and Events are the same. Only emitter may influence the output. - String doc1 = dumper.dump(bean); - // System.out.println(doc1); - /* - * 'date' must be used only with the explicit '!!timestamp' tag. - * Implicit tag will not work because 'date' is the JavaBean property - * and in this case the empty constructor of the class will be used. - * Since this constructor does not exist for JodaTime an exception will - * be thrown. - */ - assertEquals("!!examples.jodatime.MyBean\ndate: 2001-09-09T01:46:40Z\nid: id123\n", doc1); - /* - * provided JodaTimeContructor will be ignored because 'date' is a - * JavaBean property and its class gets more priority then the implicit - * '!!timestamp' tag. - */ - Yaml loader = new Yaml(new JodaTimeImplicitContructor()); - try { - loader.load(doc1); - } catch (Exception e) { - assertTrue( - "The error must indicate that JodaTime cannot be created from the scalar value.", - e.getMessage() - .contains( - "No String constructor found. Exception=org.joda.time.DateTime.<init>(java.lang.String)")); + private static final long timestamp = 1000000000000L; + + /** + * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=128">issue 128</a> + */ + public void testLoadBeanWithBlockFlow() { + MyBean bean = new MyBean(); + bean.setId("id123"); + DateTime etalon = new DateTime(timestamp, DateTimeZone.UTC); + bean.setDate(etalon); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml dumper = new Yaml(new JodaTimeRepresenter(), options); + // compare Nodes with flow style AUTO and flow style BLOCK + Node node1 = dumper.represent(bean); + DumperOptions options2 = new DumperOptions(); + options2.setDefaultFlowStyle(FlowStyle.AUTO); + Yaml dumper2 = new Yaml(new JodaTimeRepresenter(), options2); + Node node2 = dumper2.represent(bean); + assertEquals(node2.toString(), node1.toString()); + // compare Events with flow style AUTO and flow style BLOCK + List<Event> events1 = dumper.serialize(node1); + List<Event> events2 = dumper2.serialize(node2); + assertEquals(events2.size(), events1.size()); + int i = 0; + for (Event etalonEvent : events2) { + assertEquals(etalonEvent, events1.get(i++)); + if (etalonEvent instanceof ScalarEvent) { + ScalarEvent scalar = (ScalarEvent) etalonEvent; + if (scalar.getValue().equals("2001-09-09T01:46:40Z")) { + assertTrue(scalar.getImplicit().canOmitTagInPlainScalar()); + assertFalse(scalar.getImplicit().canOmitTagInNonPlainScalar()); } - // we have to provide a special way to create JodaTime instances from - // scalars - Yaml loader2 = new Yaml(new JodaPropertyConstructor()); - MyBean parsed = (MyBean) loader2.load(doc1); - assertEquals(etalon, parsed.getDate()); + } } - - /** - * !!timestamp must be used, without it the implicit tag will be ignored - * because 'date' is the JavaBean property. - * - * Since the timestamp contains ':' character it cannot use plain scalar - * style in the FLOW mapping style. Emitter suggests single quoted scalar - * style and that is why the explicit '!!timestamp' is present in the YAML - * document. - * - * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=128"></a> - * + // Nodes and Events are the same. Only emitter may influence the output. + String doc1 = dumper.dump(bean); + // System.out.println(doc1); + /* + * 'date' must be used only with the explicit '!!timestamp' tag. Implicit tag will not work + * because 'date' is the JavaBean property and in this case the empty constructor of the class + * will be used. Since this constructor does not exist for JodaTime an exception will be thrown. */ - public void testLoadBeanWithAutoFlow() { - MyBean bean = new MyBean(); - bean.setId("id123"); - DateTime etalon = new DateTime(timestamp, DateTimeZone.UTC); - bean.setDate(etalon); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.AUTO); - Yaml dumper = new Yaml(new JodaTimeRepresenter(), options); - String doc = dumper.dump(bean); - // System.out.println(doc); - assertEquals( - "!!examples.jodatime.MyBean {date: !!timestamp '2001-09-09T01:46:40Z', id: id123}\n", - doc); - Yaml loader = new Yaml(new JodaTimeImplicitContructor()); - MyBean parsed = (MyBean) loader.load(doc); - assertEquals(etalon, parsed.getDate()); + assertEquals("!!examples.jodatime.MyBean\ndate: 2001-09-09T01:46:40Z\nid: id123\n", doc1); + /* + * provided JodaTimeContructor will be ignored because 'date' is a JavaBean property and its + * class gets more priority then the implicit '!!timestamp' tag. + */ + Yaml loader = new Yaml(new JodaTimeImplicitContructor()); + try { + loader.load(doc1); + } catch (Exception e) { + assertTrue("The error must indicate that JodaTime cannot be created from the scalar value.", + e.getMessage().contains( + "No String constructor found. Exception=org.joda.time.DateTime.<init>(java.lang.String)")); } + // we have to provide a special way to create JodaTime instances from + // scalars + Yaml loader2 = new Yaml(new JodaPropertyConstructor()); + MyBean parsed = loader2.load(doc1); + assertEquals(etalon, parsed.getDate()); + } - private class JodaPropertyConstructor extends Constructor { - public JodaPropertyConstructor() { - yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct()); - } + /** + * !!timestamp must be used, without it the implicit tag will be ignored because 'date' is the + * JavaBean property. + * + * Since the timestamp contains ':' character it cannot use plain scalar style in the FLOW mapping + * style. Emitter suggests single quoted scalar style and that is why the explicit '!!timestamp' + * is present in the YAML document. + * + * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=128">issue 128</a> + * + */ + public void testLoadBeanWithAutoFlow() { + MyBean bean = new MyBean(); + bean.setId("id123"); + DateTime etalon = new DateTime(timestamp, DateTimeZone.UTC); + bean.setDate(etalon); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.AUTO); + Yaml dumper = new Yaml(new JodaTimeRepresenter(), options); + String doc = dumper.dump(bean); + // System.out.println(doc); + assertEquals( + "!!examples.jodatime.MyBean {date: !!timestamp '2001-09-09T01:46:40Z', id: id123}\n", doc); + Yaml loader = new Yaml(new JodaTimeImplicitContructor()); + MyBean parsed = loader.load(doc); + assertEquals(etalon, parsed.getDate()); + } + + private class JodaPropertyConstructor extends Constructor { - class TimeStampConstruct extends Constructor.ConstructScalar { - @Override - public Object construct(Node nnode) { - if (nnode.getTag().equals(new Tag("tag:yaml.org,2002:timestamp"))) { - Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP); - Date date = (Date) dateConstructor.construct(nnode); - return new DateTime(date, DateTimeZone.UTC); - } else { - return super.construct(nnode); - } - } + public JodaPropertyConstructor() { + yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct()); + } + + class TimeStampConstruct extends Constructor.ConstructScalar { + @Override + public Object construct(Node nnode) { + if (nnode.getTag().equals(new Tag("tag:yaml.org,2002:timestamp"))) { + Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP); + Date date = (Date) dateConstructor.construct(nnode); + return new DateTime(date, DateTimeZone.UTC); + } else { + return super.construct(nnode); } + } + } + } } diff --git a/src/test/java/examples/jodatime/JodaTimeImplicitContructor.java b/src/test/java/examples/jodatime/JodaTimeImplicitContructor.java index e1af4288..667815ef 100644 --- a/src/test/java/examples/jodatime/JodaTimeImplicitContructor.java +++ b/src/test/java/examples/jodatime/JodaTimeImplicitContructor.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.jodatime; import java.util.Date; - import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.yaml.snakeyaml.constructor.Constructor; @@ -27,14 +24,16 @@ import org.yaml.snakeyaml.nodes.Tag; * It works only when JodaTime is not a JavaBean property */ public class JodaTimeImplicitContructor extends Constructor { - public JodaTimeImplicitContructor() { - this.yamlConstructors.put(Tag.TIMESTAMP, new ConstructJodaTimestamp()); - } - private class ConstructJodaTimestamp extends ConstructYamlTimestamp { - public Object construct(Node node) { - Date date = (Date) super.construct(node); - return new DateTime(date, DateTimeZone.UTC); - } + public JodaTimeImplicitContructor() { + this.yamlConstructors.put(Tag.TIMESTAMP, new ConstructJodaTimestamp()); + } + + private class ConstructJodaTimestamp extends ConstructYamlTimestamp { + + public Object construct(Node node) { + Date date = (Date) super.construct(node); + return new DateTime(date, DateTimeZone.UTC); } + } } diff --git a/src/test/java/examples/jodatime/JodaTimeRepresenter.java b/src/test/java/examples/jodatime/JodaTimeRepresenter.java index f7fd8242..305f67d0 100644 --- a/src/test/java/examples/jodatime/JodaTimeRepresenter.java +++ b/src/test/java/examples/jodatime/JodaTimeRepresenter.java @@ -1,36 +1,34 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.jodatime; import java.util.Date; - import org.joda.time.DateTime; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.representer.Representer; class JodaTimeRepresenter extends Representer { - public JodaTimeRepresenter() { - multiRepresenters.put(DateTime.class, new RepresentJodaDateTime()); - } - private class RepresentJodaDateTime extends RepresentDate { + public JodaTimeRepresenter() { + multiRepresenters.put(DateTime.class, new RepresentJodaDateTime()); + } + + private class RepresentJodaDateTime extends RepresentDate { - public Node representData(Object data) { - DateTime date = (DateTime) data; - return super.representData(new Date(date.getMillis())); - } + public Node representData(Object data) { + DateTime date = (DateTime) data; + return super.representData(new Date(date.getMillis())); } -}
\ No newline at end of file + } +} diff --git a/src/test/java/examples/jodatime/MyBean.java b/src/test/java/examples/jodatime/MyBean.java index 5957ae58..919cbe0f 100644 --- a/src/test/java/examples/jodatime/MyBean.java +++ b/src/test/java/examples/jodatime/MyBean.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.jodatime; import org.joda.time.DateTime; public class MyBean { - private String id; - private DateTime date; - public String getId() { - return id; - } + private String id; + private DateTime date; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public DateTime getDate() { - return date; - } + public void setId(String id) { + this.id = id; + } - public void setDate(DateTime date) { - this.date = date; - } -}
\ No newline at end of file + public DateTime getDate() { + return date; + } + + public void setDate(DateTime date) { + this.date = date; + } +} diff --git a/src/test/java/examples/resolver/CustomResolver.java b/src/test/java/examples/resolver/CustomResolver.java index 4e3f71cd..3ce73b54 100644 --- a/src/test/java/examples/resolver/CustomResolver.java +++ b/src/test/java/examples/resolver/CustomResolver.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.resolver; @@ -20,16 +18,16 @@ import org.yaml.snakeyaml.resolver.Resolver; public class CustomResolver extends Resolver { - /* - * do not resolve float and timestamp - */ - protected void addImplicitResolvers() { - addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO"); - // addImplicitResolver(Tags.FLOAT, FLOAT, "-+0123456789."); - addImplicitResolver(Tag.INT, INT, "-+0123456789"); - addImplicitResolver(Tag.MERGE, MERGE, "<"); - addImplicitResolver(Tag.NULL, NULL, "~nN\0"); - addImplicitResolver(Tag.NULL, EMPTY, null); - // addImplicitResolver(Tags.TIMESTAMP, TIMESTAMP, "0123456789"); - } + /* + * do not resolve float and timestamp + */ + protected void addImplicitResolvers() { + addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO"); + // addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); + addImplicitResolver(Tag.INT, INT, "-+0123456789"); + addImplicitResolver(Tag.MERGE, MERGE, "<"); + addImplicitResolver(Tag.NULL, NULL, "~nN\0"); + addImplicitResolver(Tag.NULL, EMPTY, null); + // addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789"); + } } diff --git a/src/test/java/examples/resolver/CustomResolverTest.java b/src/test/java/examples/resolver/CustomResolverTest.java index e647a251..bd652517 100644 --- a/src/test/java/examples/resolver/CustomResolverTest.java +++ b/src/test/java/examples/resolver/CustomResolverTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.resolver; import java.util.HashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; @@ -27,30 +23,50 @@ import org.yaml.snakeyaml.representer.Representer; public class CustomResolverTest extends TestCase { - public void testResolverToDump() { - Map<Object, Object> map = new HashMap<Object, Object>(); - map.put("1.0", "2009-01-01"); - Yaml yaml = new Yaml(new Constructor(), new Representer(), new DumperOptions(), - new CustomResolver()); - String output = yaml.dump(map); - assertEquals("{1.0: 2009-01-01}\n", output); - assertEquals("Float and Date must be escaped.", "{'1.0': '2009-01-01'}\n", - new Yaml().dump(map)); - } + public void testResolverToDump() { + Map<Object, Object> map = new HashMap<Object, Object>(); + map.put("1.0", "2009-01-01"); + Yaml yaml = + new Yaml(new Constructor(), new Representer(), new DumperOptions(), new CustomResolver()); + String output = yaml.dump(map); + assertEquals("{1.0: 2009-01-01}\n", output); + assertEquals("Float and Date must be escaped.", "{'1.0': '2009-01-01'}\n", + new Yaml().dump(map)); + } + + @SuppressWarnings("unchecked") + public void testResolverToLoad() { + Yaml yaml = + new Yaml(new Constructor(), new Representer(), new DumperOptions(), new CustomResolver()); + Map<Object, Object> map = yaml.load("1.0: 2009-01-01"); + assertEquals(1, map.size()); + assertEquals("2009-01-01", map.get("1.0")); + // the default Resolver shall create Date and Double from the same YAML + // document + Yaml yaml2 = new Yaml(); + Map<Object, Object> map2 = yaml2.load("1.0: 2009-01-01"); + assertEquals(1, map2.size()); + assertFalse(map2.containsKey("1.0")); + assertTrue(map2.toString(), map2.containsKey(Double.valueOf(1.0))); + } + + /** + * https://bitbucket.org/snakeyaml/snakeyaml/issues/454/snakeyaml-implicitly-converts-time-into + */ + public void testResolverToLoadNoTime() { + Yaml yaml = new Yaml(new Constructor(), new Representer(), new DumperOptions(), + new NoTimeIntResolver()); + Map<Object, Object> map = yaml.load("a: 17:00:00\nb: 17"); + assertEquals(2, map.size()); + assertEquals("17:00:00", map.get("a")); + assertEquals(17, map.get("b")); + } - @SuppressWarnings("unchecked") - public void testResolverToLoad() { - Yaml yaml = new Yaml(new Constructor(), new Representer(), new DumperOptions(), - new CustomResolver()); - Map<Object, Object> map = (Map<Object, Object>) yaml.load("1.0: 2009-01-01"); - assertEquals(1, map.size()); - assertEquals("2009-01-01", map.get("1.0")); - // the default Resolver shall create Date and Double from the same YAML - // document - Yaml yaml2 = new Yaml(); - Map<Object, Object> map2 = (Map<Object, Object>) yaml2.load("1.0: 2009-01-01"); - assertEquals(1, map2.size()); - assertFalse(map2.containsKey("1.0")); - assertTrue(map2.toString(), map2.containsKey(new Double(1.0))); - } + public void testJsonBooleanResolverToLoad() { + Yaml yaml = new Yaml(new Constructor(), new Representer(), new DumperOptions(), + new JsonBooleanResolver()); + Map<Object, Object> map = yaml.load("no: true"); + assertEquals(1, map.size()); + assertEquals(true, map.get("no")); + } } diff --git a/src/test/java/examples/resolver/JsonBooleanResolver.java b/src/test/java/examples/resolver/JsonBooleanResolver.java new file mode 100644 index 00000000..e03253f0 --- /dev/null +++ b/src/test/java/examples/resolver/JsonBooleanResolver.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples.resolver; + +import java.util.regex.Pattern; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.resolver.Resolver; + +public class JsonBooleanResolver extends Resolver { + + public static final Pattern BOOL = Pattern.compile("^(?:true|false)$"); + + /* + * resolve boolean for only 2 values: true and false + */ + protected void addImplicitResolvers() { + addImplicitResolver(Tag.BOOL, BOOL, "tf"); + addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); + // define simple int pattern + addImplicitResolver(Tag.INT, INT, "0123456789"); + addImplicitResolver(Tag.MERGE, MERGE, "<"); + addImplicitResolver(Tag.NULL, NULL, "~nN\0"); + addImplicitResolver(Tag.NULL, EMPTY, null); + addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789"); + } +} diff --git a/src/test/java/examples/resolver/NoTimeIntResolver.java b/src/test/java/examples/resolver/NoTimeIntResolver.java new file mode 100644 index 00000000..47a64413 --- /dev/null +++ b/src/test/java/examples/resolver/NoTimeIntResolver.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples.resolver; + +import java.util.regex.Pattern; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.resolver.Resolver; + +/** + * resolve integers without the 12:00:00 pattern + */ +public class NoTimeIntResolver extends Resolver { + + public static final Pattern SIMPLE_INT = Pattern + .compile("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?(?:0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+)$"); + + /* + * resolve boolean for only 2 values: true and false + */ + protected void addImplicitResolvers() { + addImplicitResolver(Tag.BOOL, BOOL, "tf"); + // define simple int pattern + addImplicitResolver(Tag.INT, SIMPLE_INT, "-+0123456789"); + addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); + addImplicitResolver(Tag.MERGE, MERGE, "<"); + addImplicitResolver(Tag.NULL, NULL, "~nN\0"); + addImplicitResolver(Tag.NULL, EMPTY, null); + // addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789"); + } +} diff --git a/src/test/java/examples/spring/DataRegistry.java b/src/test/java/examples/spring/DataRegistry.java new file mode 100644 index 00000000..0711c0fa --- /dev/null +++ b/src/test/java/examples/spring/DataRegistry.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples.spring; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * This is a test bean that simulates storing external data that will be used for instantiating + * beans + * + * @since 2016-06-06 + * @author kibertoad + * + */ +public class DataRegistry { + + private final AtomicInteger counter = new AtomicInteger(1); + + /** + * Generates pseudodata of format "<id>]-<id>" + * + * @param id + * @return + */ + public String getDataForId(String id) { + return id + "-" + id; + } + + /** + * Returns next unassigned counter value + * + * @return + */ + public int getNextCounterValue() { + return counter.getAndIncrement(); + } +} diff --git a/src/test/java/examples/spring/TestEntity.java b/src/test/java/examples/spring/TestEntity.java new file mode 100644 index 00000000..05ed22df --- /dev/null +++ b/src/test/java/examples/spring/TestEntity.java @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples.spring; + +/** + * @since 2016-06-06 + * @author kibertoad + * + */ +public class TestEntity { + + // This field is supposed to be set by the means of calling {@link DataRegistry} and affects ID + // setting + private transient int counter; + + // This field is supposed to be serialized and deserialized into YAML + private String id; + + // This field is supposed to be set by the means of calling {@link DataRegistry} and is affected + // by ID + private transient String data; + + + public String getId() { + return id; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public void setId(String id) { + this.id = counter + ":" + id; + } + + public void setCounter(int counter) { + this.counter = counter; + } + + public int getCounter() { + return counter; + } + +} diff --git a/src/test/java/examples/spring/TestEntityDescription.java b/src/test/java/examples/spring/TestEntityDescription.java new file mode 100644 index 00000000..1e07b8b6 --- /dev/null +++ b/src/test/java/examples/spring/TestEntityDescription.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package examples.spring; + +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.nodes.Node; + +/** + * This description is supposed to work like this: + * + * 1) Counter is retrieved from dataRegistry and is set before deserializing data from YAML; 2) Id + * is deserialized from YAML, using standard SnakeYAML logic for Strings and is impacted by Counter + * that was set before; 3) Data is being retrieved from injected DataRegistry bean using the id; + * + */ +public class TestEntityDescription extends TypeDescription { + + private DataRegistry dataRegistry; + + public TestEntityDescription() { + super(TestEntity.class, TestEntity.class); + } + + @Override + public Object newInstance(Node node) { + TestEntity entity = (TestEntity) super.newInstance(node); + entity.setCounter(dataRegistry.getNextCounterValue()); + return entity; + } + + @Override + public Object finalizeConstruction(Object obj) { + TestEntity entity = (TestEntity) super.finalizeConstruction(obj); + entity.setData(dataRegistry.getDataForId(entity.getId())); + return entity; + } + + public void setDataRegistry(DataRegistry dataRegistry) { + this.dataRegistry = dataRegistry; + } +} diff --git a/src/test/java/examples/staticstate/JavaBeanWithStaticState.java b/src/test/java/examples/staticstate/JavaBeanWithStaticState.java index 0514de0c..be8b6487 100644 --- a/src/test/java/examples/staticstate/JavaBeanWithStaticState.java +++ b/src/test/java/examples/staticstate/JavaBeanWithStaticState.java @@ -1,47 +1,46 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.staticstate; public class JavaBeanWithStaticState { - private String name; - private int age; - public static String color;// public field - private static String type;// private field with a getter - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public static String getType() { - return type; - } - - public static void setType(String type) { - JavaBeanWithStaticState.type = type; - } -}
\ No newline at end of file + + private String name; + private int age; + public static String color;// public field + private static String type;// private field with a getter + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public static String getType() { + return type; + } + + public static void setType(String type) { + JavaBeanWithStaticState.type = type; + } +} diff --git a/src/test/java/examples/staticstate/StaticFieldsTest.java b/src/test/java/examples/staticstate/StaticFieldsTest.java index 60068ce0..e4d5e9f3 100644 --- a/src/test/java/examples/staticstate/StaticFieldsTest.java +++ b/src/test/java/examples/staticstate/StaticFieldsTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.staticstate; import java.util.ArrayList; import java.util.List; import java.util.Set; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; @@ -29,93 +25,101 @@ import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeTuple; import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; /** * Example with static fields */ public class StaticFieldsTest extends TestCase { - public void testAsJavaBean() { - JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); - bean.setName("Bahrack"); - bean.setAge(-47); - JavaBeanWithStaticState.setType("Represent"); - JavaBeanWithStaticState.color = "Black"; - Yaml yaml = new Yaml(); - String output = yaml.dump(bean); - // System.out.println(output); - assertEquals("!!examples.staticstate.JavaBeanWithStaticState {age: -47, name: Bahrack}\n", - output); - // parse back to instance - JavaBeanWithStaticState bean2 = (JavaBeanWithStaticState) yaml.load(output); - assertEquals(-47, bean2.getAge()); - assertEquals("Bahrack", bean2.getName()); - } - public void testCustomDump() { - JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); - bean.setName("Lui"); - bean.setAge(25); - JavaBeanWithStaticState.setType("Represent"); - JavaBeanWithStaticState.color = "Black"; - Yaml yaml = new Yaml(new MyRepresenter(), new DumperOptions()); - String output = yaml.dump(bean); - // System.out.println(output); - assertEquals( - "!!examples.staticstate.JavaBeanWithStaticState {age: 25, name: Lui, color: Black,\n type: Represent}\n", - output); - } + public void testAsJavaBean() { + JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); + bean.setName("Bahrack"); + bean.setAge(-47); + JavaBeanWithStaticState.setType("Represent"); + JavaBeanWithStaticState.color = "Black"; + Yaml yaml = new Yaml(); + String output = yaml.dump(bean); + // System.out.println(output); + assertEquals("!!examples.staticstate.JavaBeanWithStaticState {age: -47, name: Bahrack}\n", + output); + // parse back to instance + JavaBeanWithStaticState bean2 = yaml.load(output); + assertEquals(-47, bean2.getAge()); + assertEquals("Bahrack", bean2.getName()); + } - public void testCustomLoad() { - Yaml yaml = new Yaml(new MyConstructor()); - String output = "!!examples.staticstate.JavaBeanWithStaticState {age: 25, name: Lui, color: Oranje,\n type: King}\n"; - JavaBeanWithStaticState bean2 = (JavaBeanWithStaticState) yaml.load(output); - assertEquals(25, bean2.getAge()); - assertEquals("Lui", bean2.getName()); - assertEquals("Oranje", JavaBeanWithStaticState.color); - assertEquals("King", JavaBeanWithStaticState.getType()); - } + public void testCustomDump() { + JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); + bean.setName("Lui"); + bean.setAge(25); + JavaBeanWithStaticState.setType("Represent"); + JavaBeanWithStaticState.color = "Black"; + Yaml yaml = new Yaml(new MyRepresenter(), new DumperOptions()); + String output = yaml.dump(bean); + // System.out.println(output); + assertEquals( + "!!examples.staticstate.JavaBeanWithStaticState {age: 25, name: Lui, color: Black,\n type: Represent}\n", + output); + } - private class MyRepresenter extends Representer { - @Override - protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { - MappingNode node = super.representJavaBean(properties, javaBean); - if (javaBean instanceof JavaBeanWithStaticState) { - List<NodeTuple> value = node.getValue(); - value.add(new NodeTuple(representData("color"), - representData(JavaBeanWithStaticState.color))); - value.add(new NodeTuple(representData("type"), - representData(JavaBeanWithStaticState.getType()))); - } - return node; - } + public void testCustomLoad() { + Yaml yaml = new Yaml(new MyConstructor()); + String output = + "!!examples.staticstate.JavaBeanWithStaticState {age: 25, name: Lui, color: Oranje,\n type: King}\n"; + JavaBeanWithStaticState bean2 = yaml.load(output); + assertEquals(25, bean2.getAge()); + assertEquals("Lui", bean2.getName()); + assertEquals("Oranje", JavaBeanWithStaticState.color); + assertEquals("King", JavaBeanWithStaticState.getType()); + } + + private class MyRepresenter extends Representer { + + @Override + protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { + MappingNode node = super.representJavaBean(properties, javaBean); + if (javaBean instanceof JavaBeanWithStaticState) { + List<NodeTuple> value = node.getValue(); + value.add( + new NodeTuple(representData("color"), representData(JavaBeanWithStaticState.color))); + value.add( + new NodeTuple(representData("type"), representData(JavaBeanWithStaticState.getType()))); + } + return node; } + } - private class MyConstructor extends Constructor { - protected Object constructObject(Node node) { - if (node.getType().isAssignableFrom(JavaBeanWithStaticState.class)) { - MappingNode beanNode = (MappingNode) node; - List<NodeTuple> value = beanNode.getValue(); - List<NodeTuple> removed = new ArrayList<NodeTuple>(); - for (NodeTuple tuple : value) { - ScalarNode keyNode = (ScalarNode) tuple.getKeyNode(); - if (keyNode.getValue().equals("color")) { - ScalarNode valueNode = (ScalarNode) tuple.getValueNode(); - JavaBeanWithStaticState.color = valueNode.getValue(); - } else if (keyNode.getValue().equals("type")) { - ScalarNode valueNode = (ScalarNode) tuple.getValueNode(); - JavaBeanWithStaticState.setType(valueNode.getValue()); - } else - removed.add(tuple); - } - beanNode.setValue(removed); - JavaBeanWithStaticState bean = (JavaBeanWithStaticState) super - .constructObject(beanNode); + private class MyConstructor extends Constructor { - return bean; - } else { - return super.constructObject(node); - } + private final Tag JBWSS = new Tag(JavaBeanWithStaticState.class); + + protected Object constructObject(Node node) { + if (JavaBeanWithStaticState.class.isAssignableFrom(node.getType()) + || JBWSS.equals(node.getTag())) { + MappingNode beanNode = (MappingNode) node; + List<NodeTuple> value = beanNode.getValue(); + List<NodeTuple> removed = new ArrayList<NodeTuple>(); + for (NodeTuple tuple : value) { + ScalarNode keyNode = (ScalarNode) tuple.getKeyNode(); + if (keyNode.getValue().equals("color")) { + ScalarNode valueNode = (ScalarNode) tuple.getValueNode(); + JavaBeanWithStaticState.color = valueNode.getValue(); + } else if (keyNode.getValue().equals("type")) { + ScalarNode valueNode = (ScalarNode) tuple.getValueNode(); + JavaBeanWithStaticState.setType(valueNode.getValue()); + } else { + removed.add(tuple); + } } + beanNode.setValue(removed); + JavaBeanWithStaticState bean = (JavaBeanWithStaticState) super.constructObject(beanNode); + + return bean; + } else { + return super.constructObject(node); + } } + } } diff --git a/src/test/java/examples/staticstate/StaticFieldsWrapperTest.java b/src/test/java/examples/staticstate/StaticFieldsWrapperTest.java index 7555258c..36a89c57 100644 --- a/src/test/java/examples/staticstate/StaticFieldsWrapperTest.java +++ b/src/test/java/examples/staticstate/StaticFieldsWrapperTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.staticstate; import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; @@ -28,73 +25,73 @@ import org.yaml.snakeyaml.representer.Representer; */ public class StaticFieldsWrapperTest extends TestCase { - /** - * use wrapper with global tag - */ - public void testWrapper() { - JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); - bean.setName("Bahrack"); - bean.setAge(-47); - JavaBeanWithStaticState.setType("Type3"); - JavaBeanWithStaticState.color = "Violet"; - Yaml yaml = new Yaml(); - String output = yaml.dump(new Wrapper(bean)); - // System.out.println(output); - assertEquals( - "!!examples.staticstate.Wrapper {age: -47, color: Violet, name: Bahrack, type: Type3}\n", - output); - // parse back to instance - Wrapper wrapper = (Wrapper) yaml.load(output); - JavaBeanWithStaticState bean2 = wrapper.createBean(); - assertEquals(-47, bean2.getAge()); - assertEquals("Bahrack", bean2.getName()); - } + /** + * use wrapper with global tag + */ + public void testWrapper() { + JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); + bean.setName("Bahrack"); + bean.setAge(-47); + JavaBeanWithStaticState.setType("Type3"); + JavaBeanWithStaticState.color = "Violet"; + Yaml yaml = new Yaml(); + String output = yaml.dump(new Wrapper(bean)); + // System.out.println(output); + assertEquals( + "!!examples.staticstate.Wrapper {age: -47, color: Violet, name: Bahrack, type: Type3}\n", + output); + // parse back to instance + Wrapper wrapper = yaml.load(output); + JavaBeanWithStaticState bean2 = wrapper.createBean(); + assertEquals(-47, bean2.getAge()); + assertEquals("Bahrack", bean2.getName()); + } - /** - * use wrapper with local tag - */ - public void testLocalTag() { - JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); - bean.setName("Bahrack"); - bean.setAge(-47); - JavaBeanWithStaticState.setType("Type3"); - JavaBeanWithStaticState.color = "Violet"; - Representer repr = new Representer(); - repr.addClassTag(Wrapper.class, new Tag("!mybean")); - Yaml yaml = new Yaml(repr); - String output = yaml.dump(new Wrapper(bean)); - // System.out.println(output); - assertEquals("!mybean {age: -47, color: Violet, name: Bahrack, type: Type3}\n", output); - // parse back to instance - Constructor constr = new Constructor(); - TypeDescription description = new TypeDescription(Wrapper.class, new Tag("!mybean")); - constr.addTypeDescription(description); - yaml = new Yaml(constr); - Wrapper wrapper = (Wrapper) yaml.load(output); - JavaBeanWithStaticState bean2 = wrapper.createBean(); - assertEquals(-47, bean2.getAge()); - assertEquals("Bahrack", bean2.getName()); - } + /** + * use wrapper with local tag + */ + public void testLocalTag() { + JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); + bean.setName("Bahrack"); + bean.setAge(-47); + JavaBeanWithStaticState.setType("Type3"); + JavaBeanWithStaticState.color = "Violet"; + Representer repr = new Representer(); + repr.addClassTag(Wrapper.class, new Tag("!mybean")); + Yaml yaml = new Yaml(repr); + String output = yaml.dump(new Wrapper(bean)); + // System.out.println(output); + assertEquals("!mybean {age: -47, color: Violet, name: Bahrack, type: Type3}\n", output); + // parse back to instance + Constructor constr = new Constructor(); + TypeDescription description = new TypeDescription(Wrapper.class, new Tag("!mybean")); + constr.addTypeDescription(description); + yaml = new Yaml(constr); + Wrapper wrapper = yaml.load(output); + JavaBeanWithStaticState bean2 = wrapper.createBean(); + assertEquals(-47, bean2.getAge()); + assertEquals("Bahrack", bean2.getName()); + } - /** - * use wrapper with no tag - */ - public void testRootBean() { - JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); - bean.setName("Bahrack"); - bean.setAge(-47); - JavaBeanWithStaticState.setType("Type3"); - JavaBeanWithStaticState.color = "Violet"; - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(new Wrapper(bean)); - // System.out.println(output); - assertEquals("age: -47\ncolor: Violet\nname: Bahrack\ntype: Type3\n", output); - // parse back to instance - Yaml loader = new Yaml(); - Wrapper wrapper = loader.loadAs(output, Wrapper.class); - JavaBeanWithStaticState bean2 = wrapper.createBean(); - assertEquals(-47, bean2.getAge()); - assertEquals("Bahrack", bean2.getName()); - } + /** + * use wrapper with no tag + */ + public void testRootBean() { + JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); + bean.setName("Bahrack"); + bean.setAge(-47); + JavaBeanWithStaticState.setType("Type3"); + JavaBeanWithStaticState.color = "Violet"; + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(new Wrapper(bean)); + // System.out.println(output); + assertEquals("age: -47\ncolor: Violet\nname: Bahrack\ntype: Type3\n", output); + // parse back to instance + Yaml loader = new Yaml(); + Wrapper wrapper = loader.loadAs(output, Wrapper.class); + JavaBeanWithStaticState bean2 = wrapper.createBean(); + assertEquals(-47, bean2.getAge()); + assertEquals("Bahrack", bean2.getName()); + } } diff --git a/src/test/java/examples/staticstate/Wrapper.java b/src/test/java/examples/staticstate/Wrapper.java index b5c5bbbf..cb33e487 100644 --- a/src/test/java/examples/staticstate/Wrapper.java +++ b/src/test/java/examples/staticstate/Wrapper.java @@ -1,75 +1,74 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package examples.staticstate; public class Wrapper { - private String name; - private int age; - private String color; - private String type; - public JavaBeanWithStaticState createBean() { - JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); - bean.setAge(age); - bean.setName(name); - JavaBeanWithStaticState.color = color; - JavaBeanWithStaticState.setType(type); - return bean; - } + private String name; + private int age; + private String color; + private String type; - public Wrapper() { - color = JavaBeanWithStaticState.color; - type = JavaBeanWithStaticState.getType(); - } + public JavaBeanWithStaticState createBean() { + JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); + bean.setAge(age); + bean.setName(name); + JavaBeanWithStaticState.color = color; + JavaBeanWithStaticState.setType(type); + return bean; + } - public Wrapper(JavaBeanWithStaticState bean) { - this(); - name = bean.getName(); - age = bean.getAge(); - } + public Wrapper() { + color = JavaBeanWithStaticState.color; + type = JavaBeanWithStaticState.getType(); + } - public String getName() { - return name; - } + public Wrapper(JavaBeanWithStaticState bean) { + this(); + name = bean.getName(); + age = bean.getAge(); + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public int getAge() { - return age; - } + public void setName(String name) { + this.name = name; + } - public void setAge(int age) { - this.age = age; - } + public int getAge() { + return age; + } - public String getColor() { - return color; - } + public void setAge(int age) { + this.age = age; + } - public void setColor(String color) { - this.color = color; - } + public String getColor() { + return color; + } - public String getType() { - return type; - } + public void setColor(String color) { + this.color = color; + } - public void setType(String type) { - this.type = type; - } -}
\ No newline at end of file + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/src/test/java/org/pyyaml/AnInstance.java b/src/test/java/org/pyyaml/AnInstance.java index ddff4f1c..2c71b4f3 100644 --- a/src/test/java/org/pyyaml/AnInstance.java +++ b/src/test/java/org/pyyaml/AnInstance.java @@ -1,45 +1,43 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; public class AnInstance { - private Object foo; - private Object bar; - public AnInstance() { - } + private Object foo; + private Object bar; - public AnInstance(Object foo, Object bar) { - this.foo = foo; - this.bar = bar; - } + public AnInstance() {} - public Object getFoo() { - return foo; - } + public AnInstance(Object foo, Object bar) { + this.foo = foo; + this.bar = bar; + } - public void setFoo(Object foo) { - this.foo = foo; - } + public Object getFoo() { + return foo; + } - public Object getBar() { - return bar; - } + public void setFoo(Object foo) { + this.foo = foo; + } - public void setBar(Object bar) { - this.bar = bar; - } -}
\ No newline at end of file + public Object getBar() { + return bar; + } + + public void setBar(Object bar) { + this.bar = bar; + } +} diff --git a/src/test/java/org/pyyaml/CanonicalException.java b/src/test/java/org/pyyaml/CanonicalException.java index 3eedb88e..d4bfd5c0 100644 --- a/src/test/java/org/pyyaml/CanonicalException.java +++ b/src/test/java/org/pyyaml/CanonicalException.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -19,13 +17,13 @@ import org.yaml.snakeyaml.error.YAMLException; public class CanonicalException extends YAMLException { - private static final long serialVersionUID = -6489045150083747626L; + private static final long serialVersionUID = -6489045150083747626L; - public CanonicalException(String message) { - super(message); - } + public CanonicalException(String message) { + super(message); + } - public CanonicalException(Throwable cause) { - super(cause); - } + public CanonicalException(Throwable cause) { + super(cause); + } } diff --git a/src/test/java/org/pyyaml/CanonicalLoader.java b/src/test/java/org/pyyaml/CanonicalLoader.java index e2d0444b..3c7444bf 100644 --- a/src/test/java/org/pyyaml/CanonicalLoader.java +++ b/src/test/java/org/pyyaml/CanonicalLoader.java @@ -1,85 +1,85 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; import java.io.IOException; import java.io.Reader; import java.util.Iterator; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.error.YAMLException; public class CanonicalLoader extends Yaml { - @Override - public Object load(Reader yaml) { - try { - int ch = yaml.read(); - StringBuilder buffer = new StringBuilder(); - while (ch != -1) { - buffer.append((char) ch); - ch = yaml.read(); - } - Composer composer = new Composer(new CanonicalParser(buffer.toString()), resolver); - constructor.setComposer(composer); - return constructor.getSingleData(Object.class); - } catch (IOException e) { - throw new YAMLException(e); - } + + @Override + public Object load(Reader yaml) { + try { + int ch = yaml.read(); + StringBuilder buffer = new StringBuilder(); + while (ch != -1) { + buffer.append((char) ch); + ch = yaml.read(); + } + Composer composer = new Composer( + new CanonicalParser(buffer.toString().replace(System.lineSeparator(), "\n")), resolver); + constructor.setComposer(composer); + return constructor.getSingleData(Object.class); + } catch (IOException e) { + throw new YAMLException(e); } + } - public Iterable<Object> loadAll(Reader yaml) { - try { - int ch = yaml.read(); - StringBuilder buffer = new StringBuilder(); - while (ch != -1) { - buffer.append((char) ch); - ch = yaml.read(); - } - Composer composer = new Composer(new CanonicalParser(buffer.toString()), resolver); - this.constructor.setComposer(composer); - Iterator<Object> result = new Iterator<Object>() { - public boolean hasNext() { - return constructor.checkData(); - } + public Iterable<Object> loadAll(Reader yaml) { + try { + int ch = yaml.read(); + StringBuilder buffer = new StringBuilder(); + while (ch != -1) { + buffer.append((char) ch); + ch = yaml.read(); + } + Composer composer = new Composer(new CanonicalParser(buffer.toString()), resolver); + this.constructor.setComposer(composer); + Iterator<Object> result = new Iterator<Object>() { + public boolean hasNext() { + return constructor.checkData(); + } - public Object next() { - return constructor.getData(); - } + public Object next() { + return constructor.getData(); + } - public void remove() { - throw new UnsupportedOperationException(); - } - }; - return new YamlIterable(result); - } catch (IOException e) { - throw new YAMLException(e); + public void remove() { + throw new UnsupportedOperationException(); } + }; + return new YamlIterable(result); + } catch (IOException e) { + throw new YAMLException(e); } + } - private class YamlIterable implements Iterable<Object> { - private Iterator<Object> iterator; + private class YamlIterable implements Iterable<Object> { - public YamlIterable(Iterator<Object> iterator) { - this.iterator = iterator; - } + private final Iterator<Object> iterator; - public Iterator<Object> iterator() { - return iterator; - } + public YamlIterable(Iterator<Object> iterator) { + this.iterator = iterator; + } + public Iterator<Object> iterator() { + return iterator; } + + } } diff --git a/src/test/java/org/pyyaml/CanonicalParser.java b/src/test/java/org/pyyaml/CanonicalParser.java index eccd9644..a8081e51 100644 --- a/src/test/java/org/pyyaml/CanonicalParser.java +++ b/src/test/java/org/pyyaml/CanonicalParser.java @@ -1,22 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; import java.util.ArrayList; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.Version; import org.yaml.snakeyaml.events.AliasEvent; import org.yaml.snakeyaml.events.DocumentEndEvent; @@ -30,6 +28,7 @@ import org.yaml.snakeyaml.events.SequenceEndEvent; import org.yaml.snakeyaml.events.SequenceStartEvent; import org.yaml.snakeyaml.events.StreamEndEvent; import org.yaml.snakeyaml.events.StreamStartEvent; +import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.parser.Parser; import org.yaml.snakeyaml.tokens.AliasToken; import org.yaml.snakeyaml.tokens.AnchorToken; @@ -38,153 +37,154 @@ import org.yaml.snakeyaml.tokens.TagToken; import org.yaml.snakeyaml.tokens.Token; public class CanonicalParser implements Parser { - private ArrayList<Event> events; - private boolean parsed; - private CanonicalScanner scanner; - public CanonicalParser(String data) { - events = new ArrayList<Event>(); - parsed = false; - scanner = new CanonicalScanner(data); - } + private final ArrayList<Event> events; + private boolean parsed; + private final CanonicalScanner scanner; - // stream: STREAM-START document* STREAM-END - private void parseStream() { - scanner.getToken(Token.ID.StreamStart); - events.add(new StreamStartEvent(null, null)); - while (!scanner.checkToken(Token.ID.StreamEnd)) { - if (scanner.checkToken(Token.ID.Directive, Token.ID.DocumentStart)) { - parseDocument(); - } else { - throw new CanonicalException("document is expected, got " + scanner.tokens.get(0)); - } - } - scanner.getToken(Token.ID.StreamEnd); - events.add(new StreamEndEvent(null, null)); + public CanonicalParser(String data) { + events = new ArrayList<Event>(); + parsed = false; + scanner = new CanonicalScanner(data); + } + + // stream: STREAM-START document* STREAM-END + private void parseStream() { + scanner.getToken(Token.ID.StreamStart); + events.add(new StreamStartEvent(null, null)); + while (!scanner.checkToken(Token.ID.StreamEnd)) { + if (scanner.checkToken(Token.ID.Directive, Token.ID.DocumentStart)) { + parseDocument(); + } else { + throw new CanonicalException("document is expected, got " + scanner.tokens.get(0)); + } } + scanner.getToken(Token.ID.StreamEnd); + events.add(new StreamEndEvent(null, null)); + } - // document: DIRECTIVE? DOCUMENT-START node - private void parseDocument() { - if (scanner.checkToken(Token.ID.Directive)) { - scanner.getToken(Token.ID.Directive); - } - scanner.getToken(Token.ID.DocumentStart); - events.add(new DocumentStartEvent(null, null, true, Version.V1_1, null)); - parseNode(); - events.add(new DocumentEndEvent(null, null, true)); + // document: DIRECTIVE? DOCUMENT-START node + private void parseDocument() { + if (scanner.checkToken(Token.ID.Directive)) { + scanner.getToken(Token.ID.Directive); } + scanner.getToken(Token.ID.DocumentStart); + events.add(new DocumentStartEvent(null, null, true, Version.V1_1, null)); + parseNode(); + events.add(new DocumentEndEvent(null, null, true)); + } - // node: ALIAS | ANCHOR? TAG? (SCALAR|sequence|mapping) - private void parseNode() { - if (scanner.checkToken(Token.ID.Alias)) { - AliasToken token = (AliasToken) scanner.getToken(); - events.add(new AliasEvent(token.getValue(), null, null)); - } else { - String anchor = null; - if (scanner.checkToken(Token.ID.Anchor)) { - AnchorToken token = (AnchorToken) scanner.getToken(); - anchor = token.getValue(); - } - String tag = null; - if (scanner.checkToken(Token.ID.Tag)) { - TagToken token = (TagToken) scanner.getToken(); - tag = token.getValue().getHandle() + token.getValue().getSuffix(); - } - if (scanner.checkToken(Token.ID.Scalar)) { - ScalarToken token = (ScalarToken) scanner.getToken(); - events.add(new ScalarEvent(anchor, tag, new ImplicitTuple(false, false), token - .getValue(), null, null, null)); - } else if (scanner.checkToken(Token.ID.FlowSequenceStart)) { - events.add(new SequenceStartEvent(anchor, tag, false, null, null, null)); - parseSequence(); - } else if (scanner.checkToken(Token.ID.FlowMappingStart)) { - events.add(new MappingStartEvent(anchor, tag, false, null, null, null)); - parseMapping(); - } else { - throw new CanonicalException("SCALAR, '[', or '{' is expected, got " - + scanner.tokens.get(0)); - } - } + // node: ALIAS | ANCHOR? TAG? (SCALAR|sequence|mapping) + private void parseNode() { + if (scanner.checkToken(Token.ID.Alias)) { + AliasToken token = (AliasToken) scanner.getToken(); + events.add(new AliasEvent(token.getValue(), null, null)); + } else { + String anchor = null; + if (scanner.checkToken(Token.ID.Anchor)) { + AnchorToken token = (AnchorToken) scanner.getToken(); + anchor = token.getValue(); + } + String tag = null; + if (scanner.checkToken(Token.ID.Tag)) { + TagToken token = (TagToken) scanner.getToken(); + tag = token.getValue().getHandle() + token.getValue().getSuffix(); + } + if (scanner.checkToken(Token.ID.Scalar)) { + ScalarToken token = (ScalarToken) scanner.getToken(); + events.add(new ScalarEvent(anchor, tag, new ImplicitTuple(false, false), token.getValue(), + null, null, DumperOptions.ScalarStyle.PLAIN)); + } else if (scanner.checkToken(Token.ID.FlowSequenceStart)) { + events.add(new SequenceStartEvent(anchor, Tag.SEQ.getValue(), false, null, null, + DumperOptions.FlowStyle.AUTO)); + parseSequence(); + } else if (scanner.checkToken(Token.ID.FlowMappingStart)) { + events.add(new MappingStartEvent(anchor, Tag.MAP.getValue(), false, null, null, + DumperOptions.FlowStyle.AUTO)); + parseMapping(); + } else { + throw new CanonicalException( + "SCALAR, '[', or '{' is expected, got " + scanner.tokens.get(0)); + } } + } - // sequence: SEQUENCE-START (node (ENTRY node)*)? ENTRY? SEQUENCE-END - private void parseSequence() { - scanner.getToken(Token.ID.FlowSequenceStart); + // sequence: SEQUENCE-START (node (ENTRY node)*)? ENTRY? SEQUENCE-END + private void parseSequence() { + scanner.getToken(Token.ID.FlowSequenceStart); + if (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { + parseNode(); + while (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { + scanner.getToken(Token.ID.FlowEntry); if (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { - parseNode(); - while (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { - scanner.getToken(Token.ID.FlowEntry); - if (!scanner.checkToken(Token.ID.FlowSequenceEnd)) { - parseNode(); - } - } + parseNode(); } - scanner.getToken(Token.ID.FlowSequenceEnd); - events.add(new SequenceEndEvent(null, null)); + } } + scanner.getToken(Token.ID.FlowSequenceEnd); + events.add(new SequenceEndEvent(null, null)); + } - // mapping: MAPPING-START (map_entry (ENTRY map_entry)*)? ENTRY? MAPPING-END - private void parseMapping() { - scanner.getToken(Token.ID.FlowMappingStart); + // mapping: MAPPING-START (map_entry (ENTRY map_entry)*)? ENTRY? MAPPING-END + private void parseMapping() { + scanner.getToken(Token.ID.FlowMappingStart); + if (!scanner.checkToken(Token.ID.FlowMappingEnd)) { + parseMapEntry(); + while (!scanner.checkToken(Token.ID.FlowMappingEnd)) { + scanner.getToken(Token.ID.FlowEntry); if (!scanner.checkToken(Token.ID.FlowMappingEnd)) { - parseMapEntry(); - while (!scanner.checkToken(Token.ID.FlowMappingEnd)) { - scanner.getToken(Token.ID.FlowEntry); - if (!scanner.checkToken(Token.ID.FlowMappingEnd)) { - parseMapEntry(); - } - } + parseMapEntry(); } - scanner.getToken(Token.ID.FlowMappingEnd); - events.add(new MappingEndEvent(null, null)); + } } + scanner.getToken(Token.ID.FlowMappingEnd); + events.add(new MappingEndEvent(null, null)); + } - // map_entry: KEY node VALUE node - private void parseMapEntry() { - scanner.getToken(Token.ID.Key); - parseNode(); - scanner.getToken(Token.ID.Value); - parseNode(); - } + // map_entry: KEY node VALUE node + private void parseMapEntry() { + scanner.getToken(Token.ID.Key); + parseNode(); + scanner.getToken(Token.ID.Value); + parseNode(); + } - public void parse() { - parseStream(); - parsed = true; - } + public void parse() { + parseStream(); + parsed = true; + } - public Event getEvent() { - if (!parsed) { - parse(); - } - return events.remove(0); + public Event getEvent() { + if (!parsed) { + parse(); } + return events.remove(0); + } - /** - * Check the type of the next event. - */ - public boolean checkEvent(Event.ID choice) { - if (!parsed) { - parse(); - } - if (!events.isEmpty()) { - if (events.get(0).is(choice)) { - return true; - } - } - return false; + /** + * Check the type of the next event. + */ + public boolean checkEvent(Event.ID choice) { + if (!parsed) { + parse(); + } + if (!events.isEmpty()) { + return events.get(0).is(choice); } + return false; + } - /** - * Get the next event. - */ - public Event peekEvent() { - if (!parsed) { - parse(); - } - if (events.isEmpty()) { - return null; - } else { - return events.get(0); - } + /** + * Get the next event. + */ + public Event peekEvent() { + if (!parsed) { + parse(); + } + if (events.isEmpty()) { + return null; + } else { + return events.get(0); } + } } diff --git a/src/test/java/org/pyyaml/CanonicalScanner.java b/src/test/java/org/pyyaml/CanonicalScanner.java index 0bb8cc69..8670839f 100644 --- a/src/test/java/org/pyyaml/CanonicalScanner.java +++ b/src/test/java/org/pyyaml/CanonicalScanner.java @@ -1,24 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; import java.util.ArrayList; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.scanner.Scanner; @@ -42,265 +39,263 @@ import org.yaml.snakeyaml.tokens.Token; import org.yaml.snakeyaml.tokens.ValueToken; public class CanonicalScanner implements Scanner { - private static final String DIRECTIVE = "%YAML 1.1"; - private final static Map<Character, Integer> QUOTE_CODES = ScannerImpl.ESCAPE_CODES; - private final static Map<Character, String> QUOTE_REPLACES = ScannerImpl.ESCAPE_REPLACEMENTS; + private static final String DIRECTIVE = "%YAML 1.1"; + private final static Map<Character, Integer> QUOTE_CODES = ScannerImpl.ESCAPE_CODES; - private String data; - private int index; - public ArrayList<Token> tokens; - private boolean scanned; - private Mark mark; + private final static Map<Character, String> QUOTE_REPLACES = ScannerImpl.ESCAPE_REPLACEMENTS; - public CanonicalScanner(String data) { - this.data = data + "\0"; - this.index = 0; - this.tokens = new ArrayList<Token>(); - this.scanned = false; - this.mark = new Mark("test", 0, 0, 0, data, 0); - } + private final String data; + private int index; + public ArrayList<Token> tokens; + private boolean scanned; + private final Mark mark; - public boolean checkToken(Token.ID... choices) { - if (!scanned) { - scan(); - } - if (!tokens.isEmpty()) { - if (choices.length == 0) { - return true; - } - Token first = this.tokens.get(0); - for (Token.ID choice : choices) { - if (first.getTokenId() == choice) { - return true; - } - } + public CanonicalScanner(String data) { + this.data = data + "\0"; + this.index = 0; + this.tokens = new ArrayList<Token>(); + this.scanned = false; + this.mark = new Mark("test", 0, 0, 0, data.toCharArray(), 0); + } + + public boolean checkToken(Token.ID... choices) { + if (!scanned) { + scan(); + } + if (!tokens.isEmpty()) { + if (choices.length == 0) { + return true; + } + Token first = this.tokens.get(0); + for (Token.ID choice : choices) { + if (first.getTokenId() == choice) { + return true; } - return false; + } } + return false; + } - public Token peekToken() { - if (!scanned) { - scan(); - } - if (!tokens.isEmpty()) { - return this.tokens.get(0); - } - return null; + public Token peekToken() { + if (!scanned) { + scan(); } + if (!tokens.isEmpty()) { + return this.tokens.get(0); + } + return null; + } - public Token getToken() { - if (!scanned) { - scan(); - } - return this.tokens.remove(0); + public Token getToken() { + if (!scanned) { + scan(); } + return this.tokens.remove(0); + } - public Token getToken(Token.ID choice) { - Token token = getToken(); - if (choice != null && token.getTokenId() != choice) { - throw new CanonicalException("unexpected token " + token); - } - return token; + public Token getToken(Token.ID choice) { + Token token = getToken(); + if (choice != null && token.getTokenId() != choice) { + throw new CanonicalException("unexpected token " + token); } + return token; + } - private void scan() { - this.tokens.add(new StreamStartToken(mark, mark)); - boolean stop = false; - while (!stop) { - findToken(); - char ch = data.charAt(index); - switch (ch) { - case '\0': - tokens.add(new StreamEndToken(mark, mark)); - stop = true; - break; + private void scan() { + this.tokens.add(new StreamStartToken(mark, mark)); + boolean stop = false; + while (!stop) { + findToken(); + int c = data.codePointAt(index); + switch (c) { + case '\0': + tokens.add(new StreamEndToken(mark, mark)); + stop = true; + break; - case '%': - tokens.add(scanDirective()); - break; + case '%': + tokens.add(scanDirective()); + break; - case '-': - if ("---".equals(data.substring(index, index + 3))) { - index += 3; - tokens.add(new DocumentStartToken(mark, mark)); - } - break; + case '-': + if ("---".equals(data.substring(index, index + 3))) { + index += 3; + tokens.add(new DocumentStartToken(mark, mark)); + } + break; - case '[': - index++; - tokens.add(new FlowSequenceStartToken(mark, mark)); - break; + case '[': + index++; + tokens.add(new FlowSequenceStartToken(mark, mark)); + break; - case '{': - index++; - tokens.add(new FlowMappingStartToken(mark, mark)); - break; + case '{': + index++; + tokens.add(new FlowMappingStartToken(mark, mark)); + break; - case ']': - index++; - tokens.add(new FlowSequenceEndToken(mark, mark)); - break; + case ']': + index++; + tokens.add(new FlowSequenceEndToken(mark, mark)); + break; - case '}': - index++; - tokens.add(new FlowMappingEndToken(mark, mark)); - break; + case '}': + index++; + tokens.add(new FlowMappingEndToken(mark, mark)); + break; - case '?': - index++; - tokens.add(new KeyToken(mark, mark)); - break; + case '?': + index++; + tokens.add(new KeyToken(mark, mark)); + break; - case ':': - index++; - tokens.add(new ValueToken(mark, mark)); - break; + case ':': + index++; + tokens.add(new ValueToken(mark, mark)); + break; - case ',': - index++; - tokens.add(new FlowEntryToken(mark, mark)); - break; + case ',': + index++; + tokens.add(new FlowEntryToken(mark, mark)); + break; - case '*': - tokens.add(scanAlias()); - break; + case '*': + tokens.add(scanAlias()); + break; - case '&': - tokens.add(scanAlias()); - break; + case '&': + tokens.add(scanAlias()); + break; - case '!': - tokens.add(scanTag()); - break; + case '!': + tokens.add(scanTag()); + break; - case '"': - tokens.add(scanScalar()); - break; + case '"': + tokens.add(scanScalar()); + break; - default: - throw new CanonicalException("invalid token"); - } - } - scanned = true; + default: + throw new CanonicalException("invalid token"); + } } + scanned = true; + } - private Token scanDirective() { - String chunk1 = data.substring(index, index + DIRECTIVE.length()); - char chunk2 = data.charAt(index + DIRECTIVE.length()); - if (DIRECTIVE.equals(chunk1) && "\n\0".indexOf(chunk2) != -1) { - index += DIRECTIVE.length(); - List<Integer> implicit = new ArrayList<Integer>(2); - implicit.add(new Integer(1)); - implicit.add(new Integer(1)); - return new DirectiveToken<Integer>("YAML", implicit, mark, mark); - } else { - throw new CanonicalException("invalid directive"); - } + private Token scanDirective() { + String chunk1 = data.substring(index, index + DIRECTIVE.length()); + char chunk2 = data.charAt(index + DIRECTIVE.length()); + if (DIRECTIVE.equals(chunk1) && "\n\0".indexOf(chunk2) != -1) { + index += DIRECTIVE.length(); + List<Integer> implicit = new ArrayList<Integer>(2); + implicit.add(1); + implicit.add(1); + return new DirectiveToken<Integer>("YAML", implicit, mark, mark); + } else { + throw new CanonicalException("invalid directive"); } + } - private Token scanAlias() { - boolean isTokenClassAlias; - if (data.charAt(index) == '*') { - isTokenClassAlias = true; - } else { - isTokenClassAlias = false; - } - index++; - int start = index; - while (", \n\0".indexOf(data.charAt(index)) == -1) { - index++; - } - String value = data.substring(start, index); - Token token; - if (isTokenClassAlias) { - token = new AliasToken(value, mark, mark); - } else { - token = new AnchorToken(value, mark, mark); - } - return token; + private Token scanAlias() { + boolean isTokenClassAlias; + final int c = data.codePointAt(index); + isTokenClassAlias = c == '*'; + index += Character.charCount(c); + int start = index; + while (", \n\0".indexOf(data.charAt(index)) == -1) { + index++; + } + String value = data.substring(start, index); + Token token; + if (isTokenClassAlias) { + token = new AliasToken(value, mark, mark); + } else { + token = new AnchorToken(value, mark, mark); } + return token; + } - private Token scanTag() { - index++; - int start = index; - while (" \n\0".indexOf(data.charAt(index)) == -1) { - index++; - } - String value = data.substring(start, index); - if (value.length() == 0) { - value = "!"; - } else if (value.charAt(0) == '!') { - value = Tag.PREFIX + value.substring(1); - } else if (value.charAt(0) == '<' && value.charAt(value.length() - 1) == '>') { - value = value.substring(1, value.length() - 1); + private Token scanTag() { + index += Character.charCount(data.codePointAt(index)); + int start = index; + while (" \n\0".indexOf(data.charAt(index)) == -1) { + index++; + } + String value = data.substring(start, index); + if (value.length() == 0) { + value = "!"; + } else if (value.charAt(0) == '!') { + value = Tag.PREFIX + value.substring(1); + } else if (value.charAt(0) == '<' && value.charAt(value.length() - 1) == '>') { + value = value.substring(1, value.length() - 1); + } else { + value = "!" + value; + } + return new TagToken(new TagTuple("", value), mark, mark); + } + + private Token scanScalar() { + index += Character.charCount(data.codePointAt(index)); + StringBuilder chunks = new StringBuilder(); + int start = index; + boolean ignoreSpaces = false; + while (data.charAt(index) != '"') { + if (data.charAt(index) == '\\') { + ignoreSpaces = false; + chunks.append(data, start, index); + index += Character.charCount(data.codePointAt(index)); + int c = data.codePointAt(index); + index += Character.charCount(data.codePointAt(index)); + if (c == '\n') { + ignoreSpaces = true; + } else if (!Character.isSupplementaryCodePoint(c) && QUOTE_CODES.containsKey((char) c)) { + int length = QUOTE_CODES.get((char) c); + int code = Integer.parseInt(data.substring(index, index + length), 16); + chunks.append((char) code); + index += length; } else { - value = "!" + value; + if (Character.isSupplementaryCodePoint(c) || !QUOTE_REPLACES.containsKey((char) c)) { + throw new CanonicalException("invalid escape code"); + } + chunks.append(QUOTE_REPLACES.get((char) c)); } - return new TagToken(new TagTuple("", value), mark, mark); + start = index; + } else if (data.charAt(index) == '\n') { + chunks.append(data, start, index); + chunks.append(" "); + index += Character.charCount(data.codePointAt(index)); + start = index; + ignoreSpaces = true; + } else if (ignoreSpaces && data.charAt(index) == ' ') { + index += Character.charCount(data.codePointAt(index)); + start = index; + } else { + ignoreSpaces = false; + index += Character.charCount(data.codePointAt(index)); + } } + chunks.append(data, start, index); + index += Character.charCount(data.codePointAt(index)); + return new ScalarToken(chunks.toString(), mark, mark, false); + } - private Token scanScalar() { + private void findToken() { + boolean found = false; + while (!found) { + while (" \t".indexOf(data.charAt(index)) != -1) { index++; - StringBuilder chunks = new StringBuilder(); - int start = index; - boolean ignoreSpaces = false; - while (data.charAt(index) != '"') { - if (data.charAt(index) == '\\') { - ignoreSpaces = false; - chunks.append(data.substring(start, index)); - index++; - char ch = data.charAt(index); - index++; - if (ch == '\n') { - ignoreSpaces = true; - } else if (QUOTE_CODES.keySet().contains(ch)) { - int length = QUOTE_CODES.get(ch); - int code = Integer.parseInt(data.substring(index, index + length), 16); - chunks.append(String.valueOf((char) code)); - index += length; - } else { - if (!QUOTE_REPLACES.keySet().contains(ch)) { - throw new CanonicalException("invalid escape code"); - } - chunks.append(QUOTE_REPLACES.get(ch)); - } - start = index; - } else if (data.charAt(index) == '\n') { - chunks.append(data.substring(start, index)); - chunks.append(" "); - index++; - start = index; - ignoreSpaces = true; - } else if (ignoreSpaces && data.charAt(index) == ' ') { - index++; - start = index; - } else { - ignoreSpaces = false; - index++; - } + } + if (data.charAt(index) == '#') { + while (data.charAt(index) != '\n') { + index++; } - chunks.append(data.substring(start, index)); + } + if (data.charAt(index) == '\n') { index++; - return new ScalarToken(chunks.toString(), mark, mark, false); - } - - private void findToken() { - boolean found = false; - while (!found) { - while (" \t".indexOf(data.charAt(index)) != -1) { - index++; - } - if (data.charAt(index) == '#') { - while (data.charAt(index) != '\n') { - index++; - } - } - if (data.charAt(index) == '\n') { - index++; - } else { - found = true; - } - } + } else { + found = true; + } } + } } diff --git a/src/test/java/org/pyyaml/PyCanonicalTest.java b/src/test/java/org/pyyaml/PyCanonicalTest.java index fc6a9e32..5dad9264 100644 --- a/src/test/java/org/pyyaml/PyCanonicalTest.java +++ b/src/test/java/org/pyyaml/PyCanonicalTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -21,7 +19,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; - import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.tokens.Token; @@ -30,40 +27,41 @@ import org.yaml.snakeyaml.tokens.Token; */ public class PyCanonicalTest extends PyImportTest { - public void testCanonicalScanner() throws IOException { - File[] files = getStreamsByExtension(".canonical"); - assertTrue("No test files found.", files.length > 0); - for (int i = 0; i < files.length; i++) { - InputStream input = new FileInputStream(files[i]); - List<Token> tokens = canonicalScan(input); - input.close(); - assertFalse(tokens.isEmpty()); - } + public void testCanonicalScanner() throws IOException { + File[] files = getStreamsByExtension(".canonical"); + assertTrue("No test files found.", files.length > 0); + for (int i = 0; i < files.length; i++) { + InputStream input = new FileInputStream(files[i]); + List<Token> tokens = canonicalScan(input); + input.close(); + assertFalse(tokens.isEmpty()); } + } - private List<Token> canonicalScan(InputStream input) throws IOException { - int ch = input.read(); - StringBuilder buffer = new StringBuilder(); - while (ch != -1) { - buffer.append((char) ch); - ch = input.read(); - } - CanonicalScanner scanner = new CanonicalScanner(buffer.toString()); - List<Token> result = new ArrayList<Token>(); - while (scanner.peekToken() != null) { - result.add(scanner.getToken()); - } - return result; + private List<Token> canonicalScan(InputStream input) throws IOException { + int ch = input.read(); + StringBuilder buffer = new StringBuilder(); + while (ch != -1) { + buffer.append((char) ch); + ch = input.read(); + } + CanonicalScanner scanner = + new CanonicalScanner(buffer.toString().replace(System.lineSeparator(), "\n")); + List<Token> result = new ArrayList<Token>(); + while (scanner.peekToken() != null) { + result.add(scanner.getToken()); } + return result; + } - public void testCanonicalParser() throws IOException { - File[] files = getStreamsByExtension(".canonical"); - assertTrue("No test files found.", files.length > 0); - for (int i = 0; i < files.length; i++) { - InputStream input = new FileInputStream(files[i]); - List<Event> tokens = canonicalParse(input); - input.close(); - assertFalse(tokens.isEmpty()); - } + public void testCanonicalParser() throws IOException { + File[] files = getStreamsByExtension(".canonical"); + assertTrue("No test files found.", files.length > 0); + for (int i = 0; i < files.length; i++) { + InputStream input = new FileInputStream(files[i]); + List<Event> tokens = canonicalParse(input); + input.close(); + assertFalse(tokens.isEmpty()); } + } } diff --git a/src/test/java/org/pyyaml/PyEmitterTest.java b/src/test/java/org/pyyaml/PyEmitterTest.java index 8ca80d31..41fe09ba 100644 --- a/src/test/java/org/pyyaml/PyEmitterTest.java +++ b/src/test/java/org/pyyaml/PyEmitterTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -24,7 +22,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.emitter.Emitter; import org.yaml.snakeyaml.emitter.EventConstructor; @@ -43,250 +40,246 @@ import org.yaml.snakeyaml.reader.UnicodeReader; * imported from PyYAML */ public class PyEmitterTest extends PyImportTest { - public void testEmitterOnData() { - _testEmitter(".data", false); - } - public void testEmitterOnCanonicalNormally() { - _testEmitter(".canonical", false); - } + public void testEmitterOnData() { + _testEmitter(".data", false); + } - public void testEmitterOnCanonicalCanonically() { - _testEmitter(".canonical", true); - } + public void testEmitterOnCanonicalNormally() { + _testEmitter(".canonical", false); + } - private void _testEmitter(String mask, boolean canonical) { - File[] files = getStreamsByExtension(mask, true); - assertTrue("No test files found.", files.length > 0); - for (File file : files) { - // if (!file.getName().contains("spec-06-01.canonical")) { - // continue; - // } - try { - InputStream input = new FileInputStream(file); - List<Event> events = parse(input); - input.close(); - // - StringWriter stream = new StringWriter(); - DumperOptions options = new DumperOptions(); - options.setCanonical(canonical); - Emitter emitter = new Emitter(stream, options); - for (Event event : events) { - emitter.emit(event); - } - // - String data = stream.toString(); - List<Event> newEvents = new ArrayList<Event>(); - StreamReader reader = new StreamReader(data); - Parser parser = new ParserImpl(reader); - while (parser.peekEvent() != null) { - Event event = parser.getEvent(); - newEvents.add(event); - } - // check - assertEquals(events.size(), newEvents.size()); - Iterator<Event> iter1 = events.iterator(); - Iterator<Event> iter2 = newEvents.iterator(); - while (iter1.hasNext()) { - Event event = iter1.next(); - Event newEvent = iter2.next(); - assertEquals(event.getClass().getName(), newEvent.getClass().getName()); - if (event instanceof NodeEvent) { - NodeEvent e1 = (NodeEvent) event; - NodeEvent e2 = (NodeEvent) newEvent; - assertEquals(e1.getAnchor(), e2.getAnchor()); - } - if (event instanceof CollectionStartEvent) { - CollectionStartEvent e1 = (CollectionStartEvent) event; - CollectionStartEvent e2 = (CollectionStartEvent) newEvent; - assertEquals(e1.getTag(), e2.getTag()); - } - if (event instanceof ScalarEvent) { - ScalarEvent e1 = (ScalarEvent) event; - ScalarEvent e2 = (ScalarEvent) newEvent; - if (e1.getImplicit().bothFalse() && e2.getImplicit().bothFalse()) { - assertEquals(e1.getTag(), e2.getTag()); - } - assertEquals(e1.getValue(), e2.getValue()); - } - } - } catch (Exception e) { - System.out.println("Failed File: " + file); - // fail("Failed File: " + file + "; " + e.getMessage()); - throw new RuntimeException(e); + public void testEmitterOnCanonicalCanonically() { + _testEmitter(".canonical", true); + } + + private void _testEmitter(String mask, boolean canonical) { + File[] files = getStreamsByExtension(mask, true); + assertTrue("No test files found.", files.length > 0); + for (File file : files) { + // if (!file.getName().contains("spec-06-01.canonical")) { + // continue; + // } + try { + InputStream input = new FileInputStream(file); + List<Event> events = parse(input); + input.close(); + // + StringWriter stream = new StringWriter(); + DumperOptions options = new DumperOptions(); + options.setCanonical(canonical); + Emitter emitter = new Emitter(stream, options); + for (Event event : events) { + emitter.emit(event); + } + // + String data = stream.toString(); + List<Event> newEvents = new ArrayList<Event>(); + StreamReader reader = new StreamReader(data); + Parser parser = new ParserImpl(reader); + while (parser.peekEvent() != null) { + Event event = parser.getEvent(); + newEvents.add(event); + } + // check + assertEquals(events.size(), newEvents.size()); + Iterator<Event> iter1 = events.iterator(); + Iterator<Event> iter2 = newEvents.iterator(); + while (iter1.hasNext()) { + Event event = iter1.next(); + Event newEvent = iter2.next(); + assertEquals(event.getClass().getName(), newEvent.getClass().getName()); + if (event instanceof NodeEvent) { + NodeEvent e1 = (NodeEvent) event; + NodeEvent e2 = (NodeEvent) newEvent; + assertEquals(e1.getAnchor(), e2.getAnchor()); + } + if (event instanceof CollectionStartEvent) { + CollectionStartEvent e1 = (CollectionStartEvent) event; + CollectionStartEvent e2 = (CollectionStartEvent) newEvent; + assertEquals(e1.getTag(), e2.getTag()); + } + if (event instanceof ScalarEvent) { + ScalarEvent e1 = (ScalarEvent) event; + ScalarEvent e2 = (ScalarEvent) newEvent; + if (e1.getImplicit().bothFalse() && e2.getImplicit().bothFalse()) { + assertEquals(e1.getTag(), e2.getTag()); } + assertEquals(e1.getValue(), e2.getValue()); + } } + } catch (Exception e) { + System.out.println("Failed File: " + file); + // fail("Failed File: " + file + "; " + e.getMessage()); + throw new RuntimeException(e); + } } + } - public void testEmitterStyles() { - File[] canonicalFiles = getStreamsByExtension(".canonical", false); - assertTrue("No test files found.", canonicalFiles.length > 0); - File[] dataFiles = getStreamsByExtension(".data", true); - assertTrue("No test files found.", dataFiles.length > 0); - List<File> allFiles = new ArrayList<File>(Arrays.asList(canonicalFiles)); - allFiles.addAll(Arrays.asList(dataFiles)); - for (File file : allFiles) { - try { - List<Event> events = new ArrayList<Event>(); - InputStream input = new FileInputStream(file); - StreamReader reader = new StreamReader(new UnicodeReader(input)); - Parser parser = new ParserImpl(reader); - while (parser.peekEvent() != null) { - Event event = parser.getEvent(); - events.add(event); - } - input.close(); - // - for (Boolean flowStyle : new Boolean[] { Boolean.FALSE, Boolean.TRUE }) { - for (DumperOptions.ScalarStyle style : DumperOptions.ScalarStyle.values()) { - List<Event> styledEvents = new ArrayList<Event>(); - for (Event event : events) { - if (event instanceof ScalarEvent) { - ScalarEvent scalar = (ScalarEvent) event; - event = new ScalarEvent(scalar.getAnchor(), scalar.getTag(), - scalar.getImplicit(), scalar.getValue(), - scalar.getStartMark(), scalar.getEndMark(), style.getChar()); - } else if (event instanceof SequenceStartEvent) { - SequenceStartEvent seqStart = (SequenceStartEvent) event; - event = new SequenceStartEvent(seqStart.getAnchor(), - seqStart.getTag(), seqStart.getImplicit(), - seqStart.getStartMark(), seqStart.getEndMark(), flowStyle); - } else if (event instanceof MappingStartEvent) { - MappingStartEvent mapStart = (MappingStartEvent) event; - event = new MappingStartEvent(mapStart.getAnchor(), - mapStart.getTag(), mapStart.getImplicit(), - mapStart.getStartMark(), mapStart.getEndMark(), flowStyle); - } - styledEvents.add(event); - } - // emit - String data = emit(styledEvents); - List<Event> newEvents = parse(data); - assertEquals("Events must not change. File: " + file, events.size(), - newEvents.size()); - Iterator<Event> oldIter = events.iterator(); - Iterator<Event> newIter = newEvents.iterator(); - while (oldIter.hasNext()) { - Event event = oldIter.next(); - Event newEvent = newIter.next(); - assertEquals(event.getClass(), newEvent.getClass()); - if (event instanceof NodeEvent) { - assertEquals(((NodeEvent) event).getAnchor(), - ((NodeEvent) newEvent).getAnchor()); - } - if (event instanceof CollectionStartEvent) { - assertEquals(((CollectionStartEvent) event).getTag(), - ((CollectionStartEvent) newEvent).getTag()); - } - if (event instanceof ScalarEvent) { - ScalarEvent scalarOld = (ScalarEvent) event; - ScalarEvent scalarNew = (ScalarEvent) newEvent; - if (scalarOld.getImplicit().bothFalse() - && scalarNew.getImplicit().bothFalse()) { - assertEquals(scalarOld.getTag(), scalarNew.getTag()); - } - assertEquals(scalarOld.getValue(), scalarNew.getValue()); - } - } - } + public void testEmitterStyles() { + File[] canonicalFiles = getStreamsByExtension(".canonical", false); + assertTrue("No test files found.", canonicalFiles.length > 0); + File[] dataFiles = getStreamsByExtension(".data", true); + assertTrue("No test files found.", dataFiles.length > 0); + List<File> allFiles = new ArrayList<File>(Arrays.asList(canonicalFiles)); + allFiles.addAll(Arrays.asList(dataFiles)); + for (File file : allFiles) { + try { + List<Event> events = new ArrayList<Event>(); + InputStream input = new FileInputStream(file); + StreamReader reader = new StreamReader(new UnicodeReader(input)); + Parser parser = new ParserImpl(reader); + while (parser.peekEvent() != null) { + Event event = parser.getEvent(); + events.add(event); + } + input.close(); + // + for (DumperOptions.FlowStyle flowStyle : DumperOptions.FlowStyle.values()) { + for (DumperOptions.ScalarStyle style : DumperOptions.ScalarStyle.values()) { + List<Event> styledEvents = new ArrayList<Event>(); + for (Event event : events) { + if (event instanceof ScalarEvent) { + ScalarEvent scalar = (ScalarEvent) event; + event = new ScalarEvent(scalar.getAnchor(), scalar.getTag(), scalar.getImplicit(), + scalar.getValue(), scalar.getStartMark(), scalar.getEndMark(), style); + } else if (event instanceof SequenceStartEvent) { + SequenceStartEvent seqStart = (SequenceStartEvent) event; + event = new SequenceStartEvent(seqStart.getAnchor(), seqStart.getTag(), + seqStart.getImplicit(), seqStart.getStartMark(), seqStart.getEndMark(), + flowStyle); + } else if (event instanceof MappingStartEvent) { + MappingStartEvent mapStart = (MappingStartEvent) event; + event = new MappingStartEvent(mapStart.getAnchor(), mapStart.getTag(), + mapStart.getImplicit(), mapStart.getStartMark(), mapStart.getEndMark(), + flowStyle); + } + styledEvents.add(event); + } + // emit + String data = emit(styledEvents); + List<Event> newEvents = parse(data); + assertEquals("Events must not change. File: " + file, events.size(), newEvents.size()); + Iterator<Event> oldIter = events.iterator(); + Iterator<Event> newIter = newEvents.iterator(); + while (oldIter.hasNext()) { + Event event = oldIter.next(); + Event newEvent = newIter.next(); + assertEquals(event.getClass(), newEvent.getClass()); + if (event instanceof NodeEvent) { + assertEquals(((NodeEvent) event).getAnchor(), ((NodeEvent) newEvent).getAnchor()); + } + if (event instanceof CollectionStartEvent) { + assertEquals(((CollectionStartEvent) event).getTag(), + ((CollectionStartEvent) newEvent).getTag()); + } + if (event instanceof ScalarEvent) { + ScalarEvent scalarOld = (ScalarEvent) event; + ScalarEvent scalarNew = (ScalarEvent) newEvent; + if (scalarOld.getImplicit().bothFalse() && scalarNew.getImplicit().bothFalse()) { + assertEquals(scalarOld.getTag(), scalarNew.getTag()); } - - } catch (Exception e) { - System.out.println("Failed File: " + file); - // fail("Failed File: " + file + "; " + e.getMessage()); - throw new RuntimeException(e); + assertEquals(scalarOld.getValue(), scalarNew.getValue()); + } } + } } + + } catch (Exception e) { + System.out.println("Failed File: " + file); + // fail("Failed File: " + file + "; " + e.getMessage()); + throw new RuntimeException(e); + } } + } - private String emit(List<Event> events) throws IOException { - StringWriter writer = new StringWriter(); - Emitter emitter = new Emitter(writer, new DumperOptions()); - for (Event event : events) { - emitter.emit(event); - } - return writer.toString(); + private String emit(List<Event> events) throws IOException { + StringWriter writer = new StringWriter(); + Emitter emitter = new Emitter(writer, new DumperOptions()); + for (Event event : events) { + emitter.emit(event); + } + return writer.toString(); + } + + private List<Event> parse(String data) { + ParserImpl parser = new ParserImpl(new StreamReader(data)); + List<Event> newEvents = new ArrayList<Event>(); + while (parser.peekEvent() != null) { + newEvents.add(parser.getEvent()); } + return newEvents; + } - private List<Event> parse(String data) { - ParserImpl parser = new ParserImpl(new StreamReader(data)); + @SuppressWarnings("unchecked") + public void testEmitterEvents() { + File[] files = getStreamsByExtension(".events", false); + assertTrue("No test files found.", files.length > 0); + for (File file : files) { + // if (!file.getName().contains("spec-06-01.canonical")) { + // continue; + // } + try { + List<Event> events = new ArrayList<Event>(); + String content = getResource(file.getName()); + events = (List<Event>) load(new EventConstructor(), content); + // + StringWriter stream = new StringWriter(); + Emitter emitter = new Emitter(stream, new DumperOptions()); + for (Event event : events) { + emitter.emit(event); + } + // + String data = stream.toString(); List<Event> newEvents = new ArrayList<Event>(); + StreamReader reader = new StreamReader(data); + Parser parser = new ParserImpl(reader); while (parser.peekEvent() != null) { - newEvents.add(parser.getEvent()); + Event event = parser.getEvent(); + newEvents.add(event); } - return newEvents; - } + // check + assertEquals(events.size(), newEvents.size()); + Iterator<Event> iter1 = events.iterator(); + Iterator<Event> iter2 = newEvents.iterator(); + while (iter1.hasNext()) { + Event event = iter1.next(); + Event newEvent = iter2.next(); + assertEquals(event.getClass().getName(), newEvent.getClass().getName()); + if (event instanceof NodeEvent) { + NodeEvent e1 = (NodeEvent) event; + NodeEvent e2 = (NodeEvent) newEvent; + assertEquals(e1.getAnchor(), e2.getAnchor()); + } + if (event instanceof CollectionStartEvent) { + CollectionStartEvent e1 = (CollectionStartEvent) event; + CollectionStartEvent e2 = (CollectionStartEvent) newEvent; + assertEquals(e1.getTag(), e2.getTag()); + } + if (event instanceof ScalarEvent) { + ScalarEvent e1 = (ScalarEvent) event; + ScalarEvent e2 = (ScalarEvent) newEvent; + if (e1.getImplicit().canOmitTagInPlainScalar() == e2.getImplicit() + .canOmitTagInPlainScalar() + && e1.getImplicit().canOmitTagInNonPlainScalar() == e2.getImplicit() + .canOmitTagInNonPlainScalar()) { - @SuppressWarnings("unchecked") - public void testEmitterEvents() { - File[] files = getStreamsByExtension(".events", false); - assertTrue("No test files found.", files.length > 0); - for (File file : files) { - // if (!file.getName().contains("spec-06-01.canonical")) { - // continue; - // } - try { - List<Event> events = new ArrayList<Event>(); - String content = getResource(file.getName()); - events = (List<Event>) load(new EventConstructor(), content); - // - StringWriter stream = new StringWriter(); - Emitter emitter = new Emitter(stream, new DumperOptions()); - for (Event event : events) { - emitter.emit(event); - } - // - String data = stream.toString(); - List<Event> newEvents = new ArrayList<Event>(); - StreamReader reader = new StreamReader(data); - Parser parser = new ParserImpl(reader); - while (parser.peekEvent() != null) { - Event event = parser.getEvent(); - newEvents.add(event); - } - // check - assertEquals(events.size(), newEvents.size()); - Iterator<Event> iter1 = events.iterator(); - Iterator<Event> iter2 = newEvents.iterator(); - while (iter1.hasNext()) { - Event event = iter1.next(); - Event newEvent = iter2.next(); - assertEquals(event.getClass().getName(), newEvent.getClass().getName()); - if (event instanceof NodeEvent) { - NodeEvent e1 = (NodeEvent) event; - NodeEvent e2 = (NodeEvent) newEvent; - assertEquals(e1.getAnchor(), e2.getAnchor()); - } - if (event instanceof CollectionStartEvent) { - CollectionStartEvent e1 = (CollectionStartEvent) event; - CollectionStartEvent e2 = (CollectionStartEvent) newEvent; - assertEquals(e1.getTag(), e2.getTag()); - } - if (event instanceof ScalarEvent) { - ScalarEvent e1 = (ScalarEvent) event; - ScalarEvent e2 = (ScalarEvent) newEvent; - if (e1.getImplicit().canOmitTagInPlainScalar() == e2.getImplicit() - .canOmitTagInPlainScalar() - && e1.getImplicit().canOmitTagInNonPlainScalar() == e2 - .getImplicit().canOmitTagInNonPlainScalar()) { - - } else { - if ((e1.getTag() == null || e2.getTag() == null) - || e1.getTag().equals(e2.getTag())) { - } else { - System.out.println("tag1: " + e1.getTag()); - System.out.println("tag2: " + e2.getTag()); - fail("in file: " + file); - } - } - assertEquals(e1.getValue(), e2.getValue()); - } - } - } catch (Exception e) { - System.out.println("Failed File: " + file); - // fail("Failed File: " + file + "; " + e.getMessage()); - throw new RuntimeException(e); + } else { + if ((e1.getTag() == null || e2.getTag() == null) || e1.getTag().equals(e2.getTag())) { + } else { + System.out.println("tag1: " + e1.getTag()); + System.out.println("tag2: " + e2.getTag()); + fail("in file: " + file); + } } + assertEquals(e1.getValue(), e2.getValue()); + } } + } catch (Exception e) { + System.out.println("Failed File: " + file); + // fail("Failed File: " + file + "; " + e.getMessage()); + throw new RuntimeException(e); + } } + } } diff --git a/src/test/java/org/pyyaml/PyErrorsTest.java b/src/test/java/org/pyyaml/PyErrorsTest.java index 14955847..e34f0187 100644 --- a/src/test/java/org/pyyaml/PyErrorsTest.java +++ b/src/test/java/org/pyyaml/PyErrorsTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -23,7 +21,6 @@ import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.emitter.Emitter; import org.yaml.snakeyaml.emitter.EventConstructor; @@ -34,98 +31,99 @@ import org.yaml.snakeyaml.events.Event; * imported from PyYAML */ public class PyErrorsTest extends PyImportTest { - private boolean skip(String filename) { - List<String> failures = new ArrayList<String>(); - // in python list cannot be a key in a dictionary. - failures.add("unacceptable-key.loader-error"); - for (String name : failures) { - if (name.equals(filename)) { - return true; - } - } - return false; + + private boolean skip(String filename) { + List<String> failures = new ArrayList<String>(); + // in python list cannot be a key in a dictionary. + failures.add("unacceptable-key.loader-error"); + for (String name : failures) { + if (name.equals(filename)) { + return true; + } } + return false; + } - public void testLoaderErrors() throws FileNotFoundException { - File[] files = getStreamsByExtension(".loader-error"); - assertTrue("No test files found.", files.length > 0); - for (int i = 0; i < files.length; i++) { - if (skip(files[i].getName())) { - continue; - } - try { - InputStream input = new FileInputStream(files[i]); - for (Object document : loadAll(input)) { - assertNotNull("File " + files[i], document); - } - input.close(); - fail("Loading must fail for " + files[i].getAbsolutePath()); - // System.err.println("Loading must fail for " + - // files[i].getAbsolutePath()); - } catch (Exception e) { - assertTrue(true); - } + public void testLoaderErrors() throws FileNotFoundException { + File[] files = getStreamsByExtension(".loader-error"); + assertTrue("No test files found.", files.length > 0); + for (int i = 0; i < files.length; i++) { + if (skip(files[i].getName())) { + continue; + } + try { + InputStream input = new FileInputStream(files[i]); + for (Object document : loadAll(input)) { + assertNotNull("File " + files[i], document); } + input.close(); + fail("Loading must fail for " + files[i].getAbsolutePath()); + // System.err.println("Loading must fail for " + + // files[i].getAbsolutePath()); + } catch (Exception e) { + assertTrue(true); + } } + } - public void testLoaderStringErrors() throws FileNotFoundException { - File[] files = getStreamsByExtension(".loader-error"); - assertTrue("No test files found.", files.length > 0); - for (int i = 0; i < files.length; i++) { - if (skip(files[i].getName())) { - continue; - } - try { - String content = getResource(files[i].getName()); - for (Object document : loadAll(content.trim())) { - assertNotNull(document); - } - fail("Loading must fail for " + files[i].getAbsolutePath()); - // System.err.println("Loading must fail for " + - // files[i].getAbsolutePath()); - } catch (Exception e) { - assertTrue(true); - } + public void testLoaderStringErrors() throws FileNotFoundException { + File[] files = getStreamsByExtension(".loader-error"); + assertTrue("No test files found.", files.length > 0); + for (int i = 0; i < files.length; i++) { + if (skip(files[i].getName())) { + continue; + } + try { + String content = getResource(files[i].getName()); + for (Object document : loadAll(content.trim())) { + assertNotNull(document); } + fail("Loading must fail for " + files[i].getAbsolutePath()); + // System.err.println("Loading must fail for " + + // files[i].getAbsolutePath()); + } catch (Exception e) { + assertTrue(true); + } } + } - public void testLoaderSingleErrors() throws FileNotFoundException { - File[] files = getStreamsByExtension(".single-loader-error"); - assertTrue("No test files found.", files.length > 0); - for (int i = 0; i < files.length; i++) { - try { - String content = getResource(files[i].getName()); - load(content.trim()); - fail("Loading must fail for " + files[i].getAbsolutePath()); - // multiple documents must not be accepted - System.err.println("Loading must fail for " + files[i].getAbsolutePath()); - } catch (YAMLException e) { - assertTrue(true); - } - } + public void testLoaderSingleErrors() throws FileNotFoundException { + File[] files = getStreamsByExtension(".single-loader-error"); + assertTrue("No test files found.", files.length > 0); + for (int i = 0; i < files.length; i++) { + try { + String content = getResource(files[i].getName()); + load(content.trim()); + fail("Loading must fail for " + files[i].getAbsolutePath()); + // multiple documents must not be accepted + System.err.println("Loading must fail for " + files[i].getAbsolutePath()); + } catch (YAMLException e) { + assertTrue(true); + } } + } - @SuppressWarnings("unchecked") - public void testEmitterErrors() { - File[] files = getStreamsByExtension(".emitter-error"); - assertTrue("No test files found.", files.length > 0); - for (int i = 0; i < files.length; i++) { - String content = getResource(files[i].getName()); - List<Event> document = (List<Event>) load(new EventConstructor(), content.trim()); - Writer writer = new StringWriter(); - Emitter emitter = new Emitter(writer, new DumperOptions()); - try { - for (Event event : document) { - emitter.emit(event); - } - fail("Loading must fail for " + files[i].getAbsolutePath()); - // System.err.println("Loading must fail for " + - // files[i].getAbsolutePath()); - } catch (Exception e) { - assertTrue(true); - } + @SuppressWarnings("unchecked") + public void testEmitterErrors() { + File[] files = getStreamsByExtension(".emitter-error"); + assertTrue("No test files found.", files.length > 0); + for (int i = 0; i < files.length; i++) { + String content = getResource(files[i].getName()); + List<Event> document = (List<Event>) load(new EventConstructor(), content.trim()); + Writer writer = new StringWriter(); + Emitter emitter = new Emitter(writer, new DumperOptions()); + try { + for (Event event : document) { + emitter.emit(event); } + fail("Loading must fail for " + files[i].getAbsolutePath()); + // System.err.println("Loading must fail for " + + // files[i].getAbsolutePath()); + } catch (Exception e) { + assertTrue(true); + } } + } - // testDumperErrors() is implemented in SerializerTest.java + // testDumperErrors() is implemented in SerializerTest.java } diff --git a/src/test/java/org/pyyaml/PyImportTest.java b/src/test/java/org/pyyaml/PyImportTest.java index 966e5e77..30cdf9ec 100644 --- a/src/test/java/org/pyyaml/PyImportTest.java +++ b/src/test/java/org/pyyaml/PyImportTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -21,9 +19,7 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; @@ -34,102 +30,103 @@ import org.yaml.snakeyaml.reader.StreamReader; import org.yaml.snakeyaml.reader.UnicodeReader; public abstract class PyImportTest extends TestCase { - public static final String PATH = "pyyaml"; - - protected Object load(String data) { - Yaml yaml = new Yaml(); - return yaml.load(data); - } - - protected Object load(Constructor loader, String data) { - Yaml yaml = new Yaml(loader); - return yaml.load(data); - } - - protected Iterable<Object> loadAll(InputStream data) { - Yaml yaml = new Yaml(); - return yaml.loadAll(data); - } - protected Iterable<Object> loadAll(String data) { - Yaml yaml = new Yaml(); - return yaml.loadAll(data); + public static final String PATH = "pyyaml"; + + protected Object load(String data) { + Yaml yaml = new Yaml(); + return yaml.load(data); + } + + protected Object load(Constructor loader, String data) { + Yaml yaml = new Yaml(loader); + return yaml.load(data); + } + + protected Iterable<Object> loadAll(InputStream data) { + Yaml yaml = new Yaml(); + return yaml.loadAll(data); + } + + protected Iterable<Object> loadAll(String data) { + Yaml yaml = new Yaml(); + return yaml.loadAll(data); + } + + protected Iterable<Object> loadAll(Constructor loader, String data) { + Yaml yaml = new Yaml(loader); + return yaml.loadAll(data); + } + + protected String getResource(String theName) { + return Util.getLocalResource(PATH + File.separator + theName); + } + + protected File[] getStreamsByExtension(String extention) { + return getStreamsByExtension(extention, false); + } + + protected File[] getStreamsByExtension(String extention, boolean onlyIfCanonicalPresent) { + File file = new File("src/test/resources/pyyaml"); + assertTrue("Folder not found: " + file.getAbsolutePath(), file.exists()); + assertTrue(file.isDirectory()); + return file.listFiles(new PyFilenameFilter(extention, onlyIfCanonicalPresent)); + } + + protected File getFileByName(String name) { + File file = new File("src/test/resources/pyyaml/" + name); + assertTrue("Folder not found: " + file.getAbsolutePath(), file.exists()); + assertTrue(file.isFile()); + return file; + } + + protected List<Event> canonicalParse(InputStream input2) throws IOException { + StreamReader reader = new StreamReader(new UnicodeReader(input2)); + StringBuilder buffer = new StringBuilder(); + while (reader.peek() != '\0') { + buffer.appendCodePoint(reader.peek()); + reader.forward(); } - - protected Iterable<Object> loadAll(Constructor loader, String data) { - Yaml yaml = new Yaml(loader); - return yaml.loadAll(data); - } - - protected String getResource(String theName) { - String content; - content = Util.getLocalResource(PATH + File.separator + theName); - return content; - } - - protected File[] getStreamsByExtension(String extention) { - return getStreamsByExtension(extention, false); + CanonicalParser parser = + new CanonicalParser(buffer.toString().replace(System.lineSeparator(), "\n")); + List<Event> result = new ArrayList<Event>(); + while (parser.peekEvent() != null) { + result.add(parser.getEvent()); } - - protected File[] getStreamsByExtension(String extention, boolean onlyIfCanonicalPresent) { - File file = new File("src/test/resources/pyyaml"); - assertTrue("Folder not found: " + file.getAbsolutePath(), file.exists()); - assertTrue(file.isDirectory()); - return file.listFiles(new PyFilenameFilter(extention, onlyIfCanonicalPresent)); + input2.close(); + return result; + } + + protected List<Event> parse(InputStream input) throws IOException { + StreamReader reader = new StreamReader(new UnicodeReader(input)); + Parser parser = new ParserImpl(reader); + List<Event> result = new ArrayList<Event>(); + while (parser.peekEvent() != null) { + result.add(parser.getEvent()); } + input.close(); + return result; + } - protected File getFileByName(String name) { - File file = new File("src/test/resources/pyyaml/" + name); - assertTrue("Folder not found: " + file.getAbsolutePath(), file.exists()); - assertTrue(file.isFile()); - return file; - } + private class PyFilenameFilter implements FilenameFilter { - protected List<Event> canonicalParse(InputStream input2) throws IOException { - StreamReader reader = new StreamReader(new UnicodeReader(input2)); - StringBuilder buffer = new StringBuilder(); - while (reader.peek() != '\0') { - buffer.append(reader.peek()); - reader.forward(); - } - CanonicalParser parser = new CanonicalParser(buffer.toString()); - List<Event> result = new ArrayList<Event>(); - while (parser.peekEvent() != null) { - result.add(parser.getEvent()); - } - input2.close(); - return result; - } + private final String extension; + private final boolean onlyIfCanonicalPresent; - protected List<Event> parse(InputStream input) throws IOException { - StreamReader reader = new StreamReader(new UnicodeReader(input)); - Parser parser = new ParserImpl(reader); - List<Event> result = new ArrayList<Event>(); - while (parser.peekEvent() != null) { - result.add(parser.getEvent()); - } - input.close(); - return result; + public PyFilenameFilter(String extension, boolean onlyIfCanonicalPresent) { + this.extension = extension; + this.onlyIfCanonicalPresent = onlyIfCanonicalPresent; } - private class PyFilenameFilter implements FilenameFilter { - private String extension; - private boolean onlyIfCanonicalPresent; - - public PyFilenameFilter(String extension, boolean onlyIfCanonicalPresent) { - this.extension = extension; - this.onlyIfCanonicalPresent = onlyIfCanonicalPresent; - } - - public boolean accept(File dir, String name) { - int position = name.lastIndexOf('.'); - String canonicalFileName = name.substring(0, position) + ".canonical"; - File canonicalFile = new File(dir, canonicalFileName); - if (onlyIfCanonicalPresent && !canonicalFile.exists()) { - return false; - } else { - return name.endsWith(extension); - } - } + public boolean accept(File dir, String name) { + int position = name.lastIndexOf('.'); + String canonicalFileName = name.substring(0, position) + ".canonical"; + File canonicalFile = new File(dir, canonicalFileName); + if (onlyIfCanonicalPresent && !canonicalFile.exists()) { + return false; + } else { + return name.endsWith(extension); + } } + } } diff --git a/src/test/java/org/pyyaml/PyMarkTest.java b/src/test/java/org/pyyaml/PyMarkTest.java index 3f6f8f92..96e6d5a6 100644 --- a/src/test/java/org/pyyaml/PyMarkTest.java +++ b/src/test/java/org/pyyaml/PyMarkTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -22,36 +20,35 @@ import org.yaml.snakeyaml.error.Mark; */ public class PyMarkTest extends PyImportTest { - public void testMarks() { - String content = getResource("test_mark.marks"); - String[] inputs = content.split("---\n"); - for (int i = 1; i < inputs.length; i++) { - String input = inputs[i]; - int index = 0; - int line = 0; - int column = 0; - while (input.charAt(index) != '*') { - if (input.charAt(index) != '\n') { - line += 1; - column = 0; - } else { - column += 1; - } - index += 1; - } - Mark mark = new Mark("testMarks", index, line, column, input, index); - String snippet = mark.get_snippet(2, 79); - assertTrue("Must only have one '\n'.", snippet.indexOf("\n") > -1); - assertEquals("Must only have only one '\n'.", snippet.indexOf("\n"), - snippet.lastIndexOf("\n")); - String[] lines = snippet.split("\n"); - String data = lines[0]; - String pointer = lines[1]; - assertTrue("Mark must be restricted: " + data, data.length() < 82); - int dataPosition = data.indexOf("*"); - int pointerPosition = pointer.indexOf("^"); - assertEquals("Pointer should coincide with '*':\n " + snippet, dataPosition, - pointerPosition); + public void testMarks() { + String content = getResource("test_mark.marks"); + String[] inputs = content.split("---\n"); + for (int i = 1; i < inputs.length; i++) { + String input = inputs[i]; + int index = 0; + int line = 0; + int column = 0; + while (input.charAt(index) != '*') { + if (input.charAt(index) != '\n') { + line += 1; + column = 0; + } else { + column += 1; } + index += 1; + } + Mark mark = new Mark("testMarks", index, line, column, input.toCharArray(), index); + String snippet = mark.get_snippet(2, 79); + assertTrue("Must only have one '\n'.", snippet.indexOf("\n") > -1); + assertEquals("Must only have only one '\n'.", snippet.indexOf("\n"), + snippet.lastIndexOf("\n")); + String[] lines = snippet.split("\n"); + String data = lines[0]; + String pointer = lines[1]; + assertTrue("Mark must be restricted: " + data, data.length() < 82); + int dataPosition = data.indexOf("*"); + int pointerPosition = pointer.indexOf("^"); + assertEquals("Pointer should coincide with '*':\n " + snippet, dataPosition, pointerPosition); } + } } diff --git a/src/test/java/org/pyyaml/PyReaderTest.java b/src/test/java/org/pyyaml/PyReaderTest.java index 3b251895..14377bb1 100644 --- a/src/test/java/org/pyyaml/PyReaderTest.java +++ b/src/test/java/org/pyyaml/PyReaderTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -19,7 +17,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; - import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.reader.ReaderException; import org.yaml.snakeyaml.reader.StreamReader; @@ -30,25 +27,25 @@ import org.yaml.snakeyaml.reader.UnicodeReader; */ public class PyReaderTest extends PyImportTest { - public void testReaderUnicodeErrors() throws IOException { - File[] inputs = getStreamsByExtension(".stream-error"); - for (int i = 0; i < inputs.length; i++) { - InputStream input = new FileInputStream(inputs[i]); - StreamReader stream = new StreamReader(new UnicodeReader(input)); - try { - while (stream.peek() != '\u0000') { - stream.forward(); - } - fail("Invalid stream must not be accepted: " + inputs[i].getAbsolutePath() - + "; encoding=" + stream.getEncoding()); - } catch (ReaderException e) { - assertTrue(e.toString(), - e.toString().contains(" special characters are not allowed")); - } catch (YAMLException e) { - assertTrue(e.toString(), e.toString().contains("MalformedInputException")); - } finally { - input.close(); - } + public void testReaderUnicodeErrors() throws IOException { + File[] inputs = getStreamsByExtension(".stream-error"); + for (int i = 0; i < inputs.length; i++) { + InputStream input = new FileInputStream(inputs[i]); + UnicodeReader unicodeReader = new UnicodeReader(input); + StreamReader stream = new StreamReader(unicodeReader); + try { + while (stream.peek() != '\u0000') { + stream.forward(); } + fail("Invalid stream must not be accepted: " + inputs[i].getAbsolutePath() + "; encoding=" + + unicodeReader.getEncoding()); + } catch (ReaderException e) { + assertTrue(e.toString(), e.toString().contains(" special characters are not allowed")); + } catch (YAMLException e) { + assertTrue(e.toString(), e.toString().contains("MalformedInputException")); + } finally { + input.close(); + } } + } } diff --git a/src/test/java/org/pyyaml/PyRecursiveTest.java b/src/test/java/org/pyyaml/PyRecursiveTest.java index da353df7..1392b883 100644 --- a/src/test/java/org/pyyaml/PyRecursiveTest.java +++ b/src/test/java/org/pyyaml/PyRecursiveTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -22,123 +20,121 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; public class PyRecursiveTest extends TestCase { - @SuppressWarnings("unchecked") - public void testDict() { - Map<AnInstance, AnInstance> value = new HashMap<AnInstance, AnInstance>(); - AnInstance instance = new AnInstance(value, value); - value.put(instance, instance); - Yaml yaml = new Yaml(); - String output1 = yaml.dump(value); - assertTrue(output1.contains("!!org.pyyaml.AnInstance")); - assertTrue(output1.contains("&id001")); - assertTrue(output1.contains("&id002")); - assertTrue(output1.contains("*id001")); - assertTrue(output1.contains("*id002")); - assertTrue(output1.contains("foo")); - assertTrue(output1.contains("bar")); - Map<AnInstance, AnInstance> value2 = (Map<AnInstance, AnInstance>) yaml.load(output1); - assertEquals(value.size(), value2.size()); - for (AnInstance tmpInstance : value2.values()) { - assertSame(tmpInstance.getBar(), tmpInstance.getFoo()); - assertSame(tmpInstance.getBar(), value2); - assertSame(tmpInstance, value2.get(tmpInstance)); - } + @SuppressWarnings("unchecked") + public void testDict() { + Map<AnInstance, AnInstance> value = new HashMap<AnInstance, AnInstance>(); + AnInstance instance = new AnInstance(value, value); + value.put(instance, instance); + Yaml yaml = new Yaml(); + String output1 = yaml.dump(value); + assertTrue(output1.contains("!!org.pyyaml.AnInstance")); + assertTrue(output1.contains("&id001")); + assertTrue(output1.contains("&id002")); + assertTrue(output1.contains("*id001")); + assertTrue(output1.contains("*id002")); + assertTrue(output1.contains("foo")); + assertTrue(output1.contains("bar")); + Map<AnInstance, AnInstance> value2 = yaml.load(output1); + assertEquals(value.size(), value2.size()); + for (AnInstance tmpInstance : value2.values()) { + assertSame(tmpInstance.getBar(), tmpInstance.getFoo()); + assertSame(tmpInstance.getBar(), value2); + assertSame(tmpInstance, value2.get(tmpInstance)); } + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testDictSafeConstructor() { - Map value = new TreeMap(); - value.put("abc", "www"); - value.put("qwerty", value); - Yaml yaml = new Yaml(new SafeConstructor()); - String output1 = yaml.dump(value); - assertEquals("&id001\nabc: www\nqwerty: *id001\n", output1); - Map value2 = (Map) yaml.load(output1); - assertEquals(2, value2.size()); - assertEquals("www", value2.get("abc")); - assertTrue(value2.get("qwerty") instanceof Map); - Map value3 = (Map) value2.get("qwerty"); - assertTrue(value3.get("qwerty") instanceof Map); - } + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testDictSafeConstructor() { + Map value = new TreeMap(); + value.put("abc", "www"); + value.put("qwerty", value); + Yaml yaml = new Yaml(new SafeConstructor()); + String output1 = yaml.dump(value); + assertEquals("&id001\nabc: www\nqwerty: *id001\n", output1); + Map value2 = yaml.load(output1); + assertEquals(2, value2.size()); + assertEquals("www", value2.get("abc")); + assertTrue(value2.get("qwerty") instanceof Map); + Map value3 = (Map) value2.get("qwerty"); + assertTrue(value3.get("qwerty") instanceof Map); + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testList() { - List value = new ArrayList(); - value.add(value); - value.add("test"); - value.add(new Integer(1)); + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testList() { + List value = new ArrayList(); + value.add(value); + value.add("test"); + value.add(Integer.valueOf(1)); - Yaml yaml = new Yaml(); - String output1 = yaml.dump(value); - assertEquals("&id001\n- *id001\n- test\n- 1\n", output1); - List value2 = (List) yaml.load(output1); - assertEquals(3, value2.size()); - assertEquals(value.size(), value2.size()); - assertSame(value2, value2.get(0)); - // we expect self-reference as 1st element of the list - // let's remove self-reference and check other "simple" members of the - // list. otherwise assertEquals will lead us to StackOverflow - value.remove(0); - value2.remove(0); - assertEquals(value, value2); - } + Yaml yaml = new Yaml(); + String output1 = yaml.dump(value); + assertEquals("&id001\n- *id001\n- test\n- 1\n", output1); + List value2 = yaml.load(output1); + assertEquals(3, value2.size()); + assertEquals(value.size(), value2.size()); + assertSame(value2, value2.get(0)); + // we expect self-reference as 1st element of the list + // let's remove self-reference and check other "simple" members of the + // list. otherwise assertEquals will lead us to StackOverflow + value.remove(0); + value2.remove(0); + assertEquals(value, value2); + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testListSafeConstructor() { - List value = new ArrayList(); - value.add(value); - value.add("test"); - value.add(new Integer(1)); + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testListSafeConstructor() { + List value = new ArrayList(); + value.add(value); + value.add("test"); + value.add(Integer.valueOf(1)); - Yaml yaml = new Yaml(new SafeConstructor()); - String output1 = yaml.dump(value); - assertEquals("&id001\n- *id001\n- test\n- 1\n", output1); - List value2 = (List) yaml.load(output1); - assertEquals(3, value2.size()); - assertEquals(value.size(), value2.size()); - assertSame(value2, value2.get(0)); - // we expect self-reference as 1st element of the list - // let's remove self-reference and check other "simple" members of the - // list. otherwise assertEquals will lead us to StackOverflow - value.remove(0); - value2.remove(0); - assertEquals(value, value2); - } + Yaml yaml = new Yaml(new SafeConstructor()); + String output1 = yaml.dump(value); + assertEquals("&id001\n- *id001\n- test\n- 1\n", output1); + List value2 = yaml.load(output1); + assertEquals(3, value2.size()); + assertEquals(value.size(), value2.size()); + assertSame(value2, value2.get(0)); + // we expect self-reference as 1st element of the list + // let's remove self-reference and check other "simple" members of the + // list. otherwise assertEquals will lead us to StackOverflow + value.remove(0); + value2.remove(0); + assertEquals(value, value2); + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testSet() { - Set value = new HashSet(); - value.add(new AnInstance(value, value)); - Yaml yaml = new Yaml(); - String output1 = yaml.dump(value); - Set<AnInstance> value2 = (Set<AnInstance>) yaml.load(output1); + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testSet() { + Set value = new HashSet(); + value.add(new AnInstance(value, value)); + Yaml yaml = new Yaml(); + String output1 = yaml.dump(value); + Set<AnInstance> value2 = yaml.load(output1); - assertEquals(value.size(), value2.size()); - for (AnInstance tmpInstance : value2) { - assertSame(tmpInstance.getBar(), tmpInstance.getFoo()); - assertSame(tmpInstance.getBar(), value2); - } + assertEquals(value.size(), value2.size()); + for (AnInstance tmpInstance : value2) { + assertSame(tmpInstance.getBar(), tmpInstance.getFoo()); + assertSame(tmpInstance.getBar(), value2); } + } - public void testSet2() { - Set<Object> set = new HashSet<Object>(3); - set.add("aaa"); - set.add(111); - set.add(set); - Yaml yaml = new Yaml(); - try { - yaml.dump(set); - fail("Java does not allow a recursive set to be a key for a map."); - } catch (StackOverflowError e) { - // ignore - } + public void testSet2() { + Set<Object> set = new HashSet<Object>(3); + set.add("aaa"); + set.add(111); + set.add(set); + Yaml yaml = new Yaml(); + try { + yaml.dump(set); + fail("Java does not allow a recursive set to be a key for a map."); + } catch (StackOverflowError e) { + // ignore } + } } diff --git a/src/test/java/org/pyyaml/PyStructureTest.java b/src/test/java/org/pyyaml/PyStructureTest.java index 0d334645..108c9490 100644 --- a/src/test/java/org/pyyaml/PyStructureTest.java +++ b/src/test/java/org/pyyaml/PyStructureTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -22,7 +20,6 @@ import java.io.Reader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.constructor.AbstractConstruct; @@ -46,257 +43,262 @@ import org.yaml.snakeyaml.resolver.Resolver; */ public class PyStructureTest extends PyImportTest { - private void compareEvents(List<Event> events1, List<Event> events2, boolean full) { - assertEquals(events1.size(), events2.size()); - Iterator<Event> iter1 = events1.iterator(); - Iterator<Event> iter2 = events2.iterator(); - while (iter1.hasNext()) { - Event event1 = iter1.next(); - Event event2 = iter2.next(); - assertEquals(event1.getClass(), event2.getClass()); - if (event1 instanceof AliasEvent && full) { - assertEquals(((AliasEvent) event1).getAnchor(), ((AliasEvent) event2).getAnchor()); - } - if (event1 instanceof CollectionStartEvent) { - String tag1 = ((CollectionStartEvent) event1).getTag(); - String tag2 = ((CollectionStartEvent) event1).getTag(); - if (tag1 != null && !"!".equals(tag1) && tag2 != null && !"!".equals(tag1)) { - assertEquals(tag1, tag2); - } - } - if (event1 instanceof ScalarEvent) { - ScalarEvent scalar1 = (ScalarEvent) event1; - ScalarEvent scalar2 = (ScalarEvent) event2; - if (scalar1.getImplicit().bothFalse() && scalar2.getImplicit().bothFalse()) { - assertEquals(scalar1.getTag(), scalar2.getTag()); - } - assertEquals(scalar1.getValue(), scalar2.getValue()); - } + private void compareEvents(List<Event> events1, List<Event> events2, boolean full) { + assertEquals(events1.size(), events2.size()); + Iterator<Event> iter1 = events1.iterator(); + Iterator<Event> iter2 = events2.iterator(); + while (iter1.hasNext()) { + Event event1 = iter1.next(); + Event event2 = iter2.next(); + assertEquals(event1.getClass(), event2.getClass()); + if (event1 instanceof AliasEvent && full) { + assertEquals(((AliasEvent) event1).getAnchor(), ((AliasEvent) event2).getAnchor()); + } + if (event1 instanceof CollectionStartEvent) { + String tag1 = ((CollectionStartEvent) event1).getTag(); + String tag2 = ((CollectionStartEvent) event1).getTag(); + if (tag1 != null && !"!".equals(tag1) && tag2 != null && !"!".equals(tag1)) { + assertEquals(tag1, tag2); } + } + if (event1 instanceof ScalarEvent) { + ScalarEvent scalar1 = (ScalarEvent) event1; + ScalarEvent scalar2 = (ScalarEvent) event2; + if (scalar1.getImplicit().bothFalse() && scalar2.getImplicit().bothFalse()) { + assertEquals(scalar1.getTag(), scalar2.getTag()); + } + assertEquals(scalar1.getValue(), scalar2.getValue()); + } } + } - public void testParser() { - File[] files = getStreamsByExtension(".data", true); - assertTrue("No test files found.", files.length > 0); - for (File file : files) { - if (!file.getName().contains("scan-line-b")) { - continue; - } - try { - InputStream input = new FileInputStream(file); - List<Event> events1 = parse(input); - input.close(); - assertFalse(events1.isEmpty()); - int index = file.getAbsolutePath().lastIndexOf('.'); - String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical"; - File canonical = new File(canonicalName); - List<Event> events2 = canonicalParse(new FileInputStream(canonical)); - assertFalse(events2.isEmpty()); - compareEvents(events1, events2, false); - } catch (Exception e) { - System.out.println("Failed File: " + file); - // fail("Failed File: " + file + "; " + e.getMessage()); - throw new RuntimeException(e); - } - } + public void testParser() { + File[] files = getStreamsByExtension(".data", true); + assertTrue("No test files found.", files.length > 0); + for (File file : files) { + if (!file.getName().contains("scan-line-b")) { + continue; + } + try { + InputStream input = new FileInputStream(file); + List<Event> events1 = parse(input); + input.close(); + assertFalse(events1.isEmpty()); + int index = file.getAbsolutePath().lastIndexOf('.'); + String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical"; + File canonical = new File(canonicalName); + List<Event> events2 = canonicalParse(new FileInputStream(canonical)); + assertFalse(events2.isEmpty()); + compareEvents(events1, events2, false); + } catch (Exception e) { + System.out.println("Failed File: " + file); + // fail("Failed File: " + file + "; " + e.getMessage()); + throw new RuntimeException(e); + } } + } - public void testParserOnCanonical() { - File[] canonicalFiles = getStreamsByExtension(".canonical", false); - assertTrue("No test files found.", canonicalFiles.length > 0); - for (File file : canonicalFiles) { - try { - InputStream input = new FileInputStream(file); - List<Event> events1 = parse(input); - input.close(); - assertFalse(events1.isEmpty()); - List<Event> events2 = canonicalParse(new FileInputStream(file)); - assertFalse(events2.isEmpty()); - compareEvents(events1, events2, true); - } catch (Exception e) { - System.out.println("Failed File: " + file); - // fail("Failed File: " + file + "; " + e.getMessage()); - throw new RuntimeException(e); - } - } + public void testParserOnCanonical() { + File[] canonicalFiles = getStreamsByExtension(".canonical", false); + assertTrue("No test files found.", canonicalFiles.length > 0); + for (File file : canonicalFiles) { + try { + InputStream input = new FileInputStream(file); + List<Event> events1 = parse(input); + input.close(); + assertFalse(events1.isEmpty()); + List<Event> events2 = canonicalParse(new FileInputStream(file)); + assertFalse(events2.isEmpty()); + compareEvents(events1, events2, true); + } catch (Exception e) { + System.out.println("Failed File: " + file); + // fail("Failed File: " + file + "; " + e.getMessage()); + throw new RuntimeException(e); + } } + } - private void compareNodes(Node node1, Node node2) { - assertEquals(node1.getClass(), node2.getClass()); - if (node1 instanceof ScalarNode) { - ScalarNode scalar1 = (ScalarNode) node1; - ScalarNode scalar2 = (ScalarNode) node2; - assertEquals(scalar1.getTag(), scalar2.getTag()); - assertEquals(scalar1.getValue(), scalar2.getValue()); - } else { - if (node1 instanceof SequenceNode) { - SequenceNode seq1 = (SequenceNode) node1; - SequenceNode seq2 = (SequenceNode) node2; - assertEquals(seq1.getTag(), seq2.getTag()); - assertEquals(seq1.getValue().size(), seq2.getValue().size()); - Iterator<Node> iter2 = seq2.getValue().iterator(); - for (Node child1 : seq1.getValue()) { - Node child2 = iter2.next(); - compareNodes(child1, child2); - } - } else { - MappingNode seq1 = (MappingNode) node1; - MappingNode seq2 = (MappingNode) node2; - assertEquals(seq1.getTag(), seq2.getTag()); - assertEquals(seq1.getValue().size(), seq2.getValue().size()); - Iterator<NodeTuple> iter2 = seq2.getValue().iterator(); - for (NodeTuple child1 : seq1.getValue()) { - NodeTuple child2 = iter2.next(); - compareNodes(child1.getKeyNode(), child2.getKeyNode()); - compareNodes(child1.getValueNode(), child2.getValueNode()); - } - } + private void compareNodes(Node node1, Node node2) { + assertEquals(node1.getClass(), node2.getClass()); + if (node1 instanceof ScalarNode) { + ScalarNode scalar1 = (ScalarNode) node1; + ScalarNode scalar2 = (ScalarNode) node2; + assertEquals(scalar1.getTag(), scalar2.getTag()); + assertEquals(scalar1.getValue(), scalar2.getValue()); + } else { + if (node1 instanceof SequenceNode) { + SequenceNode seq1 = (SequenceNode) node1; + SequenceNode seq2 = (SequenceNode) node2; + assertEquals(seq1.getTag(), seq2.getTag()); + assertEquals(seq1.getValue().size(), seq2.getValue().size()); + Iterator<Node> iter2 = seq2.getValue().iterator(); + for (Node child1 : seq1.getValue()) { + Node child2 = iter2.next(); + compareNodes(child1, child2); } + } else { + MappingNode seq1 = (MappingNode) node1; + MappingNode seq2 = (MappingNode) node2; + assertEquals(seq1.getTag(), seq2.getTag()); + assertEquals(seq1.getValue().size(), seq2.getValue().size()); + Iterator<NodeTuple> iter2 = seq2.getValue().iterator(); + for (NodeTuple child1 : seq1.getValue()) { + NodeTuple child2 = iter2.next(); + compareNodes(child1.getKeyNode(), child2.getKeyNode()); + compareNodes(child1.getValueNode(), child2.getValueNode()); + } + } } + } - public void testComposer() { - File[] files = getStreamsByExtension(".data", true); - assertTrue("No test files found.", files.length > 0); - for (File file : files) { - try { - InputStream input = new FileInputStream(file); - List<Node> events1 = compose_all(input); - input.close(); - int index = file.getAbsolutePath().lastIndexOf('.'); - String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical"; - File canonical = new File(canonicalName); - InputStream input2 = new FileInputStream(canonical); - List<Node> events2 = canonical_compose_all(input2); - input2.close(); - assertEquals(events1.size(), events2.size()); - Iterator<Node> iter1 = events1.iterator(); - Iterator<Node> iter2 = events2.iterator(); - while (iter1.hasNext()) { - compareNodes(iter1.next(), iter2.next()); - } - } catch (Exception e) { - System.out.println("Failed File: " + file); - // fail("Failed File: " + file + "; " + e.getMessage()); - throw new RuntimeException(e); - } + public void testComposer() { + File[] files = getStreamsByExtension(".data", true); + assertTrue("No test files found.", files.length > 0); + for (File file : files) { + try { + InputStream input = new FileInputStream(file); + List<Node> events1 = compose_all(input); + input.close(); + int index = file.getAbsolutePath().lastIndexOf('.'); + String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical"; + File canonical = new File(canonicalName); + InputStream input2 = new FileInputStream(canonical); + List<Node> events2 = canonical_compose_all(input2); + input2.close(); + assertEquals(events1.size(), events2.size()); + Iterator<Node> iter1 = events1.iterator(); + Iterator<Node> iter2 = events2.iterator(); + while (iter1.hasNext()) { + compareNodes(iter1.next(), iter2.next()); } + } catch (Exception e) { + System.out.println("Failed File: " + file); + // fail("Failed File: " + file + "; " + e.getMessage()); + throw new RuntimeException(e); + } } + } - private List<Node> compose_all(InputStream file) { - Composer composer = new Composer(new ParserImpl(new StreamReader(new UnicodeReader(file))), - new Resolver()); - List<Node> documents = new ArrayList<Node>(); - while (composer.checkNode()) { - documents.add(composer.getNode()); - } - return documents; + private List<Node> compose_all(InputStream file) { + Composer composer = + new Composer(new ParserImpl(new StreamReader(new UnicodeReader(file))), new Resolver()); + List<Node> documents = new ArrayList<Node>(); + while (composer.checkNode()) { + documents.add(composer.getNode()); + } + return documents; + } + + private List<Node> canonical_compose_all(InputStream file) { + StreamReader reader = new StreamReader(new UnicodeReader(file)); + StringBuilder buffer = new StringBuilder(); + while (reader.peek() != '\0') { + buffer.appendCodePoint(reader.peek()); + reader.forward(); + } + CanonicalParser parser = + new CanonicalParser(buffer.toString().replace(System.lineSeparator(), "\n")); + Composer composer = new Composer(parser, new Resolver()); + List<Node> documents = new ArrayList<Node>(); + while (composer.checkNode()) { + documents.add(composer.getNode()); + } + return documents; + } + + class CanonicalLoader extends Yaml { + + public CanonicalLoader() { + super(new MyConstructor()); } - private List<Node> canonical_compose_all(InputStream file) { - StreamReader reader = new StreamReader(new UnicodeReader(file)); - StringBuilder buffer = new StringBuilder(); - while (reader.peek() != '\0') { - buffer.append(reader.peek()); - reader.forward(); + @Override + public Iterable<Object> loadAll(Reader yaml) { + StreamReader reader = new StreamReader(yaml); + StringBuilder buffer = new StringBuilder(); + while (reader.peek() != '\0') { + buffer.appendCodePoint(reader.peek()); + reader.forward(); + } + CanonicalParser parser = + new CanonicalParser(buffer.toString().replace(System.lineSeparator(), "\n")); + Composer composer = new Composer(parser, resolver); + this.constructor.setComposer(composer); + Iterator<Object> result = new Iterator<Object>() { + public boolean hasNext() { + return constructor.checkData(); } - CanonicalParser parser = new CanonicalParser(buffer.toString()); - Composer composer = new Composer(parser, new Resolver()); - List<Node> documents = new ArrayList<Node>(); - while (composer.checkNode()) { - documents.add(composer.getNode()); + + public Object next() { + return constructor.getData(); } - return documents; - } - class CanonicalLoader extends Yaml { - public CanonicalLoader() { - super(new MyConstructor()); + public void remove() { + throw new UnsupportedOperationException(); } + }; + return new YamlIterable(result); + } - @Override - public Iterable<Object> loadAll(Reader yaml) { - StreamReader reader = new StreamReader(yaml); - StringBuilder buffer = new StringBuilder(); - while (reader.peek() != '\0') { - buffer.append(reader.peek()); - reader.forward(); - } - CanonicalParser parser = new CanonicalParser(buffer.toString()); - Composer composer = new Composer(parser, resolver); - this.constructor.setComposer(composer); - Iterator<Object> result = new Iterator<Object>() { - public boolean hasNext() { - return constructor.checkData(); - } + private class YamlIterable implements Iterable<Object> { - public Object next() { - return constructor.getData(); - } + private final Iterator<Object> iterator; - public void remove() { - throw new UnsupportedOperationException(); - } - }; - return new YamlIterable(result); - } + public YamlIterable(Iterator<Object> iterator) { + this.iterator = iterator; + } - private class YamlIterable implements Iterable<Object> { - private Iterator<Object> iterator; + public Iterator<Object> iterator() { + return iterator; + } - public YamlIterable(Iterator<Object> iterator) { - this.iterator = iterator; - } + } - public Iterator<Object> iterator() { - return iterator; - } + } - } + private class MyConstructor extends Constructor { + public MyConstructor() { + this.yamlConstructors.put(null, new ConstructUndefined()); } - private class MyConstructor extends Constructor { - public MyConstructor() { - this.yamlConstructors.put(null, new ConstructUndefined()); - } + private class ConstructUndefined extends AbstractConstruct { - private class ConstructUndefined extends AbstractConstruct { - public Object construct(Node node) { - return constructScalar((ScalarNode) node); - } - } + public Object construct(Node node) { + return constructScalar((ScalarNode) node); + } } + } - public void testConstructor() { - File[] files = getStreamsByExtension(".data", true); - assertTrue("No test files found.", files.length > 0); - Yaml myYaml = new Yaml(new MyConstructor()); - Yaml canonicalYaml = new CanonicalLoader(); - for (File file : files) { - try { - InputStream input = new FileInputStream(file); - Iterable<Object> documents1 = myYaml.loadAll(input); - int index = file.getAbsolutePath().lastIndexOf('.'); - String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical"; - File canonical = new File(canonicalName); - InputStream input2 = new FileInputStream(canonical); - Iterable<Object> documents2 = canonicalYaml.loadAll(input2); - input2.close(); - Iterator<Object> iter2 = documents2.iterator(); - for (Object object1 : documents1) { - Object object2 = iter2.next(); - if (object2 != null) { - assertFalse(System.identityHashCode(object1) == System - .identityHashCode(object2)); - } - assertEquals("" + object1, object1, object2); - } - input.close(); - } catch (Exception e) { - System.out.println("Failed File: " + file); - // fail("Failed File: " + file + "; " + e.getMessage()); - throw new RuntimeException(e); - } + public void testConstructor() { + File[] files = getStreamsByExtension(".data", true); + assertTrue("No test files found.", files.length > 0); + Yaml myYaml = new Yaml(new MyConstructor()); + Yaml canonicalYaml = new CanonicalLoader(); + for (File file : files) { + try { + InputStream input = new FileInputStream(file); + Iterable<Object> documents1 = myYaml.loadAll(input); + int index = file.getAbsolutePath().lastIndexOf('.'); + String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical"; + File canonical = new File(canonicalName); + InputStream input2 = new FileInputStream(canonical); + Iterable<Object> documents2 = canonicalYaml.loadAll(input2); + input2.close(); + Iterator<Object> iter2 = documents2.iterator(); + for (Object object1 : documents1) { + Object object2 = iter2.next(); + if (object2 != null) { + assertFalse(System.identityHashCode(object1) == System.identityHashCode(object2)); + } + assertEquals("" + object1, object1, object2); } + input.close(); + } catch (Exception e) { + System.out.println("Failed File: " + file); + // fail("Failed File: " + file + "; " + e.getMessage()); + throw new RuntimeException(e); + } } + } } diff --git a/src/test/java/org/pyyaml/PyTokensTest.java b/src/test/java/org/pyyaml/PyTokensTest.java index 646c4c2d..733eabf6 100644 --- a/src/test/java/org/pyyaml/PyTokensTest.java +++ b/src/test/java/org/pyyaml/PyTokensTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.pyyaml; @@ -21,128 +19,108 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.reader.StreamReader; import org.yaml.snakeyaml.reader.UnicodeReader; import org.yaml.snakeyaml.scanner.Scanner; import org.yaml.snakeyaml.scanner.ScannerImpl; -import org.yaml.snakeyaml.tokens.AliasToken; -import org.yaml.snakeyaml.tokens.AnchorToken; -import org.yaml.snakeyaml.tokens.BlockEndToken; -import org.yaml.snakeyaml.tokens.BlockEntryToken; -import org.yaml.snakeyaml.tokens.BlockMappingStartToken; -import org.yaml.snakeyaml.tokens.BlockSequenceStartToken; -import org.yaml.snakeyaml.tokens.DirectiveToken; -import org.yaml.snakeyaml.tokens.DocumentEndToken; -import org.yaml.snakeyaml.tokens.DocumentStartToken; -import org.yaml.snakeyaml.tokens.FlowEntryToken; -import org.yaml.snakeyaml.tokens.FlowMappingEndToken; -import org.yaml.snakeyaml.tokens.FlowMappingStartToken; -import org.yaml.snakeyaml.tokens.FlowSequenceEndToken; -import org.yaml.snakeyaml.tokens.FlowSequenceStartToken; -import org.yaml.snakeyaml.tokens.KeyToken; -import org.yaml.snakeyaml.tokens.ScalarToken; import org.yaml.snakeyaml.tokens.StreamEndToken; import org.yaml.snakeyaml.tokens.StreamStartToken; -import org.yaml.snakeyaml.tokens.TagToken; import org.yaml.snakeyaml.tokens.Token; -import org.yaml.snakeyaml.tokens.ValueToken; /** * imported from PyYAML */ public class PyTokensTest extends PyImportTest { - public void testTokens() throws FileNotFoundException { - Map<Class<?>, String> replaces = new HashMap<Class<?>, String>(); - replaces.put(DirectiveToken.class, "%"); - replaces.put(DocumentStartToken.class, "---"); - replaces.put(DocumentEndToken.class, "..."); - replaces.put(AliasToken.class, "*"); - replaces.put(AnchorToken.class, "&"); - replaces.put(TagToken.class, "!"); - replaces.put(ScalarToken.class, "_"); - replaces.put(BlockSequenceStartToken.class, "[["); - replaces.put(BlockMappingStartToken.class, "{{"); - replaces.put(BlockEndToken.class, "]}"); - replaces.put(FlowSequenceStartToken.class, "["); - replaces.put(FlowSequenceEndToken.class, "]"); - replaces.put(FlowMappingStartToken.class, "{"); - replaces.put(FlowMappingEndToken.class, "}"); - replaces.put(BlockEntryToken.class, ","); - replaces.put(FlowEntryToken.class, ","); - replaces.put(KeyToken.class, "?"); - replaces.put(ValueToken.class, ":"); - // - File[] tokensFiles = getStreamsByExtension(".tokens"); - assertTrue("No test files found.", tokensFiles.length > 0); - for (int i = 0; i < tokensFiles.length; i++) { - String name = tokensFiles[i].getName(); - int position = name.lastIndexOf('.'); - String dataName = name.substring(0, position) + ".data"; - // - String tokenFileData = getResource(name); - String[] split = tokenFileData.split("\\s+"); - List<String> tokens2 = new ArrayList<String>(); - for (int j = 0; j < split.length; j++) { - tokens2.add(split[j]); - } - // - List<String> tokens1 = new ArrayList<String>(); - StreamReader reader = new StreamReader(new UnicodeReader(new FileInputStream( - getFileByName(dataName)))); - Scanner scanner = new ScannerImpl(reader); - try { - while (scanner.checkToken(new Token.ID[0])) { - Token token = scanner.getToken(); - if (!(token instanceof StreamStartToken || token instanceof StreamEndToken)) { - String replacement = replaces.get(token.getClass()); - tokens1.add(replacement); - } - } - assertEquals(tokenFileData, tokens1.size(), tokens2.size()); - assertEquals(tokens1, tokens2); - } catch (RuntimeException e) { - System.out.println("File name: \n" + tokensFiles[i].getName()); - String data = getResource(tokensFiles[i].getName()); - System.out.println("Data: \n" + data); - System.out.println("Tokens:"); - for (String token : tokens1) { - System.out.println(token); - } - fail("Cannot scan: " + tokensFiles[i]); - } + public void testTokens() throws FileNotFoundException { + Map<Token.ID, String> replaces = new HashMap<Token.ID, String>(); + replaces.put(Token.ID.Directive, "%"); + replaces.put(Token.ID.DocumentStart, "---"); + replaces.put(Token.ID.DocumentEnd, "..."); + replaces.put(Token.ID.Alias, "*"); + replaces.put(Token.ID.Anchor, "&"); + replaces.put(Token.ID.Tag, "!"); + replaces.put(Token.ID.Scalar, "_"); + replaces.put(Token.ID.BlockSequenceStart, "[["); + replaces.put(Token.ID.BlockMappingStart, "{{"); + replaces.put(Token.ID.BlockEnd, "]}"); + replaces.put(Token.ID.FlowSequenceStart, "["); + replaces.put(Token.ID.FlowSequenceEnd, "]"); + replaces.put(Token.ID.FlowMappingStart, "{"); + replaces.put(Token.ID.FlowMappingEnd, "}"); + replaces.put(Token.ID.BlockEntry, ","); + replaces.put(Token.ID.FlowEntry, ","); + replaces.put(Token.ID.Key, "?"); + replaces.put(Token.ID.Value, ":"); + // + File[] tokensFiles = getStreamsByExtension(".tokens"); + assertTrue("No test files found.", tokensFiles.length > 0); + for (int i = 0; i < tokensFiles.length; i++) { + String name = tokensFiles[i].getName(); + int position = name.lastIndexOf('.'); + String dataName = name.substring(0, position) + ".data"; + // + String tokenFileData = getResource(name); + String[] split = tokenFileData.split("\\s+"); + List<String> tokens2 = new ArrayList<String>(); + Collections.addAll(tokens2, split); + // + List<String> tokens1 = new ArrayList<String>(); + StreamReader reader = + new StreamReader(new UnicodeReader(new FileInputStream(getFileByName(dataName)))); + Scanner scanner = new ScannerImpl(reader); + try { + while (scanner.checkToken()) { + Token token = scanner.getToken(); + if (!(token instanceof StreamStartToken || token instanceof StreamEndToken)) { + String replacement = replaces.get(token.getTokenId()); + tokens1.add(replacement); + } + } + assertEquals(tokenFileData, tokens1.size(), tokens2.size()); + assertEquals(tokens1, tokens2); + } catch (RuntimeException e) { + System.out.println("File name: \n" + tokensFiles[i].getName()); + String data = getResource(tokensFiles[i].getName()); + System.out.println("Data: \n" + data); + System.out.println("Tokens:"); + for (String token : tokens1) { + System.out.println(token); } + fail("Cannot scan: " + tokensFiles[i]); + } } + } - public void testScanner() throws IOException { - File[] files = getStreamsByExtension(".data", true); - assertTrue("No test files found.", files.length > 0); - for (File file : files) { - List<String> tokens = new ArrayList<String>(); - InputStream input = new FileInputStream(file); - StreamReader reader = new StreamReader(new UnicodeReader(input)); - Scanner scanner = new ScannerImpl(reader); - try { - while (scanner.checkToken(new Token.ID[0])) { - Token token = scanner.getToken(); - tokens.add(token.getClass().getName()); - } - } catch (RuntimeException e) { - System.out.println("File name: \n" + file.getName()); - String data = getResource(file.getName()); - System.out.println("Data: \n" + data); - System.out.println("Tokens:"); - for (String token : tokens) { - System.out.println(token); - } - fail("Cannot scan: " + file + "; " + e.getMessage()); - } finally { - input.close(); - } + public void testScanner() throws IOException { + File[] files = getStreamsByExtension(".data", true); + assertTrue("No test files found.", files.length > 0); + for (File file : files) { + List<String> tokens = new ArrayList<String>(); + InputStream input = new FileInputStream(file); + StreamReader reader = new StreamReader(new UnicodeReader(input)); + Scanner scanner = new ScannerImpl(reader); + try { + while (scanner.checkToken()) { + Token token = scanner.getToken(); + tokens.add(token.getClass().getName()); + } + } catch (RuntimeException e) { + System.out.println("File name: \n" + file.getName()); + String data = getResource(file.getName()); + System.out.println("Data: \n" + data); + System.out.println("Tokens:"); + for (String token : tokens) { + System.out.println(token); } + fail("Cannot scan: " + file + "; " + e.getMessage()); + } finally { + input.close(); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/Address.java b/src/test/java/org/yaml/snakeyaml/Address.java index 0413a174..cb8a9c00 100644 --- a/src/test/java/org/yaml/snakeyaml/Address.java +++ b/src/test/java/org/yaml/snakeyaml/Address.java @@ -1,23 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; public class Address { - public String lines; - public String city; - public String state; - public String postal; -}
\ No newline at end of file + + public String lines; + public String city; + public String state; + public String postal; +} diff --git a/src/test/java/org/yaml/snakeyaml/BinaryBean.java b/src/test/java/org/yaml/snakeyaml/BinaryBean.java index 589e800e..23fdc19d 100644 --- a/src/test/java/org/yaml/snakeyaml/BinaryBean.java +++ b/src/test/java/org/yaml/snakeyaml/BinaryBean.java @@ -1,38 +1,37 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; public class BinaryBean { - byte[] data; - int id; - public byte[] getData() { - return data; - } + byte[] data; + int id; - public void setData(byte[] data) { - this.data = data; - } + public byte[] getData() { + return data; + } - public int getId() { - return id; - } + public void setData(byte[] data) { + this.data = data; + } - public void setId(int id) { - this.id = id; - } + public int getId() { + return id; + } -}
\ No newline at end of file + public void setId(int id) { + this.id = id; + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/BinaryJavaBeanTest.java b/src/test/java/org/yaml/snakeyaml/BinaryJavaBeanTest.java index 77815fb0..7d873a03 100644 --- a/src/test/java/org/yaml/snakeyaml/BinaryJavaBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/BinaryJavaBeanTest.java @@ -1,35 +1,34 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import junit.framework.TestCase; public class BinaryJavaBeanTest extends TestCase { - public void testBeanTest() { - BinaryBean bean = new BinaryBean(); - bean.setId(1); - byte[] bytes = new byte[] { 1, 7, 9, 31, 65 }; - bean.setData(bytes); - Yaml yaml = new Yaml(); - String output = yaml.dump(bean); - String etalon = "!!org.yaml.snakeyaml.BinaryBean\ndata: !!binary |-\n AQcJH0E=\nid: 1\n"; - assertEquals(etalon, output); - // load - BinaryBean bean2 = (BinaryBean) yaml.load(output); - assertEquals(1, bean2.getId()); - assertEquals(new String(bytes), new String(bean2.getData())); - } + + public void testBeanTest() { + BinaryBean bean = new BinaryBean(); + bean.setId(1); + byte[] bytes = new byte[] {1, 7, 9, 31, 65}; + bean.setData(bytes); + Yaml yaml = new Yaml(); + String output = yaml.dump(bean); + String etalon = "!!org.yaml.snakeyaml.BinaryBean\ndata: !!binary |-\n AQcJH0E=\nid: 1\n"; + assertEquals(etalon, output); + // load + BinaryBean bean2 = yaml.load(output); + assertEquals(1, bean2.getId()); + assertEquals(new String(bytes), new String(bean2.getData())); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Chapter2_1Test.java b/src/test/java/org/yaml/snakeyaml/Chapter2_1Test.java index 6bc4d1c9..0575bb62 100644 --- a/src/test/java/org/yaml/snakeyaml/Chapter2_1Test.java +++ b/src/test/java/org/yaml/snakeyaml/Chapter2_1Test.java @@ -1,107 +1,102 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.List; import java.util.Map; - import junit.framework.TestCase; /** * Test Chapter 2.1 from the YAML specification - * - * @see <a href="http://yaml.org/spec/1.1/"></a> */ public class Chapter2_1Test extends TestCase { - @SuppressWarnings("unchecked") - public void testExample_2_1() { - YamlDocument document = new YamlDocument("example2_1.yaml"); - List<String> list = (List<String>) document.getNativeData(); - assertEquals(3, list.size()); - assertEquals("Mark McGwire", list.get(0)); - assertEquals("Sammy Sosa", list.get(1)); - assertEquals("Ken Griffey", list.get(2)); - assertEquals("[Mark McGwire, Sammy Sosa, Ken Griffey]\n", document.getPresentation()); - } + @SuppressWarnings("unchecked") + public void testExample_2_1() { + YamlDocument document = new YamlDocument("example2_1.yaml"); + List<String> list = (List<String>) document.getNativeData(); + assertEquals(3, list.size()); + assertEquals("Mark McGwire", list.get(0)); + assertEquals("Sammy Sosa", list.get(1)); + assertEquals("Ken Griffey", list.get(2)); + assertEquals("[Mark McGwire, Sammy Sosa, Ken Griffey]\n", document.getPresentation()); + } - @SuppressWarnings("unchecked") - public void testExample_2_2() { - YamlDocument document = new YamlDocument("example2_2.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(3, map.size()); - assertEquals("Expect 65 to be a Integer", Integer.class, map.get("hr").getClass()); - assertEquals(new Integer(65), map.get("hr")); - assertEquals(new Float(0.278), new Float("0.278")); - assertEquals("Expect 0.278 to be a Float", Double.class, map.get("avg").getClass()); - assertEquals(new Double(0.278), map.get("avg")); - assertEquals("Expect 147 to be an Integer", Integer.class, map.get("rbi").getClass()); - assertEquals(new Integer(147), map.get("rbi")); - } + @SuppressWarnings("unchecked") + public void testExample_2_2() { + YamlDocument document = new YamlDocument("example2_2.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(3, map.size()); + assertEquals("Expect 65 to be a Integer", Integer.class, map.get("hr").getClass()); + assertEquals(Integer.valueOf(65), map.get("hr")); + assertEquals(Float.valueOf(0.278f), Float.valueOf("0.278")); + assertEquals("Expect 0.278 to be a Float", Double.class, map.get("avg").getClass()); + assertEquals(Double.valueOf(0.278), map.get("avg")); + assertEquals("Expect 147 to be an Integer", Integer.class, map.get("rbi").getClass()); + assertEquals(Integer.valueOf(147), map.get("rbi")); + } - @SuppressWarnings("unchecked") - public void testExample_2_3() { - YamlDocument document = new YamlDocument("example2_3.yaml"); - Map<String, List<String>> map = (Map<String, List<String>>) document.getNativeData(); - assertEquals(2, map.size()); - List<String> list1 = map.get("american"); - assertEquals(3, list1.size()); - assertEquals("Boston Red Sox", list1.get(0)); - assertEquals("Detroit Tigers", list1.get(1)); - assertEquals("New York Yankees", list1.get(2)); - List<String> list2 = map.get("national"); - assertEquals(3, list2.size()); - assertEquals("New York Mets", list2.get(0)); - assertEquals("Chicago Cubs", list2.get(1)); - assertEquals("Atlanta Braves", list2.get(2)); - } + @SuppressWarnings("unchecked") + public void testExample_2_3() { + YamlDocument document = new YamlDocument("example2_3.yaml"); + Map<String, List<String>> map = (Map<String, List<String>>) document.getNativeData(); + assertEquals(2, map.size()); + List<String> list1 = map.get("american"); + assertEquals(3, list1.size()); + assertEquals("Boston Red Sox", list1.get(0)); + assertEquals("Detroit Tigers", list1.get(1)); + assertEquals("New York Yankees", list1.get(2)); + List<String> list2 = map.get("national"); + assertEquals(3, list2.size()); + assertEquals("New York Mets", list2.get(0)); + assertEquals("Chicago Cubs", list2.get(1)); + assertEquals("Atlanta Braves", list2.get(2)); + } - @SuppressWarnings("unchecked") - public void testExample_2_4() { - YamlDocument document = new YamlDocument("example2_4.yaml"); - List<Map<String, Object>> list = (List<Map<String, Object>>) document.getNativeData(); - assertEquals(2, list.size()); - Map<String, Object> map1 = list.get(0); - assertEquals(3, map1.size()); - assertEquals("Mark McGwire", map1.get("name")); - } + @SuppressWarnings("unchecked") + public void testExample_2_4() { + YamlDocument document = new YamlDocument("example2_4.yaml"); + List<Map<String, Object>> list = (List<Map<String, Object>>) document.getNativeData(); + assertEquals(2, list.size()); + Map<String, Object> map1 = list.get(0); + assertEquals(3, map1.size()); + assertEquals("Mark McGwire", map1.get("name")); + } - @SuppressWarnings("unchecked") - public void testExample_2_5() { - YamlDocument document = new YamlDocument("example2_5.yaml"); - List<List<Object>> list = (List<List<Object>>) document.getNativeData(); - assertEquals(3, list.size()); - List<Object> list1 = list.get(0); - assertEquals(3, list1.size()); - assertEquals("name", list1.get(0)); - assertEquals("hr", list1.get(1)); - assertEquals("avg", list1.get(2)); - assertEquals(3, list.get(1).size()); - assertEquals(3, list.get(2).size()); - } + @SuppressWarnings("unchecked") + public void testExample_2_5() { + YamlDocument document = new YamlDocument("example2_5.yaml"); + List<List<Object>> list = (List<List<Object>>) document.getNativeData(); + assertEquals(3, list.size()); + List<Object> list1 = list.get(0); + assertEquals(3, list1.size()); + assertEquals("name", list1.get(0)); + assertEquals("hr", list1.get(1)); + assertEquals("avg", list1.get(2)); + assertEquals(3, list.get(1).size()); + assertEquals(3, list.get(2).size()); + } - @SuppressWarnings("unchecked") - public void testExample_2_6() { - YamlDocument document = new YamlDocument("example2_6.yaml"); - Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) document - .getNativeData(); - assertEquals(2, map.size()); - Map<String, Object> map1 = map.get("Mark McGwire"); - assertEquals(2, map1.size()); - Map<String, Object> map2 = map.get("Sammy Sosa"); - assertEquals(2, map2.size()); - } + @SuppressWarnings("unchecked") + public void testExample_2_6() { + YamlDocument document = new YamlDocument("example2_6.yaml"); + Map<String, Map<String, Object>> map = + (Map<String, Map<String, Object>>) document.getNativeData(); + assertEquals(2, map.size()); + Map<String, Object> map1 = map.get("Mark McGwire"); + assertEquals(2, map1.size()); + Map<String, Object> map2 = map.get("Sammy Sosa"); + assertEquals(2, map2.size()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Chapter2_2Test.java b/src/test/java/org/yaml/snakeyaml/Chapter2_2Test.java index 88b7ec9d..3c56ca74 100644 --- a/src/test/java/org/yaml/snakeyaml/Chapter2_2Test.java +++ b/src/test/java/org/yaml/snakeyaml/Chapter2_2Test.java @@ -1,112 +1,107 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.List; import java.util.Map; - import junit.framework.TestCase; /** * Test Chapter 2.2 from the YAML specification - * - * @see <a href="http://yaml.org/spec/1.1/"></a> */ public class Chapter2_2Test extends TestCase { - @SuppressWarnings("unchecked") - public void testExample_2_7() { - YamlStream resource = new YamlStream("example2_7.yaml"); - List<Object> list = (List<Object>) resource.getNativeData(); - assertEquals(2, list.size()); - List<String> list1 = (List<String>) list.get(0); - assertEquals(3, list1.size()); - assertEquals("Mark McGwire", list1.get(0)); - assertEquals("Sammy Sosa", list1.get(1)); - assertEquals("Ken Griffey", list1.get(2)); - List<String> list2 = (List<String>) list.get(1); - assertEquals(2, list2.size()); - assertEquals("Chicago Cubs", list2.get(0)); - assertEquals("St Louis Cardinals", list2.get(1)); - } + @SuppressWarnings("unchecked") + public void testExample_2_7() { + YamlStream resource = new YamlStream("example2_7.yaml"); + List<Object> list = resource.getNativeData(); + assertEquals(2, list.size()); + List<String> list1 = (List<String>) list.get(0); + assertEquals(3, list1.size()); + assertEquals("Mark McGwire", list1.get(0)); + assertEquals("Sammy Sosa", list1.get(1)); + assertEquals("Ken Griffey", list1.get(2)); + List<String> list2 = (List<String>) list.get(1); + assertEquals(2, list2.size()); + assertEquals("Chicago Cubs", list2.get(0)); + assertEquals("St Louis Cardinals", list2.get(1)); + } - @SuppressWarnings("unchecked") - public void testExample_2_8() { - YamlStream resource = new YamlStream("example2_8.yaml"); - List<Object> list = (List<Object>) resource.getNativeData(); - assertEquals(2, list.size()); - Map<String, String> map1 = (Map<String, String>) list.get(0); - assertEquals(3, map1.size()); - assertEquals(new Integer(72200), map1.get("time")); - assertEquals("Sammy Sosa", map1.get("player")); - assertEquals("strike (miss)", map1.get("action")); - Map<String, String> map2 = (Map<String, String>) list.get(1); - assertEquals(3, map2.size()); - assertEquals(new Integer(72227), map2.get("time")); - assertEquals("Sammy Sosa", map2.get("player")); - assertEquals("grand slam", map2.get("action")); - } + @SuppressWarnings("unchecked") + public void testExample_2_8() { + YamlStream resource = new YamlStream("example2_8.yaml"); + List<Object> list = resource.getNativeData(); + assertEquals(2, list.size()); + Map<String, String> map1 = (Map<String, String>) list.get(0); + assertEquals(3, map1.size()); + assertEquals(Integer.valueOf(72200), map1.get("time")); + assertEquals("Sammy Sosa", map1.get("player")); + assertEquals("strike (miss)", map1.get("action")); + Map<String, String> map2 = (Map<String, String>) list.get(1); + assertEquals(3, map2.size()); + assertEquals(Integer.valueOf(72227), map2.get("time")); + assertEquals("Sammy Sosa", map2.get("player")); + assertEquals("grand slam", map2.get("action")); + } - @SuppressWarnings("unchecked") - public void testExample_2_9() { - YamlDocument document = new YamlDocument("example2_9.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(map.toString(), 2, map.size()); - List<String> list1 = (List<String>) map.get("hr"); - assertEquals(2, list1.size()); - assertEquals("Mark McGwire", list1.get(0)); - assertEquals("Sammy Sosa", list1.get(1)); - List<String> list2 = (List<String>) map.get("rbi"); - assertEquals(2, list2.size()); - assertEquals("Sammy Sosa", list2.get(0)); - assertEquals("Ken Griffey", list2.get(1)); - } + @SuppressWarnings("unchecked") + public void testExample_2_9() { + YamlDocument document = new YamlDocument("example2_9.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(map.toString(), 2, map.size()); + List<String> list1 = (List<String>) map.get("hr"); + assertEquals(2, list1.size()); + assertEquals("Mark McGwire", list1.get(0)); + assertEquals("Sammy Sosa", list1.get(1)); + List<String> list2 = (List<String>) map.get("rbi"); + assertEquals(2, list2.size()); + assertEquals("Sammy Sosa", list2.get(0)); + assertEquals("Ken Griffey", list2.get(1)); + } - @SuppressWarnings("unchecked") - public void testExample_2_10() { - YamlDocument document = new YamlDocument("example2_10.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals("Examples 2.9 and 2.10 must be identical.", - new YamlDocument("example2_9.yaml").getNativeData(), map); - } + @SuppressWarnings("unchecked") + public void testExample_2_10() { + YamlDocument document = new YamlDocument("example2_10.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals("Examples 2.9 and 2.10 must be identical.", + new YamlDocument("example2_9.yaml").getNativeData(), map); + } - @SuppressWarnings("unchecked") - public void testExample_2_11() { - YamlDocument document = new YamlDocument("example2_11.yaml"); - Map<Object, Object> map = (Map<Object, Object>) document.getNativeData(); - assertEquals(2, map.size()); - for (Object key : map.keySet()) { - List<String> list = (List<String>) key; - assertEquals(2, list.size()); - } + @SuppressWarnings("unchecked") + public void testExample_2_11() { + YamlDocument document = new YamlDocument("example2_11.yaml"); + Map<Object, Object> map = (Map<Object, Object>) document.getNativeData(); + assertEquals(2, map.size()); + for (Object key : map.keySet()) { + List<String> list = (List<String>) key; + assertEquals(2, list.size()); } + } - public void testExample_2_12() { - YamlDocument document = new YamlDocument("example2_12.yaml"); - @SuppressWarnings("unchecked") - List<Map<Object, Object>> list = (List<Map<Object, Object>>) document.getNativeData(); - assertEquals(3, list.size()); - Map<Object, Object> map1 = (Map<Object, Object>) list.get(0); - assertEquals(2, map1.size()); - assertEquals("Super Hoop", map1.get("item")); - Map<Object, Object> map2 = (Map<Object, Object>) list.get(1); - assertEquals(2, map2.size()); - assertEquals("Basketball", map2.get("item")); - Map<Object, Object> map3 = (Map<Object, Object>) list.get(2); - assertEquals(2, map3.size()); - assertEquals("Big Shoes", map3.get("item")); - } + public void testExample_2_12() { + YamlDocument document = new YamlDocument("example2_12.yaml"); + @SuppressWarnings("unchecked") + List<Map<Object, Object>> list = (List<Map<Object, Object>>) document.getNativeData(); + assertEquals(3, list.size()); + Map<Object, Object> map1 = list.get(0); + assertEquals(2, map1.size()); + assertEquals("Super Hoop", map1.get("item")); + Map<Object, Object> map2 = list.get(1); + assertEquals(2, map2.size()); + assertEquals("Basketball", map2.get("item")); + Map<Object, Object> map3 = list.get(2); + assertEquals(2, map3.size()); + assertEquals("Big Shoes", map3.get("item")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Chapter2_3Test.java b/src/test/java/org/yaml/snakeyaml/Chapter2_3Test.java index b4e671d3..5ea2e09c 100644 --- a/src/test/java/org/yaml/snakeyaml/Chapter2_3Test.java +++ b/src/test/java/org/yaml/snakeyaml/Chapter2_3Test.java @@ -1,134 +1,128 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.io.InputStream; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions.ScalarStyle; /** * Test Chapter 2.3 from the YAML specification - * - * @see <a href="http://yaml.org/spec/1.1/"></a> */ public class Chapter2_3Test extends TestCase { - public void testExample_2_13() { - YamlDocument document = new YamlDocument("example2_13.yaml"); - String data = (String) document.getNativeData(); - assertEquals("\\//||\\/||\n// || ||__\n", data); - } - - public void testExample_2_14() { - YamlDocument document = new YamlDocument("example2_14.yaml"); - String data = (String) document.getNativeData(); - assertEquals("Mark McGwire's year was crippled by a knee injury.", data); - } - - public void testExample_2_15() { - String etalon = "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n"; - InputStream input = YamlDocument.class.getClassLoader().getResourceAsStream( - YamlDocument.ROOT + "example2_15.yaml"); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.FOLDED); - Yaml yaml = new Yaml(options); - String data = (String) yaml.load(input); - assertEquals(etalon, data); - // - String dumped = yaml.dump(data); - String etalonDumped = Util.getLocalResource("specification/example2_15_dumped.yaml"); - assertEquals(etalonDumped, dumped); - } - - @SuppressWarnings("unchecked") - public void testExample_2_16() { - YamlDocument document = new YamlDocument("example2_16.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals(map.toString(), 3, map.size()); - assertEquals("Mark McGwire", map.get("name")); - assertEquals("Mark set a major league home run record in 1998.\n", - map.get("accomplishment")); - assertEquals("65 Home Runs\n0.278 Batting Average\n", map.get("stats")); - - } - - @SuppressWarnings("unchecked") - public void testExample_2_17() { - YamlDocument document = new YamlDocument("example2_17.yaml", false); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals(map.toString(), 6, map.size()); - assertEquals("Sosa did fine.\u263A", map.get("unicode")); - assertEquals("\b1998\t1999\t2000\n", map.get("control")); - assertEquals("\r\n is \r\n", map.get("hexesc")); - assertEquals("\"Howdy!\" he cried.", map.get("single")); - assertEquals(" # not a 'comment'.", map.get("quoted")); - assertEquals("|\\-*-/|", map.get("tie-fighter")); - } - - @SuppressWarnings("unchecked") - public void testExample_2_17_unicode() { - YamlDocument document = new YamlDocument("example2_17_unicode.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals("Sosa did fine.\u263A", map.get("unicode")); - } - - @SuppressWarnings("unchecked") - public void testExample_2_17_control() { - YamlDocument document = new YamlDocument("example2_17_control.yaml", false); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals("\b1998\t1999\t2000\n", map.get("control")); - } - - @SuppressWarnings("unchecked") - public void testExample_2_17_hexesc() { - YamlDocument document = new YamlDocument("example2_17_hexesc.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals("\r\n is \r\n", map.get("hexesc")); - } - - @SuppressWarnings("unchecked") - public void testExample_2_17_single() { - YamlDocument document = new YamlDocument("example2_17_single.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals("\"Howdy!\" he cried.", map.get("single")); - } - - @SuppressWarnings("unchecked") - public void testExample_2_17_quoted() { - YamlDocument document = new YamlDocument("example2_17_quoted.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals(" # not a 'comment'.", map.get("quoted")); - } - - @SuppressWarnings("unchecked") - public void testExample_2_17_tie_fighter() { - YamlDocument document = new YamlDocument("example2_17_tie_fighter.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals("|\\-*-/|", map.get("tie-fighter")); - } - - @SuppressWarnings("unchecked") - public void testExample_2_18() { - YamlDocument document = new YamlDocument("example2_18.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals(map.toString(), 2, map.size()); - assertEquals("This unquoted scalar spans many lines.", map.get("plain")); - assertEquals("So does this quoted scalar.\n", map.get("quoted")); - } + public void testExample_2_13() { + YamlDocument document = new YamlDocument("example2_13.yaml"); + String data = (String) document.getNativeData(); + assertEquals("\\//||\\/||\n// || ||__\n", data); + } + + public void testExample_2_14() { + YamlDocument document = new YamlDocument("example2_14.yaml"); + String data = (String) document.getNativeData(); + assertEquals("Mark McGwire's year was crippled by a knee injury.", data); + } + + public void testExample_2_15() { + String etalon = + "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n"; + InputStream input = YamlDocument.class.getClassLoader() + .getResourceAsStream(YamlDocument.ROOT + "example2_15.yaml"); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.FOLDED); + Yaml yaml = new Yaml(options); + String data = yaml.load(input); + assertEquals(etalon, data); + // + String dumped = yaml.dump(data); + String etalonDumped = Util.getLocalResource("specification/example2_15_dumped.yaml"); + assertEquals(etalonDumped, dumped); + } + + @SuppressWarnings("unchecked") + public void testExample_2_16() { + YamlDocument document = new YamlDocument("example2_16.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals(map.toString(), 3, map.size()); + assertEquals("Mark McGwire", map.get("name")); + assertEquals("Mark set a major league home run record in 1998.\n", map.get("accomplishment")); + assertEquals("65 Home Runs\n0.278 Batting Average\n", map.get("stats")); + + } + + @SuppressWarnings("unchecked") + public void testExample_2_17() { + YamlDocument document = new YamlDocument("example2_17.yaml", false); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals(map.toString(), 6, map.size()); + assertEquals("Sosa did fine.\u263A", map.get("unicode")); + assertEquals("\b1998\t1999\t2000\n", map.get("control")); + assertEquals("\r\n is \r\n", map.get("hexesc")); + assertEquals("\"Howdy!\" he cried.", map.get("single")); + assertEquals(" # not a 'comment'.", map.get("quoted")); + assertEquals("|\\-*-/|", map.get("tie-fighter")); + } + + @SuppressWarnings("unchecked") + public void testExample_2_17_unicode() { + YamlDocument document = new YamlDocument("example2_17_unicode.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals("Sosa did fine.\u263A", map.get("unicode")); + } + + @SuppressWarnings("unchecked") + public void testExample_2_17_control() { + YamlDocument document = new YamlDocument("example2_17_control.yaml", false); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals("\b1998\t1999\t2000\n", map.get("control")); + } + + @SuppressWarnings("unchecked") + public void testExample_2_17_hexesc() { + YamlDocument document = new YamlDocument("example2_17_hexesc.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals("\r\n is \r\n", map.get("hexesc")); + } + + @SuppressWarnings("unchecked") + public void testExample_2_17_single() { + YamlDocument document = new YamlDocument("example2_17_single.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals("\"Howdy!\" he cried.", map.get("single")); + } + + @SuppressWarnings("unchecked") + public void testExample_2_17_quoted() { + YamlDocument document = new YamlDocument("example2_17_quoted.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals(" # not a 'comment'.", map.get("quoted")); + } + + @SuppressWarnings("unchecked") + public void testExample_2_17_tie_fighter() { + YamlDocument document = new YamlDocument("example2_17_tie_fighter.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals("|\\-*-/|", map.get("tie-fighter")); + } + + @SuppressWarnings("unchecked") + public void testExample_2_18() { + YamlDocument document = new YamlDocument("example2_18.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals(map.toString(), 2, map.size()); + assertEquals("This unquoted scalar spans many lines.", map.get("plain")); + assertEquals("So does this quoted scalar.\n", map.get("quoted")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Chapter2_4Test.java b/src/test/java/org/yaml/snakeyaml/Chapter2_4Test.java index 3d36caa8..61540c5a 100644 --- a/src/test/java/org/yaml/snakeyaml/Chapter2_4Test.java +++ b/src/test/java/org/yaml/snakeyaml/Chapter2_4Test.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -23,9 +21,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; - import junit.framework.TestCase; - import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.Node; @@ -34,149 +30,147 @@ import org.yaml.snakeyaml.nodes.Tag; /** * Test Chapter 2.4 from the YAML specification - * - * @see <a href="http://yaml.org/spec/1.1/"></a> */ public class Chapter2_4Test extends TestCase { - @SuppressWarnings("unchecked") - public void testExample_2_19() { - YamlDocument document = new YamlDocument("example2_19.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(5, map.size()); - assertEquals("Expect 12345 to be an Integer.", Integer.class, map.get("canonical") - .getClass()); - assertEquals(new Integer(12345), map.get("canonical")); - assertEquals(new Integer(12345), map.get("decimal")); - assertEquals(new Integer(3 * 3600 + 25 * 60 + 45), map.get("sexagesimal")); - assertEquals(new Integer(014), map.get("octal")); - assertEquals(new Integer(0xC), map.get("hexadecimal")); - } + @SuppressWarnings("unchecked") + public void testExample_2_19() { + YamlDocument document = new YamlDocument("example2_19.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(5, map.size()); + assertEquals("Expect 12345 to be an Integer.", Integer.class, map.get("canonical").getClass()); + assertEquals(Integer.valueOf(12345), map.get("canonical")); + assertEquals(Integer.valueOf(12345), map.get("decimal")); + assertEquals(Integer.valueOf(3 * 3600 + 25 * 60 + 45), map.get("sexagesimal")); + assertEquals(Integer.valueOf(014), map.get("octal")); + assertEquals(Integer.valueOf(0xC), map.get("hexadecimal")); + } - @SuppressWarnings("unchecked") - public void testExample_2_20() { - YamlDocument document = new YamlDocument("example2_20.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(6, map.size()); - assertEquals("Expect '1.23015e+3' to be a Double.", Double.class, map.get("canonical") - .getClass()); - assertEquals(new Double(1230.15), map.get("canonical")); - assertEquals(new Double(12.3015e+02), map.get("exponential")); - assertEquals(new Double(20 * 60 + 30.15), map.get("sexagesimal")); - assertEquals(new Double(1230.15), map.get("fixed")); - assertEquals(Double.NEGATIVE_INFINITY, map.get("negative infinity")); - assertEquals(Double.NaN, map.get("not a number")); - } + @SuppressWarnings("unchecked") + public void testExample_2_20() { + YamlDocument document = new YamlDocument("example2_20.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(6, map.size()); + assertEquals("Expect '1.23015e+3' to be a Double.", Double.class, + map.get("canonical").getClass()); + assertEquals(Double.valueOf(1230.15), map.get("canonical")); + assertEquals(Double.valueOf(12.3015e+02), map.get("exponential")); + assertEquals(Double.valueOf(20 * 60 + 30.15), map.get("sexagesimal")); + assertEquals(Double.valueOf(1230.15), map.get("fixed")); + assertEquals(Double.NEGATIVE_INFINITY, map.get("negative infinity")); + assertEquals(Double.NaN, map.get("not a number")); + } - @SuppressWarnings("unchecked") - public void testExample_2_21() { - YamlDocument document = new YamlDocument("example2_21.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(4, map.size()); - assertNull("'~' must be parsed as 'null': " + map.get(null), map.get(null)); - assertTrue((Boolean) map.get(Boolean.TRUE)); - assertFalse((Boolean) map.get(Boolean.FALSE)); - assertEquals("12345", map.get("string")); - } + @SuppressWarnings("unchecked") + public void testExample_2_21() { + YamlDocument document = new YamlDocument("example2_21.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(4, map.size()); + assertNull("'~' must be parsed as 'null': " + map.get(null), map.get(null)); + assertTrue((Boolean) map.get(Boolean.TRUE)); + assertFalse((Boolean) map.get(Boolean.FALSE)); + assertEquals("12345", map.get("string")); + } - @SuppressWarnings("unchecked") - public void testExample_2_22() { - YamlDocument document = new YamlDocument("example2_22.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(4, map.size()); - assertEquals("Expect '2001-12-15T02:59:43.1Z' to be a Date.", Date.class, - map.get("canonical").getClass()); - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - cal.clear(); - cal.set(Calendar.YEAR, 2001); - cal.set(Calendar.MONTH, 11); // Java's months are zero-based... - cal.set(Calendar.DAY_OF_MONTH, 15); - cal.set(Calendar.HOUR_OF_DAY, 2); - cal.set(Calendar.MINUTE, 59); - cal.set(Calendar.SECOND, 43); - cal.set(Calendar.MILLISECOND, 100); - Date date = cal.getTime(); - assertEquals(date, map.get("canonical")); - assertEquals("Expect '2001-12-14t21:59:43.10-05:00' to be a Date.", Date.class, - map.get("iso8601").getClass()); - assertEquals("Expect '2001-12-14 21:59:43.10 -5' to be a Date.", Date.class, - map.get("spaced").getClass()); - assertEquals("Expect '2002-12-14' to be a Date.", Date.class, map.get("date").getClass()); - } + @SuppressWarnings("unchecked") + public void testExample_2_22() { + YamlDocument document = new YamlDocument("example2_22.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(4, map.size()); + assertEquals("Expect '2001-12-15T02:59:43.1Z' to be a Date.", Date.class, + map.get("canonical").getClass()); + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + cal.clear(); + cal.set(Calendar.YEAR, 2001); + cal.set(Calendar.MONTH, 11); // Java's months are zero-based... + cal.set(Calendar.DAY_OF_MONTH, 15); + cal.set(Calendar.HOUR_OF_DAY, 2); + cal.set(Calendar.MINUTE, 59); + cal.set(Calendar.SECOND, 43); + cal.set(Calendar.MILLISECOND, 100); + Date date = cal.getTime(); + assertEquals(date, map.get("canonical")); + assertEquals("Expect '2001-12-14t21:59:43.10-05:00' to be a Date.", Date.class, + map.get("iso8601").getClass()); + assertEquals("Expect '2001-12-14 21:59:43.10 -5' to be a Date.", Date.class, + map.get("spaced").getClass()); + assertEquals("Expect '2002-12-14' to be a Date.", Date.class, map.get("date").getClass()); + } - @SuppressWarnings("unchecked") - public void testExample_2_23_non_date() { - try { - YamlDocument document = new YamlDocument("example2_23_non_date.yaml"); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(1, map.size()); - assertEquals("2002-04-28", map.get("not-date")); - } catch (RuntimeException e) { - fail("Cannot parse '!!str': 'not-date: !!str 2002-04-28'"); - } + @SuppressWarnings("unchecked") + public void testExample_2_23_non_date() { + try { + YamlDocument document = new YamlDocument("example2_23_non_date.yaml"); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(1, map.size()); + assertEquals("2002-04-28", map.get("not-date")); + } catch (RuntimeException e) { + fail("Cannot parse '!!str': 'not-date: !!str 2002-04-28'"); } + } - @SuppressWarnings("unchecked") - public void testExample_2_23_picture() { - YamlDocument document = new YamlDocument("example2_23_picture.yaml", false); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(1, map.size()); - byte[] picture = (byte[]) map.get("picture"); - assertEquals((byte) 'G', picture[0]); - assertEquals((byte) 'I', picture[1]); - assertEquals((byte) 'F', picture[2]); - } + @SuppressWarnings("unchecked") + public void testExample_2_23_picture() { + YamlDocument document = new YamlDocument("example2_23_picture.yaml", false); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(1, map.size()); + byte[] picture = (byte[]) map.get("picture"); + assertEquals((byte) 'G', picture[0]); + assertEquals((byte) 'I', picture[1]); + assertEquals((byte) 'F', picture[2]); + } - class SomethingConstructor extends Constructor { - public SomethingConstructor() { - this.yamlConstructors.put(new Tag("!something"), new ConstructSomething()); - } + class SomethingConstructor extends Constructor { - private class ConstructSomething extends AbstractConstruct { - public Object construct(Node node) { - // convert to upper case - String val = (String) constructScalar((ScalarNode) node); - return val.toUpperCase().replace('\n', ' ').trim(); - } - } + public SomethingConstructor() { + this.yamlConstructors.put(new Tag("!something"), new ConstructSomething()); } - @SuppressWarnings("unchecked") - public void testExample_2_23() { - YamlDocument document = new YamlDocument("example2_23.yaml", false, - new SomethingConstructor()); - Map<String, Object> map = (Map<String, Object>) document.getNativeData(); - assertEquals(3, map.size()); - String special = (String) map.get("application specific tag"); - assertEquals("THE SEMANTICS OF THE TAG ABOVE MAY BE DIFFERENT FOR DIFFERENT DOCUMENTS.", - special); - } + private class ConstructSomething extends AbstractConstruct { - @SuppressWarnings("unchecked") - public void testExample_2_25() { - YamlDocument document = new YamlDocument("example2_25.yaml"); - Set<String> set = (Set<String>) document.getNativeData(); - assertEquals(3, set.size()); - assertTrue(set.contains("Mark McGwire")); - assertTrue(set.contains("Sammy Sosa")); - assertTrue(set.contains("Ken Griff")); + public Object construct(Node node) { + // convert to upper case + String val = constructScalar((ScalarNode) node); + return val.toUpperCase().replace('\n', ' ').trim(); + } } + } + + @SuppressWarnings("unchecked") + public void testExample_2_23() { + YamlDocument document = new YamlDocument("example2_23.yaml", false, new SomethingConstructor()); + Map<String, Object> map = (Map<String, Object>) document.getNativeData(); + assertEquals(3, map.size()); + String special = (String) map.get("application specific tag"); + assertEquals("THE SEMANTICS OF THE TAG ABOVE MAY BE DIFFERENT FOR DIFFERENT DOCUMENTS.", + special); + } + + @SuppressWarnings("unchecked") + public void testExample_2_25() { + YamlDocument document = new YamlDocument("example2_25.yaml"); + Set<String> set = (Set<String>) document.getNativeData(); + assertEquals(3, set.size()); + assertTrue(set.contains("Mark McGwire")); + assertTrue(set.contains("Sammy Sosa")); + assertTrue(set.contains("Ken Griff")); + } - @SuppressWarnings("unchecked") - public void testExample_2_26() { - YamlDocument document = new YamlDocument("example2_26.yaml"); - Map<String, String> map = (Map<String, String>) document.getNativeData(); - assertEquals(3, map.size()); - assertTrue(map instanceof LinkedHashMap); - assertEquals(new Integer(65), map.get("Mark McGwire")); - assertEquals(new Integer(63), map.get("Sammy Sosa")); - assertEquals(new Integer(58), map.get("Ken Griffy")); - List<String> list = new ArrayList<String>(); - for (String key : map.keySet()) { - list.add(key); - } - assertEquals("Mark McGwire", list.get(0)); - assertEquals("Sammy Sosa", list.get(1)); - assertEquals("Ken Griffy", list.get(2)); + @SuppressWarnings("unchecked") + public void testExample_2_26() { + YamlDocument document = new YamlDocument("example2_26.yaml"); + Map<String, String> map = (Map<String, String>) document.getNativeData(); + assertEquals(3, map.size()); + assertTrue(map instanceof LinkedHashMap); + assertEquals(Integer.valueOf(65), map.get("Mark McGwire")); + assertEquals(Integer.valueOf(63), map.get("Sammy Sosa")); + assertEquals(Integer.valueOf(58), map.get("Ken Griffy")); + List<String> list = new ArrayList<String>(); + for (String key : map.keySet()) { + list.add(key); } + assertEquals("Mark McGwire", list.get(0)); + assertEquals("Sammy Sosa", list.get(1)); + assertEquals("Ken Griffy", list.get(2)); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Chapter2_5Test.java b/src/test/java/org/yaml/snakeyaml/Chapter2_5Test.java index bfe55517..fb4951bb 100644 --- a/src/test/java/org/yaml/snakeyaml/Chapter2_5Test.java +++ b/src/test/java/org/yaml/snakeyaml/Chapter2_5Test.java @@ -1,63 +1,58 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.Date; import java.util.List; import java.util.Map; - import junit.framework.TestCase; /** * Test Chapter 2.5 from the YAML specification - * - * @see <a href="http://yaml.org/spec/1.1/"></a> */ public class Chapter2_5Test extends TestCase { - @SuppressWarnings("unchecked") - public void testExample_2_28() { - YamlStream resource = new YamlStream("example2_28.yaml"); - List<Object> list = (List<Object>) resource.getNativeData(); - assertEquals(3, list.size()); - Map<String, Object> data0 = (Map<String, Object>) list.get(0); - Date date = (Date) data0.get("Time"); - assertEquals("Date: " + date, 1006545702000L, date.getTime()); - assertEquals("ed", data0.get("User")); - assertEquals("This is an error message for the log file", data0.get("Warning")); - // - Map<String, Object> data1 = (Map<String, Object>) list.get(1); - Date date1 = (Date) data1.get("Time"); - assertTrue("Date: " + date1, date1.after(date)); - assertEquals("ed", data1.get("User")); - assertEquals("A slightly different error message.", data1.get("Warning")); - // - Map<String, Object> data3 = (Map<String, Object>) list.get(2); - Date date3 = (Date) data3.get("Date"); - assertTrue("Date: " + date3, date3.after(date1)); - assertEquals("ed", data3.get("User")); - assertEquals("Unknown variable \"bar\"", data3.get("Fatal")); - List<Map<String, String>> list3 = (List<Map<String, String>>) data3.get("Stack"); - Map<String, String> map1 = list3.get(0); - assertEquals("TopClass.py", map1.get("file")); - assertEquals(new Integer(23), map1.get("line")); - assertEquals("x = MoreObject(\"345\\n\")\n", map1.get("code")); - Map<String, String> map2 = list3.get(1); - assertEquals("MoreClass.py", map2.get("file")); - assertEquals(new Integer(58), map2.get("line")); - assertEquals("foo = bar", map2.get("code")); - } + @SuppressWarnings("unchecked") + public void testExample_2_28() { + YamlStream resource = new YamlStream("example2_28.yaml"); + List<Object> list = resource.getNativeData(); + assertEquals(3, list.size()); + Map<String, Object> data0 = (Map<String, Object>) list.get(0); + Date date = (Date) data0.get("Time"); + assertEquals("Date: " + date, 1006545702000L, date.getTime()); + assertEquals("ed", data0.get("User")); + assertEquals("This is an error message for the log file", data0.get("Warning")); + // + Map<String, Object> data1 = (Map<String, Object>) list.get(1); + Date date1 = (Date) data1.get("Time"); + assertTrue("Date: " + date1, date1.after(date)); + assertEquals("ed", data1.get("User")); + assertEquals("A slightly different error message.", data1.get("Warning")); + // + Map<String, Object> data3 = (Map<String, Object>) list.get(2); + Date date3 = (Date) data3.get("Date"); + assertTrue("Date: " + date3, date3.after(date1)); + assertEquals("ed", data3.get("User")); + assertEquals("Unknown variable \"bar\"", data3.get("Fatal")); + List<Map<String, String>> list3 = (List<Map<String, String>>) data3.get("Stack"); + Map<String, String> map1 = list3.get(0); + assertEquals("TopClass.py", map1.get("file")); + assertEquals(Integer.valueOf(23), map1.get("line")); + assertEquals("x = MoreObject(\"345\\n\")\n", map1.get("code")); + Map<String, String> map2 = list3.get(1); + assertEquals("MoreClass.py", map2.get("file")); + assertEquals(Integer.valueOf(58), map2.get("line")); + assertEquals("foo = bar", map2.get("code")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/CollectionWithBeanYamlTest.java b/src/test/java/org/yaml/snakeyaml/CollectionWithBeanYamlTest.java index 7b30d7b6..e2b73435 100644 --- a/src/test/java/org/yaml/snakeyaml/CollectionWithBeanYamlTest.java +++ b/src/test/java/org/yaml/snakeyaml/CollectionWithBeanYamlTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -19,67 +17,67 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; public class CollectionWithBeanYamlTest extends TestCase { - @SuppressWarnings("unchecked") - public void testYamlMap() { - Map<String, Bean> data = new TreeMap<String, Bean>(); - data.put("gold1", new Bean()); - data.put("gold2", new Bean()); + @SuppressWarnings("unchecked") + public void testYamlMap() { + Map<String, Bean> data = new TreeMap<String, Bean>(); + data.put("gold1", new Bean()); + data.put("gold2", new Bean()); - Yaml yaml = new Yaml(); - String output = yaml.dump(data); - assertEquals( - "gold1: !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: ''}\ngold2: !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: ''}\n", - output); - Object o = yaml.load(output); + Yaml yaml = new Yaml(); + String output = yaml.dump(data); + assertEquals( + "gold1: !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: ''}\ngold2: !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: ''}\n", + output); + Object o = yaml.load(output); - assertTrue(o instanceof Map); - Map<String, Bean> m = (Map<String, Bean>) o; - assertTrue(m.get("gold1") instanceof Bean); - assertTrue("" + m.get("gold2").getClass(), m.get("gold2") instanceof Bean); - } + assertTrue(o instanceof Map); + Map<String, Bean> m = (Map<String, Bean>) o; + assertTrue(m.get("gold1") instanceof Bean); + assertTrue("" + m.get("gold2").getClass(), m.get("gold2") instanceof Bean); + } - @SuppressWarnings("unchecked") - public void testYamlList() { - List<Bean> data = new ArrayList<Bean>(); - data.add(new Bean("1")); - data.add(new Bean("2")); + @SuppressWarnings("unchecked") + public void testYamlList() { + List<Bean> data = new ArrayList<Bean>(); + data.add(new Bean("1")); + data.add(new Bean("2")); - Yaml yaml = new Yaml(); - String output = yaml.dump(data); - assertEquals( - "- !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: '1'}\n- !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: '2'}\n", - output); - Object o = yaml.load(output); + Yaml yaml = new Yaml(); + String output = yaml.dump(data); + assertEquals( + "- !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: '1'}\n- !!org.yaml.snakeyaml.CollectionWithBeanYamlTest$Bean {a: '2'}\n", + output); + Object o = yaml.load(output); - assertTrue(o instanceof List); - List<Bean> m = (List<Bean>) o; - assertEquals(2, m.size()); - assertTrue(m.get(0) instanceof Bean); - assertTrue(m.get(1) instanceof Bean); - } + assertTrue(o instanceof List); + List<Bean> m = (List<Bean>) o; + assertEquals(2, m.size()); + assertTrue(m.get(0) instanceof Bean); + assertTrue(m.get(1) instanceof Bean); + } - public static class Bean { - private String a; + public static class Bean { - public Bean() { - a = ""; - } + private String a; - public Bean(String value) { - a = value; - } + public Bean() { + a = ""; + } - public String getA() { - return a; - } + public Bean(String value) { + a = value; + } + + public String getA() { + return a; + } - public void setA(String s) { - a = s; - } + public void setA(String s) { + a = s; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/DumperOptionsTest.java b/src/test/java/org/yaml/snakeyaml/DumperOptionsTest.java index f36fb7ba..a4dab06d 100644 --- a/src/test/java/org/yaml/snakeyaml/DumperOptionsTest.java +++ b/src/test/java/org/yaml/snakeyaml/DumperOptionsTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -19,9 +17,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.emitter.Emitter; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.nodes.Tag; @@ -29,445 +25,508 @@ import org.yaml.snakeyaml.representer.Representer; public class DumperOptionsTest extends TestCase { - public void testDefaultStyle() { - DumperOptions options = new DumperOptions(); - Yaml yaml = new Yaml(options); - assertEquals("abc\n", yaml.dump("abc")); - // string which looks like integer - assertEquals("'123'\n", yaml.dump("123")); - // - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - yaml = new Yaml(options); - assertEquals("\"123\"\n", yaml.dump("123")); - // - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); - yaml = new Yaml(options); - assertEquals("'123'\n", yaml.dump("123")); - // - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); - yaml = new Yaml(options); - assertEquals("'123'\n", yaml.dump("123")); - assertEquals("abc\n", yaml.dump("abc")); - // null check - try { - options.setDefaultScalarStyle(null); - fail("Null must not be accepted."); - } catch (NullPointerException e) { - assertEquals("Use ScalarStyle enum.", e.getMessage()); - } - } - - public void testDefaultFlowStyle() { - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - list.add(3); - assertEquals("[1, 2, 3]\n", yaml.dump(list)); - // - DumperOptions options = new DumperOptions(); - options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - yaml = new Yaml(options); - assertEquals("[1, 2, 3]\n", yaml.dump(list)); - // - options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - options.setPrettyFlow(true); - yaml = new Yaml(options); - assertEquals("[\n 1,\n 2,\n 3]\n", yaml.dump(list)); - // - options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - yaml = new Yaml(options); - assertEquals("- 1\n- 2\n- 3\n", yaml.dump(list)); - // null check - try { - options.setDefaultFlowStyle(null); - fail("Null must not be accepted."); - } catch (NullPointerException e) { - assertEquals("Use FlowStyle enum.", e.getMessage()); - } - } - - public void testDefaultFlowStyleNested() { - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - list.add(3); - Map<String, Object> map = new LinkedHashMap<String, Object>(); - map.put("a", "b"); - map.put("c", list); - String result = yaml.dump(map); - assertEquals("a: b\nc: [1, 2, 3]\n", result); - // - DumperOptions options = new DumperOptions(); - options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - yaml = new Yaml(options); - assertEquals("{a: b, c: [1, 2, 3]}\n", yaml.dump(map)); - // - options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - options.setPrettyFlow(true); - yaml = new Yaml(options); - result = yaml.dump(map); - assertEquals("{\n a: b,\n c: [\n 1,\n 2,\n 3]\n \n}\n", result); - // - options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - yaml = new Yaml(options); - assertEquals("a: b\nc:\n- 1\n- 2\n- 3\n", yaml.dump(map)); - } - - public void testCanonical() { - Yaml yaml = new Yaml(); - assertEquals("123\n", yaml.dump(123)); - // - DumperOptions options = new DumperOptions(); - options = new DumperOptions(); - options.setCanonical(true); - yaml = new Yaml(options); - assertEquals("---\n!!int \"123\"\n", yaml.dump(123)); - // - options = new DumperOptions(); - options.setCanonical(false); - yaml = new Yaml(options); - assertEquals("123\n", yaml.dump(123)); - } - - public void testIndent() { - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - DumperOptions options = new DumperOptions(); - options.setCanonical(true); - yaml = new Yaml(options); - assertEquals("---\n!!seq [\n !!int \"1\",\n !!int \"2\",\n]\n", yaml.dump(list)); - // - options.setIndent(4); - yaml = new Yaml(options); - assertEquals("---\n!!seq [\n !!int \"1\",\n !!int \"2\",\n]\n", yaml.dump(list)); - // - try { - options.setIndent(0); - fail(); - } catch (YAMLException e) { - assertTrue(true); - } - try { - options.setIndent(-2); - fail(); - } catch (YAMLException e) { - assertTrue(true); - } - try { - options.setIndent(11); - fail(); - } catch (YAMLException e) { - assertTrue(true); - } - // - assertTrue(Emitter.MIN_INDENT > 0); - assertTrue(Emitter.MIN_INDENT < Emitter.MAX_INDENT); - assertTrue(Emitter.MAX_INDENT < 20); - } - - public void testLineBreak() { - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - DumperOptions options = new DumperOptions(); - options.setCanonical(true); - yaml = new Yaml(options); - assertEquals("---\n!!seq [\n !!int \"1\",\n !!int \"2\",\n]\n", yaml.dump(list)); - // - options.setLineBreak(DumperOptions.LineBreak.WIN); - yaml = new Yaml(options); - String output = yaml.dump(list); - assertEquals("---\r\n!!seq [\r\n !!int \"1\",\r\n !!int \"2\",\r\n]\r\n", output); - // null check - try { - options.setLineBreak(null); - fail("Null must not be accepted."); - } catch (NullPointerException e) { - assertEquals("Specify line break.", e.getMessage()); - } - } - - public void testLineBreakForPlatform() { - DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); - assertEquals("Line break must match platform's default.", - System.getProperty("line.separator"), lineBreak.getString()); - // - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - DumperOptions options = new DumperOptions(); - options.setLineBreak(DumperOptions.LineBreak.getPlatformLineBreak()); - yaml = new Yaml(options); - assertEquals("[1, 2]", yaml.dump(list).trim()); - } - - public void testLineBreakForPlatformUnix() { - System.setProperty("line.separator", "\n"); - assertEquals("\n", System.getProperty("line.separator")); - DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); - assertEquals("Line break must match platform's default.", - System.getProperty("line.separator"), lineBreak.getString()); - assertEquals("Unknown Line break must match UNIX line break.", "\n", lineBreak.getString()); - } - - public void testLineBreakForPlatformMac() { - System.setProperty("line.separator", "\r"); - assertEquals("\r", System.getProperty("line.separator")); - DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); - assertEquals("Line break must match platform's default.", - System.getProperty("line.separator"), lineBreak.getString()); - assertEquals("Unknown Line break must match UNIX line break.", "\r", lineBreak.getString()); - } - - public void testLineBreakForPlatformWin() { - System.setProperty("line.separator", "\r\n"); - assertEquals("\r\n", System.getProperty("line.separator")); - DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); - assertEquals("Line break must match platform's default.", - System.getProperty("line.separator"), lineBreak.getString()); - assertEquals("Unknown Line break must match UNIX line break.", "\r\n", - lineBreak.getString()); - } - - public void testLineBreakForPlatformUnknown() { - System.setProperty("line.separator", "\n\r"); - assertEquals("\n\r", System.getProperty("line.separator")); - DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); - assertEquals("Unknown Line break must match UNIX line break.", "\n", lineBreak.getString()); + public void testDefaultStyle() { + DumperOptions options = new DumperOptions(); + Yaml yaml = new Yaml(options); + assertEquals("abc\n", yaml.dump("abc")); + // string which looks like integer + assertEquals("'123'\n", yaml.dump("123")); + // + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + yaml = new Yaml(options); + assertEquals("\"123\"\n", yaml.dump("123")); + // + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); + yaml = new Yaml(options); + assertEquals("'123'\n", yaml.dump("123")); + // + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); + yaml = new Yaml(options); + assertEquals("'123'\n", yaml.dump("123")); + assertEquals("abc\n", yaml.dump("abc")); + // null check + try { + options.setDefaultScalarStyle(null); + fail("Null must not be accepted."); + } catch (NullPointerException e) { + assertEquals("Use ScalarStyle enum.", e.getMessage()); } - - public void testExplicitStart() { - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - list.add(3); - assertEquals("[1, 2, 3]\n", yaml.dump(list)); - // - DumperOptions options = new DumperOptions(); - options = new DumperOptions(); - options.setExplicitStart(true); - yaml = new Yaml(options); - assertEquals("--- [1, 2, 3]\n", yaml.dump(list)); - // - options.setExplicitEnd(true); - yaml = new Yaml(options); - assertEquals("--- [1, 2, 3]\n...\n", yaml.dump(list)); - } - - public void testVersion() { - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - list.add(3); - assertEquals("[1, 2, 3]\n", yaml.dump(list)); - // - DumperOptions options = new DumperOptions(); - options = new DumperOptions(); - options.setVersion(DumperOptions.Version.V1_1); - yaml = new Yaml(options); - assertEquals("%YAML 1.1\n--- [1, 2, 3]\n", yaml.dump(list)); - // - options.setVersion(DumperOptions.Version.V1_0); - yaml = new Yaml(options); - assertEquals("%YAML 1.0\n--- [1, 2, 3]\n", yaml.dump(list)); - // - assertEquals("Version: 1.1", DumperOptions.Version.V1_1.toString()); - } - - public void testTags() { - Yaml yaml = new Yaml(); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - list.add(3); - assertEquals("[1, 2, 3]\n", yaml.dump(list)); - // - DumperOptions options = new DumperOptions(); - options = new DumperOptions(); - Map<String, String> tags = new LinkedHashMap<String, String>(); - tags.put("!foo!", "bar"); - options.setTags(tags); - yaml = new Yaml(options); - assertEquals("%TAG !foo! bar\n--- [1, 2, 3]\n", yaml.dump(list)); - // - options = new DumperOptions(); - tags.put("!yaml!", Tag.PREFIX); - yaml = new Yaml(options); - assertEquals("foo\n", yaml.dump("foo")); - } - - public void testAllowUnicode() { - Yaml yaml = new Yaml(); - assertEquals("out: " + yaml.dump("\u00DCber"), "\u00DCber\n", yaml.dump("\u00DCber")); - // - DumperOptions options = new DumperOptions(); - options = new DumperOptions(); - options.setAllowUnicode(false); - yaml = new Yaml(options); - assertEquals("\"\\xdcber\"\n", yaml.dump("\u00DCber")); - } - - public void testToString() { - DumperOptions.ScalarStyle scalarStyle = DumperOptions.ScalarStyle.LITERAL; - assertEquals("Scalar style: '|'", scalarStyle.toString()); - // - DumperOptions.FlowStyle flowStyle = DumperOptions.FlowStyle.BLOCK; - assertEquals("Flow style: 'false'", flowStyle.toString()); - // - DumperOptions.LineBreak lb = DumperOptions.LineBreak.UNIX; - assertEquals("Line break: UNIX", lb.toString()); - } - - public void testWithRepresenter() { - Representer representer = new Representer(); - DumperOptions options = new DumperOptions(); - options.setIndent(4); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(representer, options); - List<Integer> list = new ArrayList<Integer>(); - list.add(1); - list.add(2); - list.add(3); - Map<String, Object> map = new LinkedHashMap<String, Object>(); - map.put("a", "b"); - map.put("c", list); - assertEquals("a: b\nc:\n- 1\n- 2\n- 3\n", yaml.dump(map)); + } + + public void testDefaultFlowStyle() { + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + list.add(3); + assertEquals("[1, 2, 3]\n", yaml.dump(list)); + // + DumperOptions options = new DumperOptions(); + options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + yaml = new Yaml(options); + assertEquals("[1, 2, 3]\n", yaml.dump(list)); + // + options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + options.setPrettyFlow(true); + yaml = new Yaml(options); + assertEquals("[\n 1,\n 2,\n 3\n]\n", yaml.dump(list)); + // + options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yaml = new Yaml(options); + assertEquals("- 1\n- 2\n- 3\n", yaml.dump(list)); + // null check + try { + options.setDefaultFlowStyle(null); + fail("Null must not be accepted."); + } catch (NullPointerException e) { + assertEquals("Use FlowStyle enum.", e.getMessage()); } - - public void testSplitLinesDoubleQuoted() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - Yaml yaml; - String output; - - // Split lines enabled (default) - assertTrue(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals("\"1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888\\\n \\ 9999999999 0000000000\"\n", output); - - // Split lines disabled - options.setSplitLines(false); - assertFalse(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals("\"1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\"\n", output); + } + + public void testDefaultFlowStyleNested() { + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + list.add(3); + Map<String, Object> map = new LinkedHashMap<String, Object>(); + map.put("a", "b"); + map.put("c", list); + String result = yaml.dump(map); + assertEquals("a: b\nc: [1, 2, 3]\n", result); + // + DumperOptions options = new DumperOptions(); + options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + yaml = new Yaml(options); + assertEquals("{a: b, c: [1, 2, 3]}\n", yaml.dump(map)); + // + options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + options.setPrettyFlow(true); + yaml = new Yaml(options); + result = yaml.dump(map); + assertEquals("{\n a: b,\n c: [\n 1,\n 2,\n 3\n ]\n \n}\n", result); + // + options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yaml = new Yaml(options); + assertEquals("a: b\nc:\n- 1\n- 2\n- 3\n", yaml.dump(map)); + } + + public void testCanonical() { + Yaml yaml = new Yaml(); + assertEquals("123\n", yaml.dump(123)); + // + DumperOptions options = new DumperOptions(); + options = new DumperOptions(); + options.setCanonical(true); + yaml = new Yaml(options); + assertEquals("---\n!!int \"123\"\n", yaml.dump(123)); + // + options = new DumperOptions(); + options.setCanonical(false); + yaml = new Yaml(options); + assertEquals("123\n", yaml.dump(123)); + } + + public void testIndent() { + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + DumperOptions options = new DumperOptions(); + options.setCanonical(true); + yaml = new Yaml(options); + assertEquals("---\n!!seq [\n !!int \"1\",\n !!int \"2\",\n]\n", yaml.dump(list)); + // + options.setIndent(4); + yaml = new Yaml(options); + assertEquals("---\n!!seq [\n !!int \"1\",\n !!int \"2\",\n]\n", yaml.dump(list)); + // + try { + options.setIndent(0); + fail(); + } catch (YAMLException e) { + assertTrue(true); } - - public void testSplitLinesSingleQuoted() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); - Yaml yaml; - String output; - - // Split lines enabled (default) - assertTrue(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals("'1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888\n 9999999999 0000000000'\n", output); - - // Split lines disabled - options.setSplitLines(false); - assertFalse(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals("'1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000'\n", output); + try { + options.setIndent(-2); + fail(); + } catch (YAMLException e) { + assertTrue(true); } - - public void testSplitLinesFolded() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.FOLDED); - Yaml yaml; - String output; - - // Split lines enabled (default) - assertTrue(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals(">-\n 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888\n 9999999999 0000000000\n", output); - - // Split lines disabled - options.setSplitLines(false); - assertFalse(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals(">-\n 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", output); + try { + options.setIndent(11); + fail(); + } catch (YAMLException e) { + assertTrue(true); } - - public void testSplitLinesLiteral() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.LITERAL); - Yaml yaml; - String output; - - // Split lines enabled (default) -- split lines does not apply to literal style - assertTrue(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals("|-\n 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", output); + // + assertTrue(Emitter.MIN_INDENT > 0); + assertTrue(Emitter.MIN_INDENT < Emitter.MAX_INDENT); + assertTrue(Emitter.MAX_INDENT < 20); + } + + public void testLineBreak() { + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + DumperOptions options = new DumperOptions(); + options.setCanonical(true); + yaml = new Yaml(options); + assertEquals("---\n!!seq [\n !!int \"1\",\n !!int \"2\",\n]\n", yaml.dump(list)); + // + options.setLineBreak(DumperOptions.LineBreak.WIN); + yaml = new Yaml(options); + String output = yaml.dump(list); + assertEquals("---\r\n!!seq [\r\n !!int \"1\",\r\n !!int \"2\",\r\n]\r\n", output); + // null check + try { + options.setLineBreak(null); + fail("Null must not be accepted."); + } catch (NullPointerException e) { + assertEquals("Specify line break.", e.getMessage()); } - - public void testSplitLinesPlain() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); - Yaml yaml; - String output; - - // Split lines enabled (default) -- split lines does not apply to plain style - assertTrue(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - assertEquals("1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", output); + } + + public void testLineBreakForPlatform() { + DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); + assertEquals("Line break must match platform's default.", System.getProperty("line.separator"), + lineBreak.getString()); + // + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + DumperOptions options = new DumperOptions(); + options.setLineBreak(DumperOptions.LineBreak.getPlatformLineBreak()); + yaml = new Yaml(options); + assertEquals("[1, 2]", yaml.dump(list).trim()); + } + + public void testLineBreakForPlatformUnix() { + System.setProperty("line.separator", "\n"); + assertEquals("\n", System.getProperty("line.separator")); + DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); + assertEquals("Line break must match platform's default.", System.getProperty("line.separator"), + lineBreak.getString()); + assertEquals("Unknown Line break must match UNIX line break.", "\n", lineBreak.getString()); + } + + public void testLineBreakForPlatformMac() { + System.setProperty("line.separator", "\r"); + assertEquals("\r", System.getProperty("line.separator")); + DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); + assertEquals("Line break must match platform's default.", System.getProperty("line.separator"), + lineBreak.getString()); + assertEquals("Unknown Line break must match UNIX line break.", "\r", lineBreak.getString()); + } + + public void testLineBreakForPlatformWin() { + System.setProperty("line.separator", "\r\n"); + assertEquals("\r\n", System.getProperty("line.separator")); + DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); + assertEquals("Line break must match platform's default.", System.getProperty("line.separator"), + lineBreak.getString()); + assertEquals("Unknown Line break must match UNIX line break.", "\r\n", lineBreak.getString()); + } + + public void testLineBreakForPlatformUnknown() { + System.setProperty("line.separator", "\n\r"); + assertEquals("\n\r", System.getProperty("line.separator")); + DumperOptions.LineBreak lineBreak = DumperOptions.LineBreak.getPlatformLineBreak(); + assertEquals("Unknown Line break must match UNIX line break.", "\n", lineBreak.getString()); + } + + public void testExplicitStart() { + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + list.add(3); + assertEquals("[1, 2, 3]\n", yaml.dump(list)); + // + DumperOptions options = new DumperOptions(); + options = new DumperOptions(); + options.setExplicitStart(true); + yaml = new Yaml(options); + assertEquals("--- [1, 2, 3]\n", yaml.dump(list)); + // + options.setExplicitEnd(true); + yaml = new Yaml(options); + assertEquals("--- [1, 2, 3]\n...\n", yaml.dump(list)); + } + + public void testVersion() { + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + list.add(3); + assertEquals("[1, 2, 3]\n", yaml.dump(list)); + // + DumperOptions options = new DumperOptions(); + options = new DumperOptions(); + options.setVersion(DumperOptions.Version.V1_1); + yaml = new Yaml(options); + assertEquals("%YAML 1.1\n--- [1, 2, 3]\n", yaml.dump(list)); + // + options.setVersion(DumperOptions.Version.V1_0); + yaml = new Yaml(options); + assertEquals("%YAML 1.0\n--- [1, 2, 3]\n", yaml.dump(list)); + // + assertEquals("Version: 1.1", DumperOptions.Version.V1_1.toString()); + } + + public void testTags() { + Yaml yaml = new Yaml(); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + list.add(3); + assertEquals("[1, 2, 3]\n", yaml.dump(list)); + // + DumperOptions options = new DumperOptions(); + options = new DumperOptions(); + Map<String, String> tags = new LinkedHashMap<String, String>(); + tags.put("!foo!", "bar"); + options.setTags(tags); + yaml = new Yaml(options); + assertEquals("%TAG !foo! bar\n--- [1, 2, 3]\n", yaml.dump(list)); + // + options = new DumperOptions(); + tags.put("!yaml!", Tag.PREFIX); + yaml = new Yaml(options); + assertEquals("foo\n", yaml.dump("foo")); + } + + public void testAllowUnicode() { + Yaml yaml = new Yaml(); + assertEquals("out: " + yaml.dump("\u00DCber"), "\u00DCber\n", yaml.dump("\u00DCber")); + // + DumperOptions options = new DumperOptions(); + options = new DumperOptions(); + options.setAllowUnicode(false); + yaml = new Yaml(options); + assertEquals("\"\\xdcber\"\n", yaml.dump("\u00DCber")); + } + + public void testToString() { + DumperOptions.ScalarStyle scalarStyle = DumperOptions.ScalarStyle.LITERAL; + assertEquals("Scalar style: '|'", scalarStyle.toString()); + // + DumperOptions.FlowStyle flowStyle = DumperOptions.FlowStyle.BLOCK; + assertEquals("Flow style: 'false'", flowStyle.toString()); + // + DumperOptions.LineBreak lb = DumperOptions.LineBreak.UNIX; + assertEquals("Line break: UNIX", lb.toString()); + } + + public void testWithRepresenter() { + Representer representer = new Representer(); + DumperOptions options = new DumperOptions(); + options.setIndent(4); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(representer, options); + List<Integer> list = new ArrayList<Integer>(); + list.add(1); + list.add(2); + list.add(3); + Map<String, Object> map = new LinkedHashMap<String, Object>(); + map.put("a", "b"); + map.put("c", list); + assertEquals("a: b\nc:\n- 1\n- 2\n- 3\n", yaml.dump(map)); + } + + public void testSplitLinesDoubleQuoted() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + Yaml yaml; + String output; + + // Split lines enabled (default) + assertTrue(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "\"1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888\\\n \\ 9999999999 0000000000\"\n", + output); + + // Lines with double spaces can be split too as whitespace can be preserved + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "\"1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777\\\n \\ 8888888888 9999999999 0000000000\"\n", + output); + + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "\"1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\"\n", + output); + } + + public void testSplitLinesSingleQuoted() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); + Yaml yaml; + String output; + + // Split lines enabled (default) + assertTrue(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "'1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888\n 9999999999 0000000000'\n", + output); + + // Do not split on double space as whitespace cannot be preserved in single quoted style + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "'1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000'\n", + output); + + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "'1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000'\n", + output); + } + + public void testSplitLinesFolded() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.FOLDED); + Yaml yaml; + String output; + + // Split lines enabled (default) + assertTrue(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + ">-\n 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888\n 9999999999 0000000000\n", + output); + + // Do not split on double space as whitespace cannot be preserved in folded style + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + ">-\n 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", + output); + + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + ">-\n 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", + output); + } + + public void testSplitLinesLiteral() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.LITERAL); + Yaml yaml; + String output; + + // Split lines enabled (default) -- split lines does not apply to literal style + assertTrue(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "|-\n 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", + output); + } + + public void testSplitLinesPlain() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); + Yaml yaml; + String output; + + // Split lines enabled (default) + assertTrue(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888\n 9999999999 0000000000\n", + output); + + // Do not split on double space as whitespace cannot be preserved in plain style + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", + output); + + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + assertEquals( + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000\n", + output); + } + + public void testSetIndicatorIndentNegative() { + DumperOptions options = new DumperOptions(); + try { + options.setIndicatorIndent(-1); + fail("Negative indent must not be accepted."); + } catch (YAMLException e) { + assertEquals("Indicator indent must be non-negative.", e.getMessage()); } - - public void testSetIndicatorIndentNegative() { - DumperOptions options = new DumperOptions(); - try { - options.setIndicatorIndent(-1); - fail("Negative indent must not be accepted."); - } catch (YAMLException e) { - assertEquals("Indicator indent must be non-negative.", e.getMessage()); - } + } + + public void testSetIndicatorIndentTooBig() { + DumperOptions options = new DumperOptions(); + try { + options.setIndicatorIndent(100); + fail("Negative indent must not be accepted."); + } catch (YAMLException e) { + assertEquals("Indicator indent must be at most Emitter.MAX_INDENT-1: 9", e.getMessage()); } - - public void testSetIndicatorIndentTooBig() { - DumperOptions options = new DumperOptions(); - try { - options.setIndicatorIndent(100); - fail("Negative indent must not be accepted."); - } catch (YAMLException e) { - assertEquals("Indicator indent must be at most Emitter.MAX_INDENT-1: 9", e.getMessage()); - } - } - - public void testCreateUnknownStyle() { - try { - DumperOptions.ScalarStyle.createStyle(' '); - fail("Negative indent must not be accepted."); - } catch (YAMLException e) { - assertEquals("Unknown scalar style character: ", e.getMessage()); - } - } - - public void testCreateStyle() { - assertEquals(DumperOptions.ScalarStyle.DOUBLE_QUOTED, DumperOptions.ScalarStyle.createStyle('"')); - assertEquals(DumperOptions.ScalarStyle.SINGLE_QUOTED, DumperOptions.ScalarStyle.createStyle('\'')); - assertEquals(DumperOptions.ScalarStyle.LITERAL, DumperOptions.ScalarStyle.createStyle('|')); - assertEquals(DumperOptions.ScalarStyle.FOLDED, DumperOptions.ScalarStyle.createStyle('>')); - assertEquals(DumperOptions.ScalarStyle.PLAIN, DumperOptions.ScalarStyle.createStyle(null)); + } + + public void testCreateUnknownStyle() { + try { + DumperOptions.ScalarStyle.createStyle(' '); + fail("Negative indent must not be accepted."); + } catch (YAMLException e) { + assertEquals("Unknown scalar style character: ", e.getMessage()); } + } + + public void testCreateStyle() { + assertEquals(DumperOptions.ScalarStyle.DOUBLE_QUOTED, + DumperOptions.ScalarStyle.createStyle('"')); + assertEquals(DumperOptions.ScalarStyle.SINGLE_QUOTED, + DumperOptions.ScalarStyle.createStyle('\'')); + assertEquals(DumperOptions.ScalarStyle.LITERAL, DumperOptions.ScalarStyle.createStyle('|')); + assertEquals(DumperOptions.ScalarStyle.FOLDED, DumperOptions.ScalarStyle.createStyle('>')); + assertEquals(DumperOptions.ScalarStyle.PLAIN, DumperOptions.ScalarStyle.createStyle(null)); + } } diff --git a/src/test/java/org/yaml/snakeyaml/EnumBean.java b/src/test/java/org/yaml/snakeyaml/EnumBean.java index 63653719..9bd96bd4 100644 --- a/src/test/java/org/yaml/snakeyaml/EnumBean.java +++ b/src/test/java/org/yaml/snakeyaml/EnumBean.java @@ -1,48 +1,47 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.LinkedHashMap; public class EnumBean { - private int id; - private Suit suit; - private LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); - public LinkedHashMap<Suit, Integer> getMap() { - return map; - } + private int id; + private Suit suit; + private LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); - public void setMap(LinkedHashMap<Suit, Integer> map) { - this.map = map; - } + public LinkedHashMap<Suit, Integer> getMap() { + return map; + } - public int getId() { - return id; - } + public void setMap(LinkedHashMap<Suit, Integer> map) { + this.map = map; + } - public void setId(int id) { - this.id = id; - } + public int getId() { + return id; + } - public Suit getSuit() { - return suit; - } + public void setId(int id) { + this.id = id; + } - public void setSuit(Suit suit) { - this.suit = suit; - } + public Suit getSuit() { + return suit; + } + + public void setSuit(Suit suit) { + this.suit = suit; + } } diff --git a/src/test/java/org/yaml/snakeyaml/EnumBeanGen.java b/src/test/java/org/yaml/snakeyaml/EnumBeanGen.java new file mode 100644 index 00000000..a819e19e --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/EnumBeanGen.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml; + +import java.util.LinkedHashMap; + +public class EnumBeanGen<T extends Enum<T>> { + + private int id; + private Enum<T> suit; + private LinkedHashMap<T, Integer> map = new LinkedHashMap<T, Integer>(); + + public LinkedHashMap<T, Integer> getMap() { + return map; + } + + public void setMap(LinkedHashMap<T, Integer> map) { + this.map = map; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Enum<T> getSuit() { + return suit; + } + + public void setSuit(T suit) { + this.suit = suit; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/EnumBeanGenTest.java b/src/test/java/org/yaml/snakeyaml/EnumBeanGenTest.java new file mode 100644 index 00000000..6388bfa6 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/EnumBeanGenTest.java @@ -0,0 +1,100 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml; + +import java.util.LinkedHashMap; +import junit.framework.TestCase; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.introspector.PropertySubstitute; + +public class EnumBeanGenTest extends TestCase { + + // Dumping + public void testDumpEnumBean() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + EnumBeanGen<Suit> bean = new EnumBeanGen<Suit>(); + bean.setId(17); + bean.setSuit(Suit.SPADES); + LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); + map.put(Suit.CLUBS, 1); + map.put(Suit.DIAMONDS, 2); + bean.setMap(map); + String output = yaml.dump(bean); + assertEquals( + "!!org.yaml.snakeyaml.EnumBeanGen\nid: 17\nmap:\n !!org.yaml.snakeyaml.Suit 'CLUBS': 1\n !!org.yaml.snakeyaml.Suit 'DIAMONDS': 2\nsuit: !!org.yaml.snakeyaml.Suit 'SPADES'\n", + output); + yaml.load(output);// load back + } + + // Loading + public void testLoadEnumBeanExplicitTags() { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + EnumBeanGen<Suit> bean = yaml.load( + "!!org.yaml.snakeyaml.EnumBeanGen\nid: 174\nmap:\n !!org.yaml.snakeyaml.Suit 'CLUBS': 1\n !!org.yaml.snakeyaml.Suit 'DIAMONDS': 2\nsuit: !!org.yaml.snakeyaml.Suit 'CLUBS'"); + + LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); + map.put(Suit.CLUBS, 1); + map.put(Suit.DIAMONDS, 2); + + assertEquals(Suit.CLUBS, bean.getSuit()); + assertEquals(174, bean.getId()); + assertEquals(map, bean.getMap()); + } + + public void testLoadNoTag4GenEnumProperty() { + TypeDescription td = new TypeDescription(EnumBeanGen.class); + td.substituteProperty("suit", Suit.class, null, null); + + Constructor constructor = new Constructor(); + constructor.addTypeDescription(td); + Yaml yaml = new Yaml(constructor); + + @SuppressWarnings("unchecked") + EnumBeanGen<Suit> bean = yaml.load( + "!!org.yaml.snakeyaml.EnumBeanGen\nid: 174\nmap:\n !!org.yaml.snakeyaml.Suit 'CLUBS': 1\n !!org.yaml.snakeyaml.Suit 'DIAMONDS': 2\nsuit: CLUBS"); + + LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); + map.put(Suit.CLUBS, 1); + map.put(Suit.DIAMONDS, 2); + + assertEquals(Suit.CLUBS, bean.getSuit()); + assertEquals(174, bean.getId()); + assertEquals(map, bean.getMap()); + } + + public void testLoadNoTags() { + Constructor c = new Constructor(); + TypeDescription td = new TypeDescription(EnumBeanGen.class); + td.substituteProperty("suit", Suit.class, null, null); + td.substituteProperty(new PropertySubstitute("map", null, Suit.class, Object.class)); + + c.addTypeDescription(td); + Yaml yaml = new Yaml(c); + @SuppressWarnings("unchecked") + EnumBeanGen<Suit> bean = yaml.load( + "!!org.yaml.snakeyaml.EnumBeanGen\nid: 174\nmap:\n CLUBS: 1\n DIAMONDS: 2\nsuit: CLUBS"); + + LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); + map.put(Suit.CLUBS, 1); + map.put(Suit.DIAMONDS, 2); + + assertEquals(Suit.CLUBS, bean.getSuit()); + assertEquals(174, bean.getId()); + assertEquals(map, bean.getMap()); + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/EnumTest.java b/src/test/java/org/yaml/snakeyaml/EnumTest.java index 3587facc..280b86b5 100644 --- a/src/test/java/org/yaml/snakeyaml/EnumTest.java +++ b/src/test/java/org/yaml/snakeyaml/EnumTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -21,179 +19,176 @@ import java.util.EnumMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.constructor.Constructor; public class EnumTest extends TestCase { - // Dumping - public void testDumpEnum() { - Yaml yaml = new Yaml(); - String output = yaml.dump(Suit.CLUBS); - assertEquals("!!org.yaml.snakeyaml.Suit 'CLUBS'\n", output); - } - - public void testDumpOverriddenToString() { - Yaml yaml = new Yaml(); - String output = yaml.dump(DumperOptions.FlowStyle.BLOCK); - assertEquals("!!org.yaml.snakeyaml.DumperOptions$FlowStyle 'BLOCK'\n", output); - } - - public void testDumpEnumArray() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String output = yaml.dump(Suit.values()); - assertEquals( - "- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'HEARTS'\n- !!org.yaml.snakeyaml.Suit 'SPADES'\n", - output); - } - - public void testDumpEnumList() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - List<Suit> list = Arrays.asList(Suit.values()); - String output = yaml.dump(list); - assertEquals( - "- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'HEARTS'\n- !!org.yaml.snakeyaml.Suit 'SPADES'\n", - output); - } - - public void testDumpEnumListNoAnchor() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - List<Suit> list = new ArrayList<Suit>(3); - list.add(Suit.CLUBS); - list.add(Suit.DIAMONDS); - list.add(Suit.CLUBS); - String output = yaml.dump(list); - assertEquals( - "- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'CLUBS'\n", - output); - } - - public void testDumpEnumMap() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - Map<String, Suit> map = new LinkedHashMap<String, Suit>(); - map.put("c", Suit.CLUBS); - map.put("d", Suit.DIAMONDS); - String output = yaml.dump(map); - assertEquals( - "c: !!org.yaml.snakeyaml.Suit 'CLUBS'\nd: !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n", - output); - } - - public void testDumpEnumMap2() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - Map<Suit, Integer> map = new EnumMap<Suit, Integer>(Suit.class); - map.put(Suit.CLUBS, 0); - map.put(Suit.DIAMONDS, 123); - String output = yaml.dump(map); - assertEquals( - "!!org.yaml.snakeyaml.Suit 'CLUBS': 0\n!!org.yaml.snakeyaml.Suit 'DIAMONDS': 123\n", - output); - } - - public void testDumpEnumBean() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - EnumBean bean = new EnumBean(); - bean.setId(17); - bean.setSuit(Suit.SPADES); - LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); - map.put(Suit.CLUBS, 1); - map.put(Suit.DIAMONDS, 2); - bean.setMap(map); - String output = yaml.dump(bean); - assertEquals( - "!!org.yaml.snakeyaml.EnumBean\nid: 17\nmap:\n CLUBS: 1\n DIAMONDS: 2\nsuit: SPADES\n", - output); - } - - // Loading - public void testLoadEnum() { - Yaml yaml = new Yaml(); - Suit suit = (Suit) yaml.load("!!org.yaml.snakeyaml.Suit 'CLUBS'\n"); - assertEquals(Suit.CLUBS, suit); - } - - public void testLoadOverridenToString() { - Yaml yaml = new Yaml(); - assertEquals(DumperOptions.FlowStyle.BLOCK, - yaml.load("!!org.yaml.snakeyaml.DumperOptions$FlowStyle 'BLOCK'\n")); - } - - @SuppressWarnings("unchecked") - public void testLoadEnumList() { - Yaml yaml = new Yaml(); - List<Suit> list = (List<Suit>) yaml - .load("- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'HEARTS'\n- !!org.yaml.snakeyaml.Suit 'SPADES'"); - assertEquals(4, list.size()); - assertEquals(Suit.CLUBS, list.get(0)); - assertEquals(Suit.DIAMONDS, list.get(1)); - assertEquals(Suit.HEARTS, list.get(2)); - assertEquals(Suit.SPADES, list.get(3)); - } - - @SuppressWarnings("unchecked") - public void testLoadEnumMap() { - Yaml yaml = new Yaml(); - Map<Integer, Suit> map = (Map<Integer, Suit>) yaml - .load("1: !!org.yaml.snakeyaml.Suit 'HEARTS'\n2: !!org.yaml.snakeyaml.Suit 'DIAMONDS'"); - assertEquals(2, map.size()); - assertEquals(Suit.HEARTS, map.get(1)); - assertEquals(Suit.DIAMONDS, map.get(2)); - } - - public void testLoadEnumBean() { - Yaml yaml = new Yaml(); - EnumBean bean = (EnumBean) yaml - .load("!!org.yaml.snakeyaml.EnumBean\nid: 174\nmap:\n !!org.yaml.snakeyaml.Suit 'CLUBS': 1\n !!org.yaml.snakeyaml.Suit 'DIAMONDS': 2\nsuit: CLUBS"); - - LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); - map.put(Suit.CLUBS, 1); - map.put(Suit.DIAMONDS, 2); - - assertEquals(Suit.CLUBS, bean.getSuit()); - assertEquals(174, bean.getId()); - assertEquals(map, bean.getMap()); - } - - public void testLoadEnumBean2() { - Constructor c = new Constructor(); - TypeDescription td = new TypeDescription(EnumBean.class); - td.putMapPropertyType("map", Suit.class, Object.class); - c.addTypeDescription(td); - Yaml yaml = new Yaml(c); - EnumBean bean = (EnumBean) yaml - .load("!!org.yaml.snakeyaml.EnumBean\nid: 174\nmap:\n CLUBS: 1\n DIAMONDS: 2\nsuit: CLUBS"); - - LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); - map.put(Suit.CLUBS, 1); - map.put(Suit.DIAMONDS, 2); - - assertEquals(Suit.CLUBS, bean.getSuit()); - assertEquals(174, bean.getId()); - assertEquals(map, bean.getMap()); - } - - public void testLoadWrongEnum() { - Yaml yaml = new Yaml(); - try { - yaml.load("1: !!org.yaml.snakeyaml.Suit 'HEARTS'\n2: !!org.yaml.snakeyaml.Suit 'KOSYR'"); - fail("KOSYR is not Suit"); - } catch (Exception e) { - assertTrue("KOSYR must be reported", - e.getMessage().contains("Unable to find enum value 'KOSYR' for enum")); - } + // Dumping + public void testDumpEnum() { + Yaml yaml = new Yaml(); + String output = yaml.dump(Suit.CLUBS); + assertEquals("!!org.yaml.snakeyaml.Suit 'CLUBS'\n", output); + } + + public void testDumpOverriddenToString() { + Yaml yaml = new Yaml(); + String output = yaml.dump(DumperOptions.FlowStyle.BLOCK); + assertEquals("!!org.yaml.snakeyaml.DumperOptions$FlowStyle 'BLOCK'\n", output); + } + + public void testDumpEnumArray() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String output = yaml.dump(Suit.values()); + assertEquals( + "- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'HEARTS'\n- !!org.yaml.snakeyaml.Suit 'SPADES'\n", + output); + } + + public void testDumpEnumList() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + List<Suit> list = Arrays.asList(Suit.values()); + String output = yaml.dump(list); + assertEquals( + "- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'HEARTS'\n- !!org.yaml.snakeyaml.Suit 'SPADES'\n", + output); + } + + public void testDumpEnumListNoAnchor() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + List<Suit> list = new ArrayList<Suit>(3); + list.add(Suit.CLUBS); + list.add(Suit.DIAMONDS); + list.add(Suit.CLUBS); + String output = yaml.dump(list); + assertEquals( + "- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'CLUBS'\n", + output); + } + + public void testDumpEnumMap() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + Map<String, Suit> map = new LinkedHashMap<String, Suit>(); + map.put("c", Suit.CLUBS); + map.put("d", Suit.DIAMONDS); + String output = yaml.dump(map); + assertEquals("c: !!org.yaml.snakeyaml.Suit 'CLUBS'\nd: !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n", + output); + } + + public void testDumpEnumMap2() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + Map<Suit, Integer> map = new EnumMap<Suit, Integer>(Suit.class); + map.put(Suit.CLUBS, 0); + map.put(Suit.DIAMONDS, 123); + String output = yaml.dump(map); + assertEquals( + "!!org.yaml.snakeyaml.Suit 'CLUBS': 0\n!!org.yaml.snakeyaml.Suit 'DIAMONDS': 123\n", + output); + } + + public void testDumpEnumBean() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + EnumBean bean = new EnumBean(); + bean.setId(17); + bean.setSuit(Suit.SPADES); + LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); + map.put(Suit.CLUBS, 1); + map.put(Suit.DIAMONDS, 2); + bean.setMap(map); + String output = yaml.dump(bean); + assertEquals( + "!!org.yaml.snakeyaml.EnumBean\nid: 17\nmap:\n CLUBS: 1\n DIAMONDS: 2\nsuit: SPADES\n", + output); + } + + // Loading + public void testLoadEnum() { + Yaml yaml = new Yaml(); + Suit suit = yaml.load("!!org.yaml.snakeyaml.Suit 'CLUBS'\n"); + assertEquals(Suit.CLUBS, suit); + } + + public void testLoadOverridenToString() { + Yaml yaml = new Yaml(); + assertEquals(DumperOptions.FlowStyle.BLOCK, + yaml.load("!!org.yaml.snakeyaml.DumperOptions$FlowStyle 'BLOCK'\n")); + } + + @SuppressWarnings("unchecked") + public void testLoadEnumList() { + Yaml yaml = new Yaml(); + List<Suit> list = yaml.load( + "- !!org.yaml.snakeyaml.Suit 'CLUBS'\n- !!org.yaml.snakeyaml.Suit 'DIAMONDS'\n- !!org.yaml.snakeyaml.Suit 'HEARTS'\n- !!org.yaml.snakeyaml.Suit 'SPADES'"); + assertEquals(4, list.size()); + assertEquals(Suit.CLUBS, list.get(0)); + assertEquals(Suit.DIAMONDS, list.get(1)); + assertEquals(Suit.HEARTS, list.get(2)); + assertEquals(Suit.SPADES, list.get(3)); + } + + @SuppressWarnings("unchecked") + public void testLoadEnumMap() { + Yaml yaml = new Yaml(); + Map<Integer, Suit> map = + yaml.load("1: !!org.yaml.snakeyaml.Suit 'HEARTS'\n2: !!org.yaml.snakeyaml.Suit 'DIAMONDS'"); + assertEquals(2, map.size()); + assertEquals(Suit.HEARTS, map.get(1)); + assertEquals(Suit.DIAMONDS, map.get(2)); + } + + public void testLoadEnumBean() { + Yaml yaml = new Yaml(); + EnumBean bean = yaml.load( + "!!org.yaml.snakeyaml.EnumBean\nid: 174\nmap:\n !!org.yaml.snakeyaml.Suit 'CLUBS': 1\n !!org.yaml.snakeyaml.Suit 'DIAMONDS': 2\nsuit: CLUBS"); + + LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); + map.put(Suit.CLUBS, 1); + map.put(Suit.DIAMONDS, 2); + + assertEquals(Suit.CLUBS, bean.getSuit()); + assertEquals(174, bean.getId()); + assertEquals(map, bean.getMap()); + } + + public void testLoadEnumBean2() { + Constructor c = new Constructor(); + TypeDescription td = new TypeDescription(EnumBean.class); + td.putMapPropertyType("map", Suit.class, Object.class); + c.addTypeDescription(td); + Yaml yaml = new Yaml(c); + EnumBean bean = yaml.load( + "!!org.yaml.snakeyaml.EnumBean\nid: 174\nmap:\n CLUBS: 1\n DIAMONDS: 2\nsuit: CLUBS"); + + LinkedHashMap<Suit, Integer> map = new LinkedHashMap<Suit, Integer>(); + map.put(Suit.CLUBS, 1); + map.put(Suit.DIAMONDS, 2); + + assertEquals(Suit.CLUBS, bean.getSuit()); + assertEquals(174, bean.getId()); + assertEquals(map, bean.getMap()); + } + + public void testLoadWrongEnum() { + Yaml yaml = new Yaml(); + try { + yaml.load("1: !!org.yaml.snakeyaml.Suit 'HEARTS'\n2: !!org.yaml.snakeyaml.Suit 'KOSYR'"); + fail("KOSYR is not Suit"); + } catch (Exception e) { + assertTrue("KOSYR must be reported", + e.getMessage().contains("Unable to find enum value 'KOSYR' for enum")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/Example2_24Test.java b/src/test/java/org/yaml/snakeyaml/Example2_24Test.java index aa544641..6931f84d 100644 --- a/src/test/java/org/yaml/snakeyaml/Example2_24Test.java +++ b/src/test/java/org/yaml/snakeyaml/Example2_24Test.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.List; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.MappingNode; @@ -32,216 +28,229 @@ import org.yaml.snakeyaml.representer.Representer; /** * Test Example 2.24 from the YAML specification - * - * @see <a href="http://yaml.org/spec/1.1/"></a> */ public class Example2_24Test extends TestCase { - class MyConstructor extends Constructor { - public MyConstructor() { - this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:shape"), - new ConstructShape()); - this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:circle"), - new ConstructCircle()); - this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:line"), new ConstructLine()); - this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:label"), - new ConstructLabel()); - } - - private class ConstructShape extends AbstractConstruct { - @SuppressWarnings("unchecked") - public Object construct(Node node) { - SequenceNode snode = (SequenceNode) node; - List<Entity> values = (List<Entity>) constructSequence(snode); - Shape shape = new Shape(values); - return shape; - } - } - - private class ConstructCircle extends AbstractConstruct { - @SuppressWarnings("unchecked") - public Object construct(Node node) { - MappingNode mnode = (MappingNode) node; - Map<Object, Object> values = constructMapping(mnode); - Circle circle = new Circle((Map<String, Integer>) values.get("center"), - (Integer) values.get("radius")); - return circle; - } - } - - private class ConstructLine extends AbstractConstruct { - @SuppressWarnings("unchecked") - public Object construct(Node node) { - MappingNode mnode = (MappingNode) node; - Map<Object, Object> values = constructMapping(mnode); - Line line = new Line((Map<String, Integer>) values.get("start"), - (Map<String, Integer>) values.get("finish")); - return line; - } - } - - private class ConstructLabel extends AbstractConstruct { - @SuppressWarnings("unchecked") - public Object construct(Node node) { - MappingNode mnode = (MappingNode) node; - Map<Object, Object> values = constructMapping(mnode); - Label label = new Label((Map<String, Integer>) values.get("start"), - (Integer) values.get("color"), (String) values.get("text")); - return label; - } - } - } - - class MyRepresenter extends Representer { - public MyRepresenter() { - this.representers.put(Shape.class, new RepresentShape()); - this.representers.put(Circle.class, new RepresentCircle()); - this.representers.put(Line.class, new RepresentLine()); - this.representers.put(Label.class, new RepresentLabel()); - this.representers.put(HexInteger.class, new RepresentHex()); - } - - private class RepresentShape implements Represent { - public Node representData(Object data) { - Shape shape = (Shape) data; - List<Entity> value = shape.getEntities(); - return representSequence(new Tag("!shape"), value, Boolean.FALSE); - } - } - - private class RepresentCircle implements Represent { - public Node representData(Object data) { - Circle circle = (Circle) data; - Map<String, Object> map = new TreeMap<String, Object>(); - map.put("center", circle.getCenter()); - map.put("radius", circle.getRadius()); - return representMapping(new Tag("!circle"), map, Boolean.FALSE); - } - } - - private class RepresentLine implements Represent { - public Node representData(Object data) { - Line line = (Line) data; - Map<String, Object> map = new TreeMap<String, Object>(); - map.put("start", line.getStart()); - map.put("finish", line.getFinish()); - return representMapping(new Tag("!line"), map, Boolean.FALSE); - } - } - - private class RepresentLabel implements Represent { - public Node representData(Object data) { - Label label = (Label) data; - Map<String, Object> map = new TreeMap<String, Object>(); - map.put("start", label.getStart()); - map.put("color", new HexInteger(label.getColor())); - map.put("text", label.getText()); - return representMapping(new Tag("!label"), map, Boolean.FALSE); - } - } - - private class RepresentHex implements Represent { - public Node representData(Object data) { - HexInteger hex = (HexInteger) data; - return representScalar(Tag.INT, "0x" - + Integer.toHexString(hex.getColor()).toUpperCase(), null); - } - } - } - - private class HexInteger { - private Integer color; - - public HexInteger(Integer color) { - this.color = color; - } - - public Integer getColor() { - return color; - } - } - - private class Shape { - private List<Entity> entities; - - public List<Entity> getEntities() { - return entities; - } - - public Shape(List<Entity> entities) { - this.entities = entities; - } - } - - private class Entity { - } - - private class Circle extends Entity { - private Map<String, Integer> center; - private Integer radius; - - public Circle(Map<String, Integer> center, Integer radius) { - this.center = center; - this.radius = radius; - } - - public Map<String, Integer> getCenter() { - return center; - } - - public Integer getRadius() { - return radius; - } - } - - private class Line extends Entity { - private Map<String, Integer> start; - private Map<String, Integer> finish; - - public Line(Map<String, Integer> start, Map<String, Integer> finish) { - this.start = start; - this.finish = finish; - } - - public Map<String, Integer> getStart() { - return start; - } - - public Map<String, Integer> getFinish() { - return finish; - } - } - - private class Label extends Entity { - private Map<String, Integer> start; - private Integer color; - private String text; - public Label(Map<String, Integer> start, Integer color, String text) { - this.start = start; - this.color = color; - this.text = text; - } + class MyConstructor extends Constructor { + + public MyConstructor() { + this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:shape"), new ConstructShape()); + this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:circle"), new ConstructCircle()); + this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:line"), new ConstructLine()); + this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:label"), new ConstructLabel()); + } + + private class ConstructShape extends AbstractConstruct { + + @SuppressWarnings("unchecked") + public Object construct(Node node) { + SequenceNode snode = (SequenceNode) node; + List<Entity> values = (List<Entity>) constructSequence(snode); + Shape shape = new Shape(values); + return shape; + } + } + + private class ConstructCircle extends AbstractConstruct { + + @SuppressWarnings("unchecked") + public Object construct(Node node) { + MappingNode mnode = (MappingNode) node; + Map<Object, Object> values = constructMapping(mnode); + Circle circle = + new Circle((Map<String, Integer>) values.get("center"), (Integer) values.get("radius")); + return circle; + } + } + + private class ConstructLine extends AbstractConstruct { + + @SuppressWarnings("unchecked") + public Object construct(Node node) { + MappingNode mnode = (MappingNode) node; + Map<Object, Object> values = constructMapping(mnode); + Line line = new Line((Map<String, Integer>) values.get("start"), + (Map<String, Integer>) values.get("finish")); + return line; + } + } + + private class ConstructLabel extends AbstractConstruct { + + @SuppressWarnings("unchecked") + public Object construct(Node node) { + MappingNode mnode = (MappingNode) node; + Map<Object, Object> values = constructMapping(mnode); + Label label = new Label((Map<String, Integer>) values.get("start"), + (Integer) values.get("color"), (String) values.get("text")); + return label; + } + } + } + + class MyRepresenter extends Representer { + + public MyRepresenter() { + this.representers.put(Shape.class, new RepresentShape()); + this.representers.put(Circle.class, new RepresentCircle()); + this.representers.put(Line.class, new RepresentLine()); + this.representers.put(Label.class, new RepresentLabel()); + this.representers.put(HexInteger.class, new RepresentHex()); + } + + private class RepresentShape implements Represent { + + public Node representData(Object data) { + Shape shape = (Shape) data; + List<Entity> value = shape.getEntities(); + return representSequence(new Tag("!shape"), value, DumperOptions.FlowStyle.BLOCK); + } + } + + private class RepresentCircle implements Represent { + + public Node representData(Object data) { + Circle circle = (Circle) data; + Map<String, Object> map = new TreeMap<String, Object>(); + map.put("center", circle.getCenter()); + map.put("radius", circle.getRadius()); + return representMapping(new Tag("!circle"), map, DumperOptions.FlowStyle.BLOCK); + } + } + + private class RepresentLine implements Represent { + + public Node representData(Object data) { + Line line = (Line) data; + Map<String, Object> map = new TreeMap<String, Object>(); + map.put("start", line.getStart()); + map.put("finish", line.getFinish()); + return representMapping(new Tag("!line"), map, DumperOptions.FlowStyle.BLOCK); + } + } + + private class RepresentLabel implements Represent { + + public Node representData(Object data) { + Label label = (Label) data; + Map<String, Object> map = new TreeMap<String, Object>(); + map.put("start", label.getStart()); + map.put("color", new HexInteger(label.getColor())); + map.put("text", label.getText()); + return representMapping(new Tag("!label"), map, DumperOptions.FlowStyle.BLOCK); + } + } + + private class RepresentHex implements Represent { + + public Node representData(Object data) { + HexInteger hex = (HexInteger) data; + return representScalar(Tag.INT, "0x" + Integer.toHexString(hex.getColor()).toUpperCase(), + null); + } + } + } + + private class HexInteger { + + private final Integer color; + + public HexInteger(Integer color) { + this.color = color; + } + + public Integer getColor() { + return color; + } + } + + private class Shape { + + private final List<Entity> entities; + + public List<Entity> getEntities() { + return entities; + } + + public Shape(List<Entity> entities) { + this.entities = entities; + } + } + + private class Entity { + + } + + private class Circle extends Entity { + + private final Map<String, Integer> center; + private final Integer radius; + + public Circle(Map<String, Integer> center, Integer radius) { + this.center = center; + this.radius = radius; + } + + public Map<String, Integer> getCenter() { + return center; + } + + public Integer getRadius() { + return radius; + } + } - public Map<String, Integer> getStart() { - return start; - } + private class Line extends Entity { - public Integer getColor() { - return color; - } + private final Map<String, Integer> start; + private final Map<String, Integer> finish; + + public Line(Map<String, Integer> start, Map<String, Integer> finish) { + this.start = start; + this.finish = finish; + } + + public Map<String, Integer> getStart() { + return start; + } + + public Map<String, Integer> getFinish() { + return finish; + } + } + + private class Label extends Entity { + + private final Map<String, Integer> start; + private final Integer color; + private final String text; + + public Label(Map<String, Integer> start, Integer color, String text) { + this.start = start; + this.color = color; + this.text = text; + } + + public Map<String, Integer> getStart() { + return start; + } - public String getText() { - return text; - } + public Integer getColor() { + return color; } - public void testExample_2_24() { - Yaml yaml = new Yaml(new MyConstructor()); - Shape shape = (Shape) yaml.load(Util.getLocalResource("specification/example2_24.yaml")); - assertNotNull(shape); - yaml = new Yaml(new MyRepresenter()); - String output = yaml.dump(shape); - String etalon = Util.getLocalResource("specification/example2_24_dumped.yaml"); - assertEquals(etalon, output); + public String getText() { + return text; } + } + + public void testExample_2_24() { + Yaml yaml = new Yaml(new MyConstructor()); + Shape shape = yaml.load(Util.getLocalResource("specification/example2_24.yaml")); + assertNotNull(shape); + yaml = new Yaml(new MyRepresenter()); + String output = yaml.dump(shape); + String etalon = Util.getLocalResource("specification/example2_24_dumped.yaml"); + assertEquals(etalon, output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Example2_27Test.java b/src/test/java/org/yaml/snakeyaml/Example2_27Test.java index e51be0fe..70f9a3c6 100644 --- a/src/test/java/org/yaml/snakeyaml/Example2_27Test.java +++ b/src/test/java/org/yaml/snakeyaml/Example2_27Test.java @@ -1,41 +1,35 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import junit.framework.TestCase; - import org.yaml.snakeyaml.constructor.Constructor; /** * Test Example 2.27 from the YAML specification - * - * @see <a href="http://yaml.org/spec/1.1/"></a> */ public class Example2_27Test extends TestCase { - public void testExample_2_27() { - Yaml yaml = new Yaml(new Constructor(Invoice.class)); - Invoice invoice = (Invoice) yaml.load(Util - .getLocalResource("specification/example2_27.yaml")); - assertNotNull(invoice); - Person billTo = invoice.billTo; - assertEquals("Dumars", billTo.family); - yaml = new Yaml(); - String output = yaml.dump(invoice); - String etalon = Util.getLocalResource("specification/example2_27_dumped.yaml"); - assertEquals(etalon, output); - } + public void testExample_2_27() { + Yaml yaml = new Yaml(new Constructor(Invoice.class)); + Invoice invoice = yaml.load(Util.getLocalResource("specification/example2_27.yaml")); + assertNotNull(invoice); + Person billTo = invoice.billTo; + assertEquals("Dumars", billTo.family); + yaml = new Yaml(); + String output = yaml.dump(invoice); + String etalon = Util.getLocalResource("specification/example2_27_dumped.yaml"); + assertEquals(etalon, output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/ExclamationTagTest.java b/src/test/java/org/yaml/snakeyaml/ExclamationTagTest.java new file mode 100644 index 00000000..1a590bc9 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/ExclamationTagTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * The tag "!" must force the parser to use only the node kind (scalar, sequence, mapping) (issue + * 459) + */ +public class ExclamationTagTest { + + @Test + public void testImplicitTag() { + Yaml yaml = new Yaml(); + Object result = yaml.load("! 12"); + assertEquals("It works the same way as PyYAML", 12, result); + // It might be changed -> assertEquals("12", yaml.load("! 12")); + } + + @Test + public void testNoImplicitTag() { + Yaml yaml = new Yaml(); + Object result = yaml.load("12"); + assertEquals(12, result); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/InputOutputExceptionTest.java b/src/test/java/org/yaml/snakeyaml/InputOutputExceptionTest.java index d309b542..3fd64c9d 100644 --- a/src/test/java/org/yaml/snakeyaml/InputOutputExceptionTest.java +++ b/src/test/java/org/yaml/snakeyaml/InputOutputExceptionTest.java @@ -1,80 +1,79 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.io.IOException; import java.io.InputStream; import java.io.Writer; - import junit.framework.TestCase; - import org.yaml.snakeyaml.error.YAMLException; public class InputOutputExceptionTest extends TestCase { - public void testIOExceptionOnLoad() { - try { - new Yaml().load(new BrokenInputStream()); - fail("Input must be broken."); - } catch (YAMLException e) { - assertTrue(e.getCause() instanceof IOException); - assertEquals("java.io.IOException: Broken 2", e.getMessage()); - } + + public void testIOExceptionOnLoad() { + try { + new Yaml().load(new BrokenInputStream()); + fail("Input must be broken."); + } catch (YAMLException e) { + assertTrue(e.getCause() instanceof IOException); + assertEquals("java.io.IOException: Broken 2", e.getMessage()); } + } - public void testIOExceptionOnDump() { - try { - new Yaml().dump("something", new BrokenWriter()); - fail("Output must be broken."); - } catch (YAMLException e) { - assertTrue(e.getCause() instanceof IOException); - assertEquals("java.io.IOException: Broken 12", e.getMessage()); - } + public void testIOExceptionOnDump() { + try { + new Yaml().dump("something", new BrokenWriter()); + fail("Output must be broken."); + } catch (YAMLException e) { + assertTrue(e.getCause() instanceof IOException); + assertEquals("java.io.IOException: Broken 12", e.getMessage()); } + } - private static class BrokenInputStream extends InputStream { - @Override - public int read() throws IOException { - throw new IOException("Broken 1"); - } + private static class BrokenInputStream extends InputStream { - @Override - public int read(byte[] bytes, int i, int i1) throws IOException { - throw new IOException("Broken 2"); - } + @Override + public int read() throws IOException { + throw new IOException("Broken 1"); + } - @Override - public void close() throws IOException { - throw new IOException("Broken 3"); - } + @Override + public int read(byte[] bytes, int i, int i1) throws IOException { + throw new IOException("Broken 2"); } - private static class BrokenWriter extends Writer { - @Override - public void close() throws IOException { - throw new IOException("Broken 10"); - } + @Override + public void close() throws IOException { + throw new IOException("Broken 3"); + } + } - @Override - public void flush() throws IOException { - throw new IOException("Broken 11"); - } + private static class BrokenWriter extends Writer { + + @Override + public void close() throws IOException { + throw new IOException("Broken 10"); + } + + @Override + public void flush() throws IOException { + throw new IOException("Broken 11"); + } - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - throw new IOException("Broken 12"); - } + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + throw new IOException("Broken 12"); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/Invoice.java b/src/test/java/org/yaml/snakeyaml/Invoice.java index 0e807751..213c161b 100644 --- a/src/test/java/org/yaml/snakeyaml/Invoice.java +++ b/src/test/java/org/yaml/snakeyaml/Invoice.java @@ -1,30 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.List; public class Invoice { - public Integer invoice; // invoice - public String date; // date - public Person billTo;// bill-to - public Person shipTo;// ship-to - public List<Product> product; - public Float tax; - public Float total; - public String comments; -}
\ No newline at end of file + public Integer invoice; // invoice + public String date; // date + public Person billTo;// bill-to + public Person shipTo;// ship-to + public List<Product> product; + public Float tax; + public Float total; + public String comments; + +} diff --git a/src/test/java/org/yaml/snakeyaml/JavaBeanTimeStampTest.java b/src/test/java/org/yaml/snakeyaml/JavaBeanTimeStampTest.java index 90a456ce..957d5375 100644 --- a/src/test/java/org/yaml/snakeyaml/JavaBeanTimeStampTest.java +++ b/src/test/java/org/yaml/snakeyaml/JavaBeanTimeStampTest.java @@ -1,61 +1,58 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.sql.Date; import java.sql.Timestamp; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions.FlowStyle; public class JavaBeanTimeStampTest extends TestCase { - public void testLoadDefaultJavaSqlTimestamp() { - JavaBeanWithSqlTimestamp javaBeanToDump = new JavaBeanWithSqlTimestamp(); - Timestamp stamp = new Timestamp(1000000000000L); - javaBeanToDump.setTimestamp(stamp); - Date date = new Date(1001376000000L); - javaBeanToDump.setDate(date); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String dumpStr = yaml.dump(javaBeanToDump); - assertEquals( - "!!org.yaml.snakeyaml.JavaBeanWithSqlTimestamp\ndate: 2001-09-25T00:00:00Z\ntimestamp: 2001-09-09T01:46:40Z\n", - dumpStr); - Yaml loader = new Yaml(); - JavaBeanWithSqlTimestamp javaBeanToLoad = loader.loadAs(dumpStr, - JavaBeanWithSqlTimestamp.class); - assertEquals(stamp, javaBeanToLoad.getTimestamp()); - assertEquals(date, javaBeanToLoad.getDate()); - } - public void testLoadDefaultJavaSqlTimestampNoGlobalTag() { - JavaBeanWithSqlTimestamp javaBeanToDump = new JavaBeanWithSqlTimestamp(); - Timestamp stamp = new Timestamp(1000000000000L); - javaBeanToDump.setTimestamp(stamp); - Date date = new Date(1001376000000L); - javaBeanToDump.setDate(date); - Yaml yaml = new Yaml(); - String dumpStr = yaml.dumpAsMap(javaBeanToDump); - assertEquals("date: 2001-09-25T00:00:00Z\ntimestamp: 2001-09-09T01:46:40Z\n", dumpStr); - Yaml loader = new Yaml(); - JavaBeanWithSqlTimestamp javaBeanToLoad = loader.loadAs(dumpStr, - JavaBeanWithSqlTimestamp.class); - assertEquals(stamp, javaBeanToLoad.getTimestamp()); - assertEquals(date, javaBeanToLoad.getDate()); - } + public void testLoadDefaultJavaSqlTimestamp() { + JavaBeanWithSqlTimestamp javaBeanToDump = new JavaBeanWithSqlTimestamp(); + Timestamp stamp = new Timestamp(1000000000000L); + javaBeanToDump.setTimestamp(stamp); + Date date = new Date(1001376000000L); + javaBeanToDump.setDate(date); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String dumpStr = yaml.dump(javaBeanToDump); + assertEquals( + "!!org.yaml.snakeyaml.JavaBeanWithSqlTimestamp\ndate: 2001-09-25T00:00:00Z\ntimestamp: 2001-09-09T01:46:40Z\n", + dumpStr); + Yaml loader = new Yaml(); + JavaBeanWithSqlTimestamp javaBeanToLoad = + loader.loadAs(dumpStr, JavaBeanWithSqlTimestamp.class); + assertEquals(stamp, javaBeanToLoad.getTimestamp()); + assertEquals(date, javaBeanToLoad.getDate()); + } + + public void testLoadDefaultJavaSqlTimestampNoGlobalTag() { + JavaBeanWithSqlTimestamp javaBeanToDump = new JavaBeanWithSqlTimestamp(); + Timestamp stamp = new Timestamp(1000000000000L); + javaBeanToDump.setTimestamp(stamp); + Date date = new Date(1001376000000L); + javaBeanToDump.setDate(date); + Yaml yaml = new Yaml(); + String dumpStr = yaml.dumpAsMap(javaBeanToDump); + assertEquals("date: 2001-09-25T00:00:00Z\ntimestamp: 2001-09-09T01:46:40Z\n", dumpStr); + Yaml loader = new Yaml(); + JavaBeanWithSqlTimestamp javaBeanToLoad = + loader.loadAs(dumpStr, JavaBeanWithSqlTimestamp.class); + assertEquals(stamp, javaBeanToLoad.getTimestamp()); + assertEquals(date, javaBeanToLoad.getDate()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValues.java b/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValues.java index 83b8d812..083b126a 100644 --- a/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValues.java +++ b/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValues.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -19,88 +17,88 @@ import java.sql.Timestamp; import java.util.Date; public class JavaBeanWithNullValues { - private String string; - private Integer integer; - private Float float1; - private Double double1; - private Long long1; - private Date date; - private java.sql.Date sqlDate; - private Timestamp timestamp; - private Boolean boolean1; - - public JavaBeanWithNullValues() { - } - - public String getString() { - return string; - } - - public void setString(String string) { - this.string = string; - } - - public Integer getInteger() { - return integer; - } - - public void setInteger(Integer integer) { - this.integer = integer; - } - - public Float getFloat1() { - return float1; - } - - public void setFloat1(Float float1) { - this.float1 = float1; - } - - public Double getDouble1() { - return double1; - } - - public void setDouble1(Double double1) { - this.double1 = double1; - } - - public Long getLong1() { - return long1; - } - - public void setLong1(Long long1) { - this.long1 = long1; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public java.sql.Date getSqlDate() { - return sqlDate; - } - - public void setSqlDate(java.sql.Date sqlDate) { - this.sqlDate = sqlDate; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - - public Boolean getBoolean1() { - return boolean1; - } - - public void setBoolean1(Boolean boolean1) { - this.boolean1 = boolean1; - } + + private String string; + private Integer integer; + private Float float1; + private Double double1; + private Long long1; + private Date date; + private java.sql.Date sqlDate; + private Timestamp timestamp; + private Boolean boolean1; + + public JavaBeanWithNullValues() {} + + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public Float getFloat1() { + return float1; + } + + public void setFloat1(Float float1) { + this.float1 = float1; + } + + public Double getDouble1() { + return double1; + } + + public void setDouble1(Double double1) { + this.double1 = double1; + } + + public Long getLong1() { + return long1; + } + + public void setLong1(Long long1) { + this.long1 = long1; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public java.sql.Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(java.sql.Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Timestamp getTimestamp() { + return timestamp; + } + + public void setTimestamp(Timestamp timestamp) { + this.timestamp = timestamp; + } + + public Boolean getBoolean1() { + return boolean1; + } + + public void setBoolean1(Boolean boolean1) { + this.boolean1 = boolean1; + } } diff --git a/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValuesTest.java b/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValuesTest.java index dc63f482..f8c4374c 100644 --- a/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValuesTest.java +++ b/src/test/java/org/yaml/snakeyaml/JavaBeanWithNullValuesTest.java @@ -1,187 +1,184 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.sql.Timestamp; import java.util.Date; - import junit.framework.TestCase; - import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; public class JavaBeanWithNullValuesTest extends TestCase { - private Yaml loader; - @Override - protected void setUp() { - loader = new Yaml(); + private Yaml loader; + + @Override + protected void setUp() { + loader = new Yaml(); + } + + public void testNotNull() { + String dumpStr = dumpJavaBeanWithNullValues(false); + // System.out.println(dumpStr); + Yaml yaml = new Yaml(); + JavaBeanWithNullValues parsed = yaml.load(dumpStr); + assertNotNull(parsed.getString()); + assertNotNull(parsed.getBoolean1()); + assertNotNull(parsed.getDate()); + assertNotNull(parsed.getDouble1()); + assertNotNull(parsed.getFloat1()); + assertNotNull(parsed.getInteger()); + assertNotNull(parsed.getLong1()); + assertNotNull(parsed.getSqlDate()); + assertNotNull(parsed.getTimestamp()); + // + parsed = loader.loadAs(dumpStr, JavaBeanWithNullValues.class); + assertNotNull(parsed.getString()); + assertNotNull(parsed.getBoolean1()); + assertNotNull(parsed.getDate()); + assertNotNull(parsed.getDouble1()); + assertNotNull(parsed.getFloat1()); + assertNotNull(parsed.getInteger()); + assertNotNull(parsed.getLong1()); + assertNotNull(parsed.getSqlDate()); + assertNotNull(parsed.getTimestamp()); + } + + public void testNull() { + String dumpStr = dumpJavaBeanWithNullValues(true); + Yaml yaml = new Yaml(); + JavaBeanWithNullValues parsed = yaml.load(dumpStr); + assertNull(parsed.getString()); + // + parsed = loader.loadAs(dumpStr, JavaBeanWithNullValues.class); + assertNull(parsed.getString()); + } + + public void testNullStringAndBoolean() { + JavaBeanWithNullValues javaBeanWithNullValues = new JavaBeanWithNullValues(); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setExplicitStart(true); + options.setExplicitEnd(true); + Yaml yaml = new Yaml(new CustomRepresenter(), options); + javaBeanWithNullValues.setBoolean1(null); + javaBeanWithNullValues.setDate(new Date(System.currentTimeMillis())); + javaBeanWithNullValues.setDouble1(1d); + javaBeanWithNullValues.setFloat1(1f); + javaBeanWithNullValues.setInteger(1); + javaBeanWithNullValues.setLong1(1L); + javaBeanWithNullValues.setSqlDate(new java.sql.Date(System.currentTimeMillis())); + javaBeanWithNullValues.setString(null); // ok + javaBeanWithNullValues.setTimestamp(new Timestamp(System.currentTimeMillis())); + + String dumpStr = yaml.dump(javaBeanWithNullValues); + // System.out.println(dumpStr); + yaml = new Yaml(); + JavaBeanWithNullValues parsed = yaml.load(dumpStr); + assertNull(" expect null, got " + parsed.getBoolean1(), parsed.getBoolean1()); + assertNull(" expect null, got " + parsed.getString(), parsed.getString()); + } + + public void testNoRootTag() { + JavaBeanWithNullValues javaBeanWithNullValues = new JavaBeanWithNullValues(); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setExplicitStart(true); + options.setExplicitEnd(true); + Yaml yaml = new Yaml(new CustomRepresenter(), options); + javaBeanWithNullValues.setBoolean1(null); + javaBeanWithNullValues.setDate(new Date(System.currentTimeMillis())); + javaBeanWithNullValues.setDouble1(1d); + javaBeanWithNullValues.setFloat1(1f); + javaBeanWithNullValues.setInteger(1); + javaBeanWithNullValues.setLong1(1L); + javaBeanWithNullValues.setSqlDate(new java.sql.Date(System.currentTimeMillis())); + javaBeanWithNullValues.setString(null); // ok + javaBeanWithNullValues.setTimestamp(new Timestamp(System.currentTimeMillis())); + + String dumpStr = yaml.dumpAsMap(javaBeanWithNullValues); + // System.out.println(dumpStr); + assertFalse("No explicit root tag must be used.", dumpStr.contains("JavaBeanWithNullValues")); + yaml = new Yaml(new CustomRepresenter(), options); + JavaBeanWithNullValues parsed = loader.loadAs(dumpStr, JavaBeanWithNullValues.class); + assertNull(" expect null, got " + parsed.getBoolean1(), parsed.getBoolean1()); + assertNull(" expect null, got " + parsed.getString(), parsed.getString()); + assertEquals(1d, parsed.getDouble1()); + assertEquals(1f, parsed.getFloat1()); + assertEquals(Integer.valueOf(1), parsed.getInteger()); + assertEquals(Long.valueOf(1L), parsed.getLong1()); + } + + private String dumpJavaBeanWithNullValues(boolean nullValues) { + JavaBeanWithNullValues javaBeanWithNullValues = new JavaBeanWithNullValues(); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setExplicitStart(true); + options.setExplicitEnd(true); + Yaml yaml = new Yaml(new CustomRepresenter(), options); + if (nullValues) { + return yaml.dump(javaBeanWithNullValues); } - - public void testNotNull() { - String dumpStr = dumpJavaBeanWithNullValues(false); - // System.out.println(dumpStr); - Yaml yaml = new Yaml(); - JavaBeanWithNullValues parsed = (JavaBeanWithNullValues) yaml.load(dumpStr); - assertNotNull(parsed.getString()); - assertNotNull(parsed.getBoolean1()); - assertNotNull(parsed.getDate()); - assertNotNull(parsed.getDouble1()); - assertNotNull(parsed.getFloat1()); - assertNotNull(parsed.getInteger()); - assertNotNull(parsed.getLong1()); - assertNotNull(parsed.getSqlDate()); - assertNotNull(parsed.getTimestamp()); - // - parsed = loader.loadAs(dumpStr, JavaBeanWithNullValues.class); - assertNotNull(parsed.getString()); - assertNotNull(parsed.getBoolean1()); - assertNotNull(parsed.getDate()); - assertNotNull(parsed.getDouble1()); - assertNotNull(parsed.getFloat1()); - assertNotNull(parsed.getInteger()); - assertNotNull(parsed.getLong1()); - assertNotNull(parsed.getSqlDate()); - assertNotNull(parsed.getTimestamp()); + javaBeanWithNullValues.setBoolean1(false); + javaBeanWithNullValues.setDate(new Date(System.currentTimeMillis())); + javaBeanWithNullValues.setDouble1(1d); + javaBeanWithNullValues.setFloat1(1f); + javaBeanWithNullValues.setInteger(1); + javaBeanWithNullValues.setLong1(1L); + javaBeanWithNullValues.setSqlDate(new java.sql.Date(System.currentTimeMillis())); + javaBeanWithNullValues.setString(""); // ok + javaBeanWithNullValues.setTimestamp(new Timestamp(System.currentTimeMillis())); + return yaml.dump(javaBeanWithNullValues); + } + + public class CustomRepresenter extends Representer { + + public CustomRepresenter() { + this.representers.put(Float.class, new RepresentFloat()); + this.representers.put(Long.class, new RepresentLong()); + this.representers.put(java.sql.Date.class, new RepresentDate()); + this.representers.put(java.sql.Timestamp.class, new RepresentTime()); } - public void testNull() { - String dumpStr = dumpJavaBeanWithNullValues(true); - Yaml yaml = new Yaml(); - JavaBeanWithNullValues parsed = (JavaBeanWithNullValues) yaml.load(dumpStr); - assertNull(parsed.getString()); - // - parsed = loader.loadAs(dumpStr, JavaBeanWithNullValues.class); - assertNull(parsed.getString()); - } + private class RepresentFloat implements Represent { - public void testNullStringAndBoolean() { - JavaBeanWithNullValues javaBeanWithNullValues = new JavaBeanWithNullValues(); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setExplicitStart(true); - options.setExplicitEnd(true); - Yaml yaml = new Yaml(new CustomRepresenter(), options); - javaBeanWithNullValues.setBoolean1(null); - javaBeanWithNullValues.setDate(new Date(System.currentTimeMillis())); - javaBeanWithNullValues.setDouble1(1d); - javaBeanWithNullValues.setFloat1(1f); - javaBeanWithNullValues.setInteger(1); - javaBeanWithNullValues.setLong1(1l); - javaBeanWithNullValues.setSqlDate(new java.sql.Date(System.currentTimeMillis())); - javaBeanWithNullValues.setString(null); // ok - javaBeanWithNullValues.setTimestamp(new Timestamp(System.currentTimeMillis())); - - String dumpStr = yaml.dump(javaBeanWithNullValues); - // System.out.println(dumpStr); - yaml = new Yaml(); - JavaBeanWithNullValues parsed = (JavaBeanWithNullValues) yaml.load(dumpStr); - assertNull(" expect null, got " + parsed.getBoolean1(), parsed.getBoolean1()); - assertNull(" expect null, got " + parsed.getString(), parsed.getString()); + public Node representData(Object data) { + return representScalar(new Tag(Tag.PREFIX + "java.lang.Float"), data.toString()); + } } - public void testNoRootTag() { - JavaBeanWithNullValues javaBeanWithNullValues = new JavaBeanWithNullValues(); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setExplicitStart(true); - options.setExplicitEnd(true); - Yaml yaml = new Yaml(new CustomRepresenter(), options); - javaBeanWithNullValues.setBoolean1(null); - javaBeanWithNullValues.setDate(new Date(System.currentTimeMillis())); - javaBeanWithNullValues.setDouble1(1d); - javaBeanWithNullValues.setFloat1(1f); - javaBeanWithNullValues.setInteger(1); - javaBeanWithNullValues.setLong1(1l); - javaBeanWithNullValues.setSqlDate(new java.sql.Date(System.currentTimeMillis())); - javaBeanWithNullValues.setString(null); // ok - javaBeanWithNullValues.setTimestamp(new Timestamp(System.currentTimeMillis())); - - String dumpStr = yaml.dumpAsMap(javaBeanWithNullValues); - // System.out.println(dumpStr); - assertFalse("No explicit root tag must be used.", - dumpStr.contains("JavaBeanWithNullValues")); - yaml = new Yaml(new CustomRepresenter(), options); - JavaBeanWithNullValues parsed = loader.loadAs(dumpStr, JavaBeanWithNullValues.class); - assertNull(" expect null, got " + parsed.getBoolean1(), parsed.getBoolean1()); - assertNull(" expect null, got " + parsed.getString(), parsed.getString()); - assertEquals(1d, parsed.getDouble1()); - assertEquals(1f, parsed.getFloat1()); - assertEquals(new Integer(1), parsed.getInteger()); - assertEquals(new Long(1l), parsed.getLong1()); + private class RepresentLong implements Represent { + + public Node representData(Object data) { + return representScalar(new Tag(Tag.PREFIX + "java.lang.Long"), ((Long) data).toString()); + } } - private String dumpJavaBeanWithNullValues(boolean nullValues) { - JavaBeanWithNullValues javaBeanWithNullValues = new JavaBeanWithNullValues(); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setExplicitStart(true); - options.setExplicitEnd(true); - Yaml yaml = new Yaml(new CustomRepresenter(), options); - if (nullValues) { - return yaml.dump(javaBeanWithNullValues); - } - javaBeanWithNullValues.setBoolean1(false); - javaBeanWithNullValues.setDate(new Date(System.currentTimeMillis())); - javaBeanWithNullValues.setDouble1(1d); - javaBeanWithNullValues.setFloat1(1f); - javaBeanWithNullValues.setInteger(1); - javaBeanWithNullValues.setLong1(1l); - javaBeanWithNullValues.setSqlDate(new java.sql.Date(System.currentTimeMillis())); - javaBeanWithNullValues.setString(""); // ok - javaBeanWithNullValues.setTimestamp(new Timestamp(System.currentTimeMillis())); - return yaml.dump(javaBeanWithNullValues); + private class RepresentDate implements Represent { + + public Node representData(Object data) { + return representScalar(new Tag(Tag.PREFIX + "java.sql.Date"), data.toString()); + } } - public class CustomRepresenter extends Representer { - public CustomRepresenter() { - this.representers.put(Float.class, new RepresentFloat()); - this.representers.put(Long.class, new RepresentLong()); - this.representers.put(java.sql.Date.class, new RepresentDate()); - this.representers.put(java.sql.Timestamp.class, new RepresentTime()); - } - - private class RepresentFloat implements Represent { - public Node representData(Object data) { - return representScalar(new Tag(Tag.PREFIX + "java.lang.Float"), - ((Float) data).toString()); - } - } - - private class RepresentLong implements Represent { - public Node representData(Object data) { - return representScalar(new Tag(Tag.PREFIX + "java.lang.Long"), - ((Long) data).toString()); - } - } - - private class RepresentDate implements Represent { - public Node representData(Object data) { - return representScalar(new Tag(Tag.PREFIX + "java.sql.Date"), - ((java.sql.Date) data).toString()); - } - } - - private class RepresentTime implements Represent { - public Node representData(Object data) { - return representScalar(new Tag(Tag.PREFIX + "java.sql.Timestamp"), - ((java.sql.Timestamp) data).toString()); - } - } + private class RepresentTime implements Represent { + + public Node representData(Object data) { + return representScalar(new Tag(Tag.PREFIX + "java.sql.Timestamp"), data.toString()); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/JavaBeanWithSqlTimestamp.java b/src/test/java/org/yaml/snakeyaml/JavaBeanWithSqlTimestamp.java index ae317689..95f35ca4 100644 --- a/src/test/java/org/yaml/snakeyaml/JavaBeanWithSqlTimestamp.java +++ b/src/test/java/org/yaml/snakeyaml/JavaBeanWithSqlTimestamp.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; public class JavaBeanWithSqlTimestamp { - private java.sql.Timestamp timestamp; - private java.sql.Date date; - public java.sql.Timestamp getTimestamp() { - return timestamp; - } + private java.sql.Timestamp timestamp; + private java.sql.Date date; - public void setTimestamp(java.sql.Timestamp timestamp) { - this.timestamp = timestamp; - } + public java.sql.Timestamp getTimestamp() { + return timestamp; + } - public java.sql.Date getDate() { - return date; - } + public void setTimestamp(java.sql.Timestamp timestamp) { + this.timestamp = timestamp; + } - public void setDate(java.sql.Date date) { - this.date = date; - } -}
\ No newline at end of file + public java.sql.Date getDate() { + return date; + } + + public void setDate(java.sql.Date date) { + this.date = date; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/Person.java b/src/test/java/org/yaml/snakeyaml/Person.java index 088130fd..ee860706 100644 --- a/src/test/java/org/yaml/snakeyaml/Person.java +++ b/src/test/java/org/yaml/snakeyaml/Person.java @@ -1,22 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; public class Person { - public String given; - public String family; - public Address address; -}
\ No newline at end of file + + public String given; + public String family; + public Address address; +} diff --git a/src/test/java/org/yaml/snakeyaml/Product.java b/src/test/java/org/yaml/snakeyaml/Product.java index badb80de..2715d63e 100644 --- a/src/test/java/org/yaml/snakeyaml/Product.java +++ b/src/test/java/org/yaml/snakeyaml/Product.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; public class Product { - public String sku; - public Integer quantity; - public String description; - public Float price; - @Override - public String toString() { - return "Product: " + sku; - } -}
\ No newline at end of file + public String sku; + public Integer quantity; + public String description; + public Float price; + + @Override + public String toString() { + return "Product: " + sku; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/PropertyUtilsSharingTest.java b/src/test/java/org/yaml/snakeyaml/PropertyUtilsSharingTest.java index 74eb4bac..a2f25719 100644 --- a/src/test/java/org/yaml/snakeyaml/PropertyUtilsSharingTest.java +++ b/src/test/java/org/yaml/snakeyaml/PropertyUtilsSharingTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import junit.framework.TestCase; - import org.junit.Test; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.introspector.PropertyUtils; @@ -24,45 +21,45 @@ import org.yaml.snakeyaml.representer.Representer; public class PropertyUtilsSharingTest extends TestCase { - public void testYamlDefaults() { - Yaml yaml1 = new Yaml(); - assertSame(yaml1.constructor.getPropertyUtils(), yaml1.representer.getPropertyUtils()); + public void testYamlDefaults() { + Yaml yaml1 = new Yaml(); + assertSame(yaml1.constructor.getPropertyUtils(), yaml1.representer.getPropertyUtils()); - Yaml yaml2 = new Yaml(new Constructor()); - assertSame(yaml2.constructor.getPropertyUtils(), yaml2.representer.getPropertyUtils()); + Yaml yaml2 = new Yaml(new Constructor()); + assertSame(yaml2.constructor.getPropertyUtils(), yaml2.representer.getPropertyUtils()); - Yaml yaml3 = new Yaml(new Representer()); - assertSame(yaml3.constructor.getPropertyUtils(), yaml3.representer.getPropertyUtils()); - } + Yaml yaml3 = new Yaml(new Representer()); + assertSame(yaml3.constructor.getPropertyUtils(), yaml3.representer.getPropertyUtils()); + } - public void testYamlConstructorWithPropertyUtils() { - Constructor constructor1 = new Constructor(); - PropertyUtils pu = new PropertyUtils(); - constructor1.setPropertyUtils(pu); - Yaml yaml = new Yaml(constructor1); - assertSame(pu, yaml.constructor.getPropertyUtils()); - assertSame(pu, yaml.representer.getPropertyUtils()); - } + public void testYamlConstructorWithPropertyUtils() { + Constructor constructor1 = new Constructor(); + PropertyUtils pu = new PropertyUtils(); + constructor1.setPropertyUtils(pu); + Yaml yaml = new Yaml(constructor1); + assertSame(pu, yaml.constructor.getPropertyUtils()); + assertSame(pu, yaml.representer.getPropertyUtils()); + } - public void testYamlRepresenterWithPropertyUtils() { - Representer representer2 = new Representer(); - PropertyUtils pu = new PropertyUtils(); - representer2.setPropertyUtils(pu); - Yaml yaml = new Yaml(representer2); - assertSame(pu, yaml.constructor.getPropertyUtils()); - assertSame(pu, yaml.representer.getPropertyUtils()); - } + public void testYamlRepresenterWithPropertyUtils() { + Representer representer2 = new Representer(); + PropertyUtils pu = new PropertyUtils(); + representer2.setPropertyUtils(pu); + Yaml yaml = new Yaml(representer2); + assertSame(pu, yaml.constructor.getPropertyUtils()); + assertSame(pu, yaml.representer.getPropertyUtils()); + } - @Test - public void testYamlConstructorANDRepresenterWithPropertyUtils() { - Constructor constructor = new Constructor(); - PropertyUtils pu_c = new PropertyUtils(); - constructor.setPropertyUtils(pu_c); - Representer representer = new Representer(); - PropertyUtils pu_r = new PropertyUtils(); - representer.setPropertyUtils(pu_r); - Yaml yaml = new Yaml(constructor, representer); - assertSame(pu_c, yaml.constructor.getPropertyUtils()); - assertSame(pu_r, yaml.representer.getPropertyUtils()); - } + @Test + public void testYamlConstructorANDRepresenterWithPropertyUtils() { + Constructor constructor = new Constructor(); + PropertyUtils pu_c = new PropertyUtils(); + constructor.setPropertyUtils(pu_c); + Representer representer = new Representer(); + PropertyUtils pu_r = new PropertyUtils(); + representer.setPropertyUtils(pu_r); + Yaml yaml = new Yaml(constructor, representer); + assertSame(pu_c, yaml.constructor.getPropertyUtils()); + assertSame(pu_r, yaml.representer.getPropertyUtils()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Suit.java b/src/test/java/org/yaml/snakeyaml/Suit.java index 8ae7f648..b504b0ca 100644 --- a/src/test/java/org/yaml/snakeyaml/Suit.java +++ b/src/test/java/org/yaml/snakeyaml/Suit.java @@ -1,20 +1,18 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; public enum Suit { - CLUBS, DIAMONDS, HEARTS, SPADES -}
\ No newline at end of file + CLUBS, DIAMONDS, HEARTS, SPADES +} diff --git a/src/test/java/org/yaml/snakeyaml/TypeDescriptionTest.java b/src/test/java/org/yaml/snakeyaml/TypeDescriptionTest.java index bb0e66b7..1a0d6d7c 100644 --- a/src/test/java/org/yaml/snakeyaml/TypeDescriptionTest.java +++ b/src/test/java/org/yaml/snakeyaml/TypeDescriptionTest.java @@ -1,39 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import junit.framework.TestCase; - import org.yaml.snakeyaml.constructor.ArrayTagsTest.CarWithArray; import org.yaml.snakeyaml.nodes.Tag; public class TypeDescriptionTest extends TestCase { - public void testSetTag() { - TypeDescription descr = new TypeDescription(TypeDescriptionTest.class); - descr.setTag("!bla"); - assertEquals(new Tag("!bla"), descr.getTag()); - descr.setTag(new Tag("!foo")); - assertEquals(new Tag("!foo"), descr.getTag()); - } + public void testSetTag() { + TypeDescription descr = new TypeDescription(TypeDescriptionTest.class); + descr.setTag("!bla"); + assertEquals(new Tag("!bla"), descr.getTag()); + descr.setTag(new Tag("!foo")); + assertEquals(new Tag("!foo"), descr.getTag()); + } - public void testToString() { - TypeDescription carDescription = new TypeDescription(CarWithArray.class, "!car"); - assertEquals( - "TypeDescription for class org.yaml.snakeyaml.constructor.ArrayTagsTest$CarWithArray (tag='!car')", - carDescription.toString()); - } + public void testToString() { + TypeDescription carDescription = new TypeDescription(CarWithArray.class, "!car"); + assertEquals( + "TypeDescription for class org.yaml.snakeyaml.constructor.ArrayTagsTest$CarWithArray (tag='!car')", + carDescription.toString()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/Util.java b/src/test/java/org/yaml/snakeyaml/Util.java index 61d9fc32..b07659c4 100644 --- a/src/test/java/org/yaml/snakeyaml/Util.java +++ b/src/test/java/org/yaml/snakeyaml/Util.java @@ -1,54 +1,61 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; public class Util { - public static String getLocalResource(String theName) { - try { - InputStream input; - input = YamlDocument.class.getClassLoader().getResourceAsStream(theName); - if (input == null) { - throw new RuntimeException("Can not find " + theName); - } - BufferedInputStream is = new BufferedInputStream(input); - StringBuilder buf = new StringBuilder(3000); - int i; - try { - while ((i = is.read()) != -1) { - buf.append((char) i); - } - } finally { - is.close(); - } - String resource = buf.toString(); - // convert EOLs - String[] lines = resource.split("\\r?\\n"); - StringBuilder buffer = new StringBuilder(); - for (int j = 0; j < lines.length; j++) { - buffer.append(lines[j]); - buffer.append("\n"); - } - return buffer.toString(); - } catch (IOException e) { - throw new RuntimeException(e); + public static String getLocalResource(String theName) { + try { + InputStream input; + input = YamlDocument.class.getClassLoader().getResourceAsStream(theName); + if (input == null) { + throw new RuntimeException("Can not find " + theName); + } + BufferedInputStream is = new BufferedInputStream(input); + StringBuilder buf = new StringBuilder(3000); + int i; + try { + while ((i = is.read()) != -1) { + buf.append((char) i); } + } finally { + is.close(); + } + String resource = buf.toString(); + // convert EOLs + String[] lines = resource.split("\\r?\\n"); + StringBuilder buffer = new StringBuilder(); + for (int j = 0; j < lines.length; j++) { + buffer.append(lines[j]); + buffer.append("\n"); + } + return buffer.toString(); + } catch (IOException e) { + throw new RuntimeException(e); } + } + + public static boolean compareAllLines(String text1, String text2) { + Set<String> split1 = new HashSet<String>(Arrays.asList(text1.trim().split("\n"))); + Set<String> split2 = new HashSet<String>(Arrays.asList(text2.trim().split("\n"))); + return split1.containsAll(split2) && split2.containsAll(split1); + } } diff --git a/src/test/java/org/yaml/snakeyaml/YamlComposeTest.java b/src/test/java/org/yaml/snakeyaml/YamlComposeTest.java index c6ac0479..a1896a75 100644 --- a/src/test/java/org/yaml/snakeyaml/YamlComposeTest.java +++ b/src/test/java/org/yaml/snakeyaml/YamlComposeTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.io.StringReader; - import junit.framework.TestCase; - import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeId; @@ -26,43 +22,43 @@ import org.yaml.snakeyaml.nodes.ScalarNode; public class YamlComposeTest extends TestCase { - public void testComposeManyDocuments() { - try { - Yaml yaml = new Yaml(); - yaml.compose(new StringReader("abc: 56\n---\n123\n---\n456")); - fail("YAML contans more then one document."); - } catch (Exception e) { - assertTrue("<<<" + e.getMessage() + ">>>", - e.getMessage().startsWith("expected a single document in the stream")); - } + public void testComposeManyDocuments() { + try { + Yaml yaml = new Yaml(); + yaml.compose(new StringReader("abc: 56\n---\n123\n---\n456")); + fail("YAML contans more then one document."); + } catch (Exception e) { + assertTrue("<<<" + e.getMessage() + ">>>", + e.getMessage().startsWith("expected a single document in the stream")); } + } - public void testComposeFromReader() { - Yaml yaml = new Yaml(); - MappingNode node = (MappingNode) yaml.compose(new StringReader("abc: 56")); - ScalarNode node1 = (ScalarNode) node.getValue().get(0).getKeyNode(); - assertEquals("abc", node1.getValue()); - ScalarNode node2 = (ScalarNode) node.getValue().get(0).getValueNode(); - assertEquals("56", node2.getValue()); - } + public void testComposeFromReader() { + Yaml yaml = new Yaml(); + MappingNode node = (MappingNode) yaml.compose(new StringReader("abc: 56")); + ScalarNode node1 = (ScalarNode) node.getValue().get(0).getKeyNode(); + assertEquals("abc", node1.getValue()); + ScalarNode node2 = (ScalarNode) node.getValue().get(0).getValueNode(); + assertEquals("56", node2.getValue()); + } - public void testComposeAllFromReader() { - Yaml yaml = new Yaml(); - boolean first = true; - for (Node node : yaml.composeAll(new StringReader("abc: 56\n---\n123\n---\n456"))) { - if (first) { - assertEquals(NodeId.mapping, node.getNodeId()); - } else { - assertEquals(NodeId.scalar, node.getNodeId()); - } - first = false; - } + public void testComposeAllFromReader() { + Yaml yaml = new Yaml(); + boolean first = true; + for (Node node : yaml.composeAll(new StringReader("abc: 56\n---\n123\n---\n456"))) { + if (first) { + assertEquals(NodeId.mapping, node.getNodeId()); + } else { + assertEquals(NodeId.scalar, node.getNodeId()); + } + first = false; } + } - public void testComposeAllOneDocument() { - Yaml yaml = new Yaml(); - for (Node node : yaml.composeAll(new StringReader("6"))) { - assertEquals(NodeId.scalar, node.getNodeId()); - } + public void testComposeAllOneDocument() { + Yaml yaml = new Yaml(); + for (Node node : yaml.composeAll(new StringReader("6"))) { + assertEquals(NodeId.scalar, node.getNodeId()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/YamlDocument.java b/src/test/java/org/yaml/snakeyaml/YamlDocument.java index fbf5104e..d8824c65 100644 --- a/src/test/java/org/yaml/snakeyaml/YamlDocument.java +++ b/src/test/java/org/yaml/snakeyaml/YamlDocument.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -20,60 +18,60 @@ import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; - +import java.nio.charset.StandardCharsets; import org.yaml.snakeyaml.constructor.Constructor; public class YamlDocument { - public static final String ROOT = "specification/"; - private String source; - private String presentation; - private Object nativeData; - public YamlDocument(String sourceName, boolean check, Constructor constructor) { - InputStream input = YamlDocument.class.getClassLoader().getResourceAsStream( - ROOT + sourceName); - if (constructor == null) { - constructor = new Constructor(); - } - Yaml yaml = new Yaml(constructor); - nativeData = yaml.load(input); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - Charset charset = Charset.forName("UTF-8"); - yaml.dump(nativeData, new OutputStreamWriter(output, charset)); - try { - presentation = output.toString(charset.name()); - source = Util.getLocalResource(ROOT + sourceName); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - // try to read generated presentation to prove that the presentation - // is identical to the source - Object result = yaml.load(presentation); - if (check && !nativeData.equals(result)) { - throw new RuntimeException("Generated presentation is not valid: " + presentation); - } - } + public static final String ROOT = "specification/"; + private final String source; + private final String presentation; + private final Object nativeData; - public YamlDocument(String sourceName, boolean check) { - this(sourceName, check, null); + public YamlDocument(String sourceName, boolean check, Constructor constructor) { + InputStream input = YamlDocument.class.getClassLoader().getResourceAsStream(ROOT + sourceName); + if (constructor == null) { + constructor = new Constructor(); } - - public YamlDocument(String sourceName) { - this(sourceName, true); + Yaml yaml = new Yaml(constructor); + nativeData = yaml.load(input); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Charset charset = StandardCharsets.UTF_8; + yaml.dump(nativeData, new OutputStreamWriter(output, charset)); + try { + presentation = output.toString(charset.name()); + source = Util.getLocalResource(ROOT + sourceName); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); } - - public String getSource() { - return source; + // try to read generated presentation to prove that the presentation + // is identical to the source + Object result = yaml.load(presentation); + if (check && !nativeData.equals(result)) { + throw new RuntimeException("Generated presentation is not valid: " + presentation); } + } - public String getPresentation() { - return presentation; - } + public YamlDocument(String sourceName, boolean check) { + this(sourceName, check, null); + } + + public YamlDocument(String sourceName) { + this(sourceName, true); + } + + public String getSource() { + return source; + } + + public String getPresentation() { + return presentation; + } - public Object getNativeData() { - if (nativeData == null) { - throw new NullPointerException("No object is parsed."); - } - return nativeData; + public Object getNativeData() { + if (nativeData == null) { + throw new NullPointerException("No object is parsed."); } + return nativeData; + } } diff --git a/src/test/java/org/yaml/snakeyaml/YamlParseTest.java b/src/test/java/org/yaml/snakeyaml/YamlParseTest.java index 4de8db47..db40588d 100644 --- a/src/test/java/org/yaml/snakeyaml/YamlParseTest.java +++ b/src/test/java/org/yaml/snakeyaml/YamlParseTest.java @@ -1,80 +1,77 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.io.StringReader; import java.util.HashMap; import java.util.Iterator; -import java.util.Map; - import junit.framework.TestCase; - -import org.yaml.snakeyaml.events.*; -import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.events.DocumentEndEvent; +import org.yaml.snakeyaml.events.DocumentStartEvent; +import org.yaml.snakeyaml.events.Event; +import org.yaml.snakeyaml.events.ImplicitTuple; +import org.yaml.snakeyaml.events.ScalarEvent; +import org.yaml.snakeyaml.events.StreamEndEvent; +import org.yaml.snakeyaml.events.StreamStartEvent; public class YamlParseTest extends TestCase { - public void testParse() { - Yaml yaml = new Yaml(); - Event e = null; - int counter = 0; - for (Event event : yaml.parse(new StringReader("abc: 56"))) { - if (e == null) { - assertTrue(event instanceof StreamStartEvent); - } - e = event; - counter++; - } - assertTrue(e instanceof StreamEndEvent); - assertEquals(8, counter); + public void testParse() { + Yaml yaml = new Yaml(); + Event e = null; + int counter = 0; + for (Event event : yaml.parse(new StringReader("abc: 56"))) { + if (e == null) { + assertTrue(event instanceof StreamStartEvent); + } + e = event; + counter++; } + assertTrue(e instanceof StreamEndEvent); + assertEquals(8, counter); + } - public void testParseEvents() { - Yaml yaml = new Yaml(); - Iterator<Event> events = yaml.parse(new StringReader("%YAML 1.1\n---\na")).iterator(); - assertTrue(events.next() instanceof StreamStartEvent); - DocumentStartEvent documentStartEvent = (DocumentStartEvent) events.next(); - assertTrue(documentStartEvent.getExplicit()); - assertEquals(DumperOptions.Version.V1_1, documentStartEvent.getVersion()); - Map<String, String> DEFAULT_TAGS = new HashMap<String, String>(); - DEFAULT_TAGS.put("!", "!"); - DEFAULT_TAGS.put("!!", Tag.PREFIX); - assertEquals(DEFAULT_TAGS, documentStartEvent.getTags()); - ScalarEvent scalarEvent = (ScalarEvent) events.next(); - assertNull(scalarEvent.getAnchor()); - assertNull(scalarEvent.getTag()); - assertEquals(new ImplicitTuple(true, false).toString(), scalarEvent.getImplicit().toString()); - DocumentEndEvent documentEndEvent = (DocumentEndEvent) events.next(); - assertFalse(documentEndEvent.getExplicit()); - assertTrue("Unexpected event.", events.next() instanceof StreamEndEvent); - assertFalse(events.hasNext()); - } + public void testParseEvents() { + Yaml yaml = new Yaml(); + Iterator<Event> events = yaml.parse(new StringReader("%YAML 1.1\n---\na")).iterator(); + assertTrue(events.next() instanceof StreamStartEvent); + DocumentStartEvent documentStartEvent = (DocumentStartEvent) events.next(); + assertTrue(documentStartEvent.getExplicit()); + assertEquals(DumperOptions.Version.V1_1, documentStartEvent.getVersion()); + assertEquals(new HashMap<String, String>(), documentStartEvent.getTags()); + ScalarEvent scalarEvent = (ScalarEvent) events.next(); + assertNull(scalarEvent.getAnchor()); + assertNull(scalarEvent.getTag()); + assertEquals(new ImplicitTuple(true, false).toString(), scalarEvent.getImplicit().toString()); + DocumentEndEvent documentEndEvent = (DocumentEndEvent) events.next(); + assertFalse(documentEndEvent.getExplicit()); + assertTrue("Unexpected event.", events.next() instanceof StreamEndEvent); + assertFalse(events.hasNext()); + } - public void testParseManyDocuments() { - Yaml yaml = new Yaml(); - Event e = null; - int counter = 0; - for (Event event : yaml.parse(new StringReader("abc: 56\n---\n4\n---\nqwe\n"))) { - if (e == null) { - assertTrue(event instanceof StreamStartEvent); - } - e = event; - counter++; - } - assertTrue(e instanceof StreamEndEvent); - assertEquals(14, counter); + public void testParseManyDocuments() { + Yaml yaml = new Yaml(); + Event e = null; + int counter = 0; + for (Event event : yaml.parse(new StringReader("abc: 56\n---\n4\n---\nqwe\n"))) { + if (e == null) { + assertTrue(event instanceof StreamStartEvent); + } + e = event; + counter++; } + assertTrue(e instanceof StreamEndEvent); + assertEquals(14, counter); + } } diff --git a/src/test/java/org/yaml/snakeyaml/YamlStream.java b/src/test/java/org/yaml/snakeyaml/YamlStream.java index 1ccd4e7e..df5d3e55 100644 --- a/src/test/java/org/yaml/snakeyaml/YamlStream.java +++ b/src/test/java/org/yaml/snakeyaml/YamlStream.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; @@ -23,73 +21,72 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; - import junit.framework.AssertionFailedError; public class YamlStream { - private List<Object> nativeData = new ArrayList<Object>(); - public YamlStream(String sourceName) { - InputStream input = YamlDocument.class.getClassLoader().getResourceAsStream( - YamlDocument.ROOT + sourceName); - Yaml yaml = new Yaml(); - for (Object document : yaml.loadAll(input)) { - nativeData.add(document); - } - ByteArrayOutputStream output = new ByteArrayOutputStream(); - yaml.dumpAll(nativeData.iterator(), new OutputStreamWriter(output)); - String presentation; - try { - presentation = output.toString("UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - // try to read generated presentation to prove that the presentation - // is identical to the source - List<Object> parsedNativeData = new ArrayList<Object>(); - for (Object document : yaml.loadAll(presentation)) { - parsedNativeData.add(document); - } - if (nativeData.getClass() != parsedNativeData.getClass()) { - throw new AssertionFailedError("Different class: " + parsedNativeData.getClass()); - } - if (nativeData.size() != parsedNativeData.size()) { - throw new AssertionFailedError("Different size."); - } - Iterator<Object> piterator = parsedNativeData.iterator(); - Iterator<Object> niterator = nativeData.iterator(); - while (piterator.hasNext()) { - Object obj1 = niterator.next(); - Object obj2 = piterator.next(); - if (obj1 instanceof Map) { - @SuppressWarnings("unchecked") - Map<Object, Object> map1 = (Map<Object, Object>) obj1; - @SuppressWarnings("unchecked") - Map<Object, Object> map2 = (Map<Object, Object>) obj2; - if (!map1.keySet().equals(map2.keySet())) { - throw new AssertionFailedError("Keyset: " + map1.keySet() + "; but was: " - + map2.keySet()); - } - for (Iterator<Object> iterator = map1.keySet().iterator(); iterator.hasNext();) { - Object key = iterator.next(); - Object o1 = map1.get(key); - Object o2 = map2.get(key); - if (!o1.equals(o2)) { - throw new AssertionFailedError("Values: " + o1 + "; but was: " + o2); - } - } - } - if (!obj1.equals(obj2)) { - throw new AssertionFailedError("Expected: " + obj1 + "; but was: " + obj2); - } + private final List<Object> nativeData = new ArrayList<Object>(); + + public YamlStream(String sourceName) { + InputStream input = + YamlDocument.class.getClassLoader().getResourceAsStream(YamlDocument.ROOT + sourceName); + Yaml yaml = new Yaml(); + for (Object document : yaml.loadAll(input)) { + nativeData.add(document); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + yaml.dumpAll(nativeData.iterator(), new OutputStreamWriter(output)); + String presentation; + try { + presentation = output.toString("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + // try to read generated presentation to prove that the presentation + // is identical to the source + List<Object> parsedNativeData = new ArrayList<Object>(); + for (Object document : yaml.loadAll(presentation)) { + parsedNativeData.add(document); + } + if (nativeData.getClass() != parsedNativeData.getClass()) { + throw new AssertionFailedError("Different class: " + parsedNativeData.getClass()); + } + if (nativeData.size() != parsedNativeData.size()) { + throw new AssertionFailedError("Different size."); + } + Iterator<Object> piterator = parsedNativeData.iterator(); + Iterator<Object> niterator = nativeData.iterator(); + while (piterator.hasNext()) { + Object obj1 = niterator.next(); + Object obj2 = piterator.next(); + if (obj1 instanceof Map) { + @SuppressWarnings("unchecked") + Map<Object, Object> map1 = (Map<Object, Object>) obj1; + @SuppressWarnings("unchecked") + Map<Object, Object> map2 = (Map<Object, Object>) obj2; + if (!map1.keySet().equals(map2.keySet())) { + throw new AssertionFailedError( + "Keyset: " + map1.keySet() + "; but was: " + map2.keySet()); } - if (!parsedNativeData.equals(nativeData)) { - throw new AssertionFailedError("Generated presentation is not the same: " - + presentation); + for (Iterator<Object> iterator = map1.keySet().iterator(); iterator.hasNext();) { + Object key = iterator.next(); + Object o1 = map1.get(key); + Object o2 = map2.get(key); + if (!o1.equals(o2)) { + throw new AssertionFailedError("Values: " + o1 + "; but was: " + o2); + } } + } + if (!obj1.equals(obj2)) { + throw new AssertionFailedError("Expected: " + obj1 + "; but was: " + obj2); + } } - - public List<Object> getNativeData() { - return nativeData; + if (!parsedNativeData.equals(nativeData)) { + throw new AssertionFailedError("Generated presentation is not the same: " + presentation); } + } + + public List<Object> getNativeData() { + return nativeData; + } } diff --git a/src/test/java/org/yaml/snakeyaml/YamlTest.java b/src/test/java/org/yaml/snakeyaml/YamlTest.java index 8f71b66b..1ecc5d03 100644 --- a/src/test/java/org/yaml/snakeyaml/YamlTest.java +++ b/src/test/java/org/yaml/snakeyaml/YamlTest.java @@ -1,74 +1,71 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml; import java.util.Iterator; - import junit.framework.TestCase; - import org.yaml.snakeyaml.error.YAMLException; public class YamlTest extends TestCase { - public void testSetNoName() { - Yaml yaml = new Yaml(); - assertTrue(yaml.toString().matches("Yaml:\\d+")); - } + public void testSetNoName() { + Yaml yaml = new Yaml(); + assertTrue(yaml.toString().matches("Yaml:\\d+")); + } - public void testSetName() { - Yaml yaml = new Yaml(); - yaml.setName("REST"); - assertEquals("REST", yaml.getName()); - assertEquals("REST", yaml.toString()); - } + public void testSetName() { + Yaml yaml = new Yaml(); + yaml.setName("REST"); + assertEquals("REST", yaml.getName()); + assertEquals("REST", yaml.toString()); + } - /** - * Check that documents are parsed only when they are asked to be loaded. - */ - public void testOneDocument() { - Yaml yaml = new Yaml(); - String doc = "--- a\n--- [:]"; - Iterator<Object> loaded = yaml.loadAll(doc).iterator(); - assertTrue(loaded.hasNext()); - Object obj1 = loaded.next(); - assertEquals("a", obj1); - assertTrue(loaded.hasNext()); - try { - loaded.next(); - fail("Second document is invalid"); - } catch (Exception e) { - assertEquals("while parsing a flow node\n" + " in 'reader', line 2, column 6:\n" - + " --- [:]\n" + " ^\n" - + "expected the node content, but found Value\n" - + " in 'reader', line 2, column 6:\n" + " --- [:]\n" + " ^\n", - e.getMessage()); - } + /** + * Check that documents are parsed only when they are asked to be loaded. + */ + public void testOneDocument() { + Yaml yaml = new Yaml(); + String doc = "--- a\n--- [:]"; + Iterator<Object> loaded = yaml.loadAll(doc).iterator(); + assertTrue(loaded.hasNext()); + Object obj1 = loaded.next(); + assertEquals("a", obj1); + assertTrue(loaded.hasNext()); + try { + loaded.next(); + fail("Second document is invalid"); + } catch (Exception e) { + assertEquals( + "while parsing a flow node\n" + " in 'reader', line 2, column 6:\n" + " --- [:]\n" + + " ^\n" + "expected the node content, but found ':'\n" + + " in 'reader', line 2, column 6:\n" + " --- [:]\n" + " ^\n", + e.getMessage()); } + } - public void testOnlyOneDocument() { - Yaml yaml = new Yaml(); - String doc = "--- a\n--- b"; - try { - yaml.load(doc); - fail("It must be only one document."); - } catch (YAMLException e) { - assertEquals("expected a single document in the stream\n" - + " in 'string', line 1, column 5:\n" + " --- a\n" + " ^\n" - + "but found another document\n" + " in 'string', line 2, column 1:\n" - + " --- b\n" + " ^\n", e.getMessage()); - } + public void testOnlyOneDocument() { + Yaml yaml = new Yaml(); + String doc = "--- a\n--- b"; + try { + yaml.load(doc); + fail("It must be only one document."); + } catch (YAMLException e) { + assertEquals( + "expected a single document in the stream\n" + " in 'string', line 1, column 5:\n" + + " --- a\n" + " ^\n" + "but found another document\n" + + " in 'string', line 2, column 1:\n" + " --- b\n" + " ^\n", + e.getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/BooleanArr.java b/src/test/java/org/yaml/snakeyaml/array/BooleanArr.java index e4659500..5fab0c29 100644 --- a/src/test/java/org/yaml/snakeyaml/array/BooleanArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/BooleanArr.java @@ -1,41 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; public class BooleanArr { - private boolean[] bools; - public BooleanArr() { - } + private boolean[] bools; - public BooleanArr(boolean[] bools) { - this.bools = bools; - } + public BooleanArr() {} - public String toString() { - return Arrays.toString(bools); - } + public BooleanArr(boolean[] bools) { + this.bools = bools; + } - public boolean[] getBools() { - return bools; - } + public String toString() { + return Arrays.toString(bools); + } - public void setBools(boolean[] bools) { - this.bools = bools; - } + public boolean[] getBools() { + return bools; + } + + public void setBools(boolean[] bools) { + this.bools = bools; + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/ByteArr.java b/src/test/java/org/yaml/snakeyaml/array/ByteArr.java index bf8aac50..050db315 100644 --- a/src/test/java/org/yaml/snakeyaml/array/ByteArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/ByteArr.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; @@ -19,24 +17,23 @@ import java.util.Arrays; public class ByteArr { - private byte[] bytes; + private byte[] bytes; - public ByteArr() { - } + public ByteArr() {} - public ByteArr(byte[] bytes) { - this.bytes = bytes; - } + public ByteArr(byte[] bytes) { + this.bytes = bytes; + } - public String toString() { - return Arrays.toString(bytes); - } + public String toString() { + return Arrays.toString(bytes); + } - public byte[] getBytes() { - return bytes; - } + public byte[] getBytes() { + return bytes; + } - public void setBytes(byte[] bytes) { - this.bytes = bytes; - } + public void setBytes(byte[] bytes) { + this.bytes = bytes; + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/CharArr.java b/src/test/java/org/yaml/snakeyaml/array/CharArr.java index 7f309ee2..e5cc9951 100644 --- a/src/test/java/org/yaml/snakeyaml/array/CharArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/CharArr.java @@ -1,41 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; public class CharArr { - private char[] chars; - public CharArr() { - } + private char[] chars; - public CharArr(char[] chars) { - this.chars = chars; - } + public CharArr() {} - public String toString() { - return Arrays.toString(chars); - } + public CharArr(char[] chars) { + this.chars = chars; + } - public char[] getChars() { - return chars; - } + public String toString() { + return Arrays.toString(chars); + } - public void setChars(char[] chars) { - this.chars = chars; - } + public char[] getChars() { + return chars; + } + + public void setChars(char[] chars) { + this.chars = chars; + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/DoubleArr.java b/src/test/java/org/yaml/snakeyaml/array/DoubleArr.java index 6b134a36..98e6bf1b 100644 --- a/src/test/java/org/yaml/snakeyaml/array/DoubleArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/DoubleArr.java @@ -1,41 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; public class DoubleArr { - private double[] doubles; - public DoubleArr() { - } + private double[] doubles; - public DoubleArr(double[] doubles) { - this.doubles = doubles; - } + public DoubleArr() {} - public String toString() { - return Arrays.toString(doubles); - } + public DoubleArr(double[] doubles) { + this.doubles = doubles; + } - public double[] getDoubles() { - return doubles; - } + public String toString() { + return Arrays.toString(doubles); + } - public void setDoubles(double[] doubles) { - this.doubles = doubles; - } + public double[] getDoubles() { + return doubles; + } + + public void setDoubles(double[] doubles) { + this.doubles = doubles; + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/FloatArr.java b/src/test/java/org/yaml/snakeyaml/array/FloatArr.java index 01f5338d..24aa5cdb 100644 --- a/src/test/java/org/yaml/snakeyaml/array/FloatArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/FloatArr.java @@ -1,41 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; public class FloatArr { - private float[] floats; - public FloatArr() { - } + private float[] floats; - public FloatArr(float[] floats) { - this.floats = floats; - } + public FloatArr() {} - public String toString() { - return Arrays.toString(floats); - } + public FloatArr(float[] floats) { + this.floats = floats; + } - public float[] getFloats() { - return floats; - } + public String toString() { + return Arrays.toString(floats); + } - public void setFloats(float[] floats) { - this.floats = floats; - } + public float[] getFloats() { + return floats; + } + + public void setFloats(float[] floats) { + this.floats = floats; + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/IntArr.java b/src/test/java/org/yaml/snakeyaml/array/IntArr.java index 8ed8e2a9..e4c6d77d 100644 --- a/src/test/java/org/yaml/snakeyaml/array/IntArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/IntArr.java @@ -1,41 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; public class IntArr { - private int[] ints; - public IntArr() { - } + private int[] ints; - public IntArr(int[] ints) { - this.ints = ints; - } + public IntArr() {} - public String toString() { - return Arrays.toString(ints); - } + public IntArr(int[] ints) { + this.ints = ints; + } - public int[] getInts() { - return ints; - } + public String toString() { + return Arrays.toString(ints); + } - public void setInts(int[] ints) { - this.ints = ints; - } + public int[] getInts() { + return ints; + } + + public void setInts(int[] ints) { + this.ints = ints; + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/LongArr.java b/src/test/java/org/yaml/snakeyaml/array/LongArr.java index c20adfe3..80fa2834 100644 --- a/src/test/java/org/yaml/snakeyaml/array/LongArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/LongArr.java @@ -1,41 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; public class LongArr { - private long[] longs; - public LongArr() { - } + private long[] longs; - public LongArr(long[] longs) { - this.longs = longs; - } + public LongArr() {} - public String toString() { - return Arrays.toString(longs); - } + public LongArr(long[] longs) { + this.longs = longs; + } - public long[] getLongs() { - return longs; - } + public String toString() { + return Arrays.toString(longs); + } - public void setLongs(long[] longs) { - this.longs = longs; - } + public long[] getLongs() { + return longs; + } + + public void setLongs(long[] longs) { + this.longs = longs; + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/PrimitiveArrayTest.java b/src/test/java/org/yaml/snakeyaml/array/PrimitiveArrayTest.java index 09b1d532..e54d4d06 100644 --- a/src/test/java/org/yaml/snakeyaml/array/PrimitiveArrayTest.java +++ b/src/test/java/org/yaml/snakeyaml/array/PrimitiveArrayTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; import java.util.List; - import junit.framework.TestCase; - import org.junit.Assert; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.ConstructorException; @@ -27,229 +23,231 @@ import org.yaml.snakeyaml.error.YAMLException; public class PrimitiveArrayTest extends TestCase { - private final String pkg = "!!org.yaml.snakeyaml.array"; - - private final byte[] bytes = new byte[] { 1, 2, 3 }; - private final short[] shorts = new short[] { 300, 301, 302 }; - private final int[] ints = new int[] { 40000, 40001, 40002 }; - private final long[] longs = new long[] { 5000000000L, 5000000001L }; - private final float[] floats = new float[] { 0.1f, 3.1415f }; - private final double[] doubles = new double[] { 50.0001, 2150.0002 }; - private final char[] chars = new char[] { 'a', 'b', 'c', 'd', 'e' }; - private final boolean[] bools = new boolean[] { true, false }; - - public void testValidConstructor() { - String testInput = "- " + pkg + ".ByteArr [ " + Arrays.toString(bytes) + " ]\n" + "- " - + pkg + ".ShortArr [ " + Arrays.toString(shorts) + " ]\n" + "- " + pkg - + ".IntArr [ " + Arrays.toString(ints) + " ]\n" + "- " + pkg + ".LongArr [ " - + Arrays.toString(longs) + " ]\n" + "- " + pkg + ".FloatArr [ " - + Arrays.toString(floats) + " ]\n" + "- " + pkg + ".DoubleArr [ " - + Arrays.toString(doubles) + " ]\n" + "- " + pkg + ".CharArr [ " - + Arrays.toString(chars) + " ]\n" + "- " + pkg + ".BooleanArr [ " - + Arrays.toString(bools) + " ]\n"; - - Yaml yaml = new Yaml(); - List<Object> wrappers = (List<Object>) yaml.load(testInput); - - Assert.assertArrayEquals(bytes, ((ByteArr) wrappers.get(0)).getBytes()); - Assert.assertArrayEquals(shorts, ((ShortArr) wrappers.get(1)).getShorts()); - Assert.assertArrayEquals(ints, ((IntArr) wrappers.get(2)).getInts()); - Assert.assertArrayEquals(longs, ((LongArr) wrappers.get(3)).getLongs()); - Assert.assertArrayEquals(floats, ((FloatArr) wrappers.get(4)).getFloats(), 0.001f); - Assert.assertArrayEquals(doubles, ((DoubleArr) wrappers.get(5)).getDoubles(), 0.001); - Assert.assertArrayEquals(chars, ((CharArr) wrappers.get(6)).getChars()); - assertArrayEquals(bools, ((BooleanArr) wrappers.get(7)).getBools()); - } - - /* - * For some reason, every other assertArrayEquals specialization is provided - * by org.junit.Assert, but not this one. - */ - private void assertArrayEquals(boolean[] expected, boolean[] actuals) { - assertEquals("Arrays differ in length", expected.length, actuals.length); - for (int i = 0; i < expected.length; ++i) { - if (expected[i] != actuals[i]) { - fail("Arrays first differ at " + i + "; expected " + expected[i] + " but got " - + actuals[i]); - } - } - } - - private void tryInvalid(String t, Class<?> expectedException) { - Yaml yaml = new Yaml(); - try { - Object loaded = yaml.load(t); - fail("Expected " + expectedException.getCanonicalName() + " but loaded = \"" + loaded - + "\""); - } catch (YAMLException e) { - assertEquals(expectedException, e.getCause().getClass()); - } - } - - public void testInvalidConstructors() { - // Loading a character as any primitive other than 'char' is a - // NumberFormatException - tryInvalid(pkg + ".ByteArr [ [ 'a' ] ]", NumberFormatException.class); - tryInvalid(pkg + ".ShortArr [ [ 'a' ] ]", NumberFormatException.class); - tryInvalid(pkg + ".IntArr [ [ 'a' ] ]", NumberFormatException.class); - tryInvalid(pkg + ".LongArr [ [ 'a' ] ]", NumberFormatException.class); - tryInvalid(pkg + ".FloatArr [ [ 'a' ] ]", NumberFormatException.class); - tryInvalid(pkg + ".DoubleArr [ [ 'a' ] ]", NumberFormatException.class); - - // Exception: because of how boolean construction works, constructing a - // boolean from 'a' - // results in null. - tryInvalid(pkg + ".BooleanArr [ [ 'a' ] ]", NullPointerException.class); - - // Loading a floating-point number as a character is a YAMLException - tryInvalid(pkg + ".CharArr [ [ 1.2 ] ]", YAMLException.class); - - // Loading a String as a Character is a YAMLException - tryInvalid(pkg + ".CharArr [ [ 'abcd' ] ]", YAMLException.class); - + private final String pkg = "!!org.yaml.snakeyaml.array"; + + private final byte[] bytes = new byte[] {1, 2, 3}; + private final short[] shorts = new short[] {300, 301, 302}; + private final int[] ints = new int[] {40000, 40001, 40002}; + private final long[] longs = new long[] {5000000000L, 5000000001L}; + private final float[] floats = new float[] {0.1f, 3.1415f}; + private final double[] doubles = new double[] {50.0001, 2150.0002}; + private final char[] chars = new char[] {'a', 'b', 'c', 'd', 'e'}; + private final boolean[] bools = new boolean[] {true, false}; + + public void testValidConstructor() { + String testInput = "- " + pkg + ".ByteArr [ " + Arrays.toString(bytes) + " ]\n" + "- " + pkg + + ".ShortArr [ " + Arrays.toString(shorts) + " ]\n" + "- " + pkg + ".IntArr [ " + + Arrays.toString(ints) + " ]\n" + "- " + pkg + ".LongArr [ " + Arrays.toString(longs) + + " ]\n" + "- " + pkg + ".FloatArr [ " + Arrays.toString(floats) + " ]\n" + "- " + pkg + + ".DoubleArr [ " + Arrays.toString(doubles) + " ]\n" + "- " + pkg + ".CharArr [ " + + Arrays.toString(chars) + " ]\n" + "- " + pkg + ".BooleanArr [ " + Arrays.toString(bools) + + " ]\n"; + + Yaml yaml = new Yaml(); + List<Object> wrappers = yaml.load(testInput); + + Assert.assertArrayEquals(bytes, ((ByteArr) wrappers.get(0)).getBytes()); + Assert.assertArrayEquals(shorts, ((ShortArr) wrappers.get(1)).getShorts()); + Assert.assertArrayEquals(ints, ((IntArr) wrappers.get(2)).getInts()); + Assert.assertArrayEquals(longs, ((LongArr) wrappers.get(3)).getLongs()); + Assert.assertArrayEquals(floats, ((FloatArr) wrappers.get(4)).getFloats(), 0.001f); + Assert.assertArrayEquals(doubles, ((DoubleArr) wrappers.get(5)).getDoubles(), 0.001); + Assert.assertArrayEquals(chars, ((CharArr) wrappers.get(6)).getChars()); + assertArrayEquals(bools, ((BooleanArr) wrappers.get(7)).getBools()); + } + + /* + * For some reason, every other assertArrayEquals specialization is provided by org.junit.Assert, + * but not this one. + */ + private void assertArrayEquals(boolean[] expected, boolean[] actuals) { + assertEquals("Arrays differ in length", expected.length, actuals.length); + for (int i = 0; i < expected.length; ++i) { + if (expected[i] != actuals[i]) { + fail( + "Arrays first differ at " + i + "; expected " + expected[i] + " but got " + actuals[i]); + } } - - public void testTruncation() { - // Loading floating-point numbers as integer types is disallowed, - // because that's a number-format problem. - tryInvalid(pkg + ".ByteArr [ [ 3.14 ] ]", NumberFormatException.class); - tryInvalid(pkg + ".ShortArr [ [ 3.14 ] ]", NumberFormatException.class); - tryInvalid(pkg + ".IntArr [ [ 3.14 ] ]", NumberFormatException.class); - tryInvalid(pkg + ".LongArr [ [ 3.14 ] ]", NumberFormatException.class); + } + + private void tryInvalid(String t, Class<?> expectedException) { + Yaml yaml = new Yaml(); + try { + Object loaded = yaml.load(t); + fail("Expected " + expectedException.getCanonicalName() + " but loaded = \"" + loaded + "\""); + } catch (YAMLException e) { + assertEquals(expectedException, e.getCause().getClass()); } - - public void testPromotion() { - Yaml yaml = new Yaml(); - - // Loading integer numbers as floating-point types is allowed... - Assert.assertArrayEquals(new float[] { 3, 5 }, - ((FloatArr) yaml.load(pkg + ".FloatArr [ [ 3, 5 ] ] ")).getFloats(), 0.001f); - - Assert.assertArrayEquals(new double[] { 3, 5 }, - ((DoubleArr) yaml.load(pkg + ".DoubleArr [ [ 3, 5 ] ] ")).getDoubles(), 0.001f); + } + + public void testInvalidConstructors() { + // Loading a character as any primitive other than 'char' is a + // NumberFormatException + tryInvalid(pkg + ".ByteArr [ [ 'a' ] ]", NumberFormatException.class); + tryInvalid(pkg + ".ShortArr [ [ 'a' ] ]", NumberFormatException.class); + tryInvalid(pkg + ".IntArr [ [ 'a' ] ]", NumberFormatException.class); + tryInvalid(pkg + ".LongArr [ [ 'a' ] ]", NumberFormatException.class); + tryInvalid(pkg + ".FloatArr [ [ 'a' ] ]", NumberFormatException.class); + tryInvalid(pkg + ".DoubleArr [ [ 'a' ] ]", NumberFormatException.class); + + // Exception: because of how boolean construction works, constructing a + // boolean from 'a' + // results in null. + tryInvalid(pkg + ".BooleanArr [ [ 'a' ] ]", NullPointerException.class); + + // Loading a floating-point number as a character is a YAMLException + tryInvalid(pkg + ".CharArr [ [ 1.2 ] ]", YAMLException.class); + + // Loading a String as a Character is a YAMLException + tryInvalid(pkg + ".CharArr [ [ 'abcd' ] ]", YAMLException.class); + + } + + public void testTruncation() { + // Loading floating-point numbers as integer types is disallowed, + // because that's a number-format problem. + tryInvalid(pkg + ".ByteArr [ [ 3.14 ] ]", NumberFormatException.class); + tryInvalid(pkg + ".ShortArr [ [ 3.14 ] ]", NumberFormatException.class); + tryInvalid(pkg + ".IntArr [ [ 3.14 ] ]", NumberFormatException.class); + tryInvalid(pkg + ".LongArr [ [ 3.14 ] ]", NumberFormatException.class); + } + + public void testPromotion() { + Yaml yaml = new Yaml(); + + // Loading integer numbers as floating-point types is allowed... + Assert.assertArrayEquals(new float[] {3, 5}, + ((FloatArr) yaml.load(pkg + ".FloatArr [ [ 3, 5 ] ] ")).getFloats(), 0.001f); + + Assert.assertArrayEquals(new double[] {3, 5}, + ((DoubleArr) yaml.load(pkg + ".DoubleArr [ [ 3, 5 ] ] ")).getDoubles(), 0.001f); + } + + public void testStringCharArray() { + Yaml yaml = new Yaml(); + + try { + yaml.load(pkg + ".CharArr [ [ abcd ] ]"); + fail("Expected exception."); + } catch (Exception e) { + assertEquals(ConstructorException.class, e.getClass()); + assertEquals("Invalid node Character: 'abcd'; length: 4", e.getCause().getMessage()); } - - public void testStringCharArray() { - Yaml yaml = new Yaml(); - - try { - yaml.load(pkg + ".CharArr [ [ abcd ] ]"); - fail("Expected exception."); - } catch (Exception e) { - assertEquals(ConstructorException.class, e.getClass()); - assertEquals("Invalid node Character: 'abcd'; length: 4", e.getCause().getMessage()); - } + } + + private static Object cycle(Object in) { + Yaml yaml = new Yaml(); + String dumped = yaml.dump(in); + // System.out.println ( dumped ); + return yaml.load(dumped); + } + + /** + * All kinds of primitive arrays should be able to cycle from (Java array) to (YAML string) to + * (Java array) again, and they should be exactly the same before and after. + */ + public void testCycle() { + ByteArr byteArr = new ByteArr(bytes); + Assert.assertArrayEquals(byteArr.getBytes(), ((ByteArr) cycle(byteArr)).getBytes()); + + ShortArr shortArr = new ShortArr(shorts); + Assert.assertArrayEquals(shortArr.getShorts(), ((ShortArr) cycle(shortArr)).getShorts()); + + IntArr intArr = new IntArr(ints); + Assert.assertArrayEquals(intArr.getInts(), ((IntArr) cycle(intArr)).getInts()); + + LongArr longArr = new LongArr(longs); + Assert.assertArrayEquals(longArr.getLongs(), ((LongArr) cycle(longArr)).getLongs()); + + FloatArr floatArr = new FloatArr(floats); + Assert.assertArrayEquals(floatArr.getFloats(), ((FloatArr) cycle(floatArr)).getFloats(), + 0.001f); + + DoubleArr doubleArr = new DoubleArr(doubles); + Assert.assertArrayEquals(doubleArr.getDoubles(), ((DoubleArr) cycle(doubleArr)).getDoubles(), + 0.001); + + CharArr charArr = new CharArr(chars); + Assert.assertArrayEquals(charArr.getChars(), ((CharArr) cycle(charArr)).getChars()); + + BooleanArr boolArr = new BooleanArr(bools); + assertArrayEquals(boolArr.getBools(), ((BooleanArr) cycle(boolArr)).getBools()); + } + + public void testMultiDimensional() { + Array2D two = new Array2D(); + two.setLongs(new long[][] {{1, 2, 3}, {4, 5, 6}}); + assertTrue(Arrays.deepEquals(two.getLongs(), ((Array2D) cycle(two)).getLongs())); + + Array3D three = new Array3D(); + three.setLongs( + new long[][][] {{{1, 2, 3, 4}, {5, 6, 7, 8}}, {{9, 10, 11, 12}, {13, 14, 15, 16}}}); + assertTrue(Arrays.deepEquals(three.getLongs(), ((Array3D) cycle(three)).getLongs())); + + // Object with an array of Objects which each have an array of + // primitives. + ArrayLongArr four = new ArrayLongArr(); + four.setContents( + new LongArr[] {new LongArr(new long[] {1, 2, 3, 4}), new LongArr(new long[] {5, 6, 7, 8})}); + Object result = cycle(four); + assertEquals(four, result); + } + + public static class Array2D { + + private long[][] longs; + + public long[][] getLongs() { + return longs; } - private static Object cycle(Object in) { - Yaml yaml = new Yaml(); - String dumped = yaml.dump(in); - // System.out.println ( dumped ); - return yaml.load(dumped); + public void setLongs(long[][] longs) { + this.longs = longs; } + } - /** - * All kinds of primitive arrays should be able to cycle from (Java array) - * to (YAML string) to (Java array) again, and they should be exactly the - * same before and after. - */ - public void testCycle() { - ByteArr byteArr = new ByteArr(bytes); - Assert.assertArrayEquals(byteArr.getBytes(), ((ByteArr) cycle(byteArr)).getBytes()); - - ShortArr shortArr = new ShortArr(shorts); - Assert.assertArrayEquals(shortArr.getShorts(), ((ShortArr) cycle(shortArr)).getShorts()); - - IntArr intArr = new IntArr(ints); - Assert.assertArrayEquals(intArr.getInts(), ((IntArr) cycle(intArr)).getInts()); + public static class Array3D { - LongArr longArr = new LongArr(longs); - Assert.assertArrayEquals(longArr.getLongs(), ((LongArr) cycle(longArr)).getLongs()); + private long[][][] longs; - FloatArr floatArr = new FloatArr(floats); - Assert.assertArrayEquals(floatArr.getFloats(), ((FloatArr) cycle(floatArr)).getFloats(), - 0.001f); - - DoubleArr doubleArr = new DoubleArr(doubles); - Assert.assertArrayEquals(doubleArr.getDoubles(), - ((DoubleArr) cycle(doubleArr)).getDoubles(), 0.001); - - CharArr charArr = new CharArr(chars); - Assert.assertArrayEquals(charArr.getChars(), ((CharArr) cycle(charArr)).getChars()); - - BooleanArr boolArr = new BooleanArr(bools); - assertArrayEquals(boolArr.getBools(), ((BooleanArr) cycle(boolArr)).getBools()); + public long[][][] getLongs() { + return longs; } - public void testMultiDimensional() { - Array2D two = new Array2D(); - two.setLongs(new long[][] { { 1, 2, 3 }, { 4, 5, 6 } }); - assertTrue(Arrays.deepEquals(two.getLongs(), ((Array2D) cycle(two)).getLongs())); - - Array3D three = new Array3D(); - three.setLongs(new long[][][] { { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }, - { { 9, 10, 11, 12 }, { 13, 14, 15, 16 } } }); - assertTrue(Arrays.deepEquals(three.getLongs(), ((Array3D) cycle(three)).getLongs())); - - // Object with an array of Objects which each have an array of - // primitives. - ArrayLongArr four = new ArrayLongArr(); - four.setContents(new LongArr[] { new LongArr(new long[] { 1, 2, 3, 4 }), - new LongArr(new long[] { 5, 6, 7, 8 }) }); - Object result = cycle(four); - assertEquals(four, (ArrayLongArr) result); + public void setLongs(long[][][] longs) { + this.longs = longs; } + } - public static class Array2D { - private long[][] longs; + public static class ArrayLongArr { - public long[][] getLongs() { - return longs; - } + private LongArr[] contents; - public void setLongs(long[][] longs) { - this.longs = longs; - } + public LongArr[] getContents() { + return contents; } - public static class Array3D { - private long[][][] longs; - - public long[][][] getLongs() { - return longs; - } - - public void setLongs(long[][][] longs) { - this.longs = longs; - } + public void setContents(LongArr[] contents) { + this.contents = contents; } - public static class ArrayLongArr { - private LongArr[] contents; - - public LongArr[] getContents() { - return contents; - } - - public void setContents(LongArr[] contents) { - this.contents = contents; + @Override + public boolean equals(Object obj) { + if (!(obj instanceof ArrayLongArr)) { + return false; + } + + ArrayLongArr other = ((ArrayLongArr) obj); + if (contents.length != other.getContents().length) { + return false; + } + for (int i = 0; i < contents.length; ++i) { + if (!Arrays.equals(contents[i].getLongs(), other.getContents()[i].getLongs())) { + return false; } + } - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ArrayLongArr)) - return false; - - ArrayLongArr other = ((ArrayLongArr) obj); - if (contents.length != other.getContents().length) - return false; - for (int i = 0; i < contents.length; ++i) { - if (!Arrays.equals(contents[i].getLongs(), other.getContents()[i].getLongs())) { - return false; - } - } - - return true; - } + return true; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/array/ShortArr.java b/src/test/java/org/yaml/snakeyaml/array/ShortArr.java index bd09bbf2..548dcab6 100644 --- a/src/test/java/org/yaml/snakeyaml/array/ShortArr.java +++ b/src/test/java/org/yaml/snakeyaml/array/ShortArr.java @@ -1,41 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.array; import java.util.Arrays; public class ShortArr { - private short[] shorts; - public ShortArr() { - } + private short[] shorts; - public ShortArr(short[] shorts) { - this.shorts = shorts; - } + public ShortArr() {} - public String toString() { - return Arrays.toString(shorts); - } + public ShortArr(short[] shorts) { + this.shorts = shorts; + } - public short[] getShorts() { - return shorts; - } + public String toString() { + return Arrays.toString(shorts); + } - public void setShorts(short[] shorts) { - this.shorts = shorts; - } + public short[] getShorts() { + return shorts; + } + + public void setShorts(short[] shorts) { + this.shorts = shorts; + } } diff --git a/src/test/java/org/yaml/snakeyaml/comment/ComposerWithCommentEnabledTest.java b/src/test/java/org/yaml/snakeyaml/comment/ComposerWithCommentEnabledTest.java new file mode 100644 index 00000000..353631a3 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/comment/ComposerWithCommentEnabledTest.java @@ -0,0 +1,592 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comment; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.comments.CommentLine; +import org.yaml.snakeyaml.composer.Composer; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.SequenceNode; +import org.yaml.snakeyaml.parser.ParserImpl; +import org.yaml.snakeyaml.reader.StreamReader; +import org.yaml.snakeyaml.resolver.Resolver; + +public class ComposerWithCommentEnabledTest { + + private final boolean DEBUG = false; + + private void printBlockComment(Node node, int level, PrintStream out) { + if (node.getBlockComments() != null) { + List<CommentLine> blockComments = node.getBlockComments(); + for (int i = 0; i < blockComments.size(); i++) { + printWithIndent("Block Comment", level, out); + } + } + } + + private void printEndComment(Node node, int level, PrintStream out) { + if (node.getEndComments() != null) { + List<CommentLine> endComments = node.getEndComments(); + for (int i = 0; i < endComments.size(); i++) { + printWithIndent("End Comment", level, out); + } + } + } + + private void printInLineComment(Node node, int level, PrintStream out) { + if (node.getInLineComments() != null) { + List<CommentLine> inLineComments = node.getInLineComments(); + for (int i = 0; i < inLineComments.size(); i++) { + printWithIndent("InLine Comment", level + 1, out); + } + } + } + + private void printWithIndent(String line, int level, PrintStream out) { + for (int ix = 0; ix < level; ix++) { + out.print(" "); + } + out.print(line); + out.print("\n"); + } + + private void printNodeInternal(Node node, int level, PrintStream out) { + + if (node instanceof MappingNode) { + MappingNode mappingNode = (MappingNode) node; + printBlockComment(mappingNode, level, out); + printWithIndent(mappingNode.getClass().getSimpleName(), level, out); + for (NodeTuple childNodeTuple : mappingNode.getValue()) { + printWithIndent("Tuple", level + 1, out); + printNodeInternal(childNodeTuple.getKeyNode(), level + 2, out); + printNodeInternal(childNodeTuple.getValueNode(), level + 2, out); + } + printInLineComment(mappingNode, level, out); + printEndComment(mappingNode, level, out); + + } else if (node instanceof SequenceNode) { + SequenceNode sequenceNode = (SequenceNode) node; + printBlockComment(sequenceNode, level, out); + printWithIndent(sequenceNode.getClass().getSimpleName(), level, out); + for (Node childNode : sequenceNode.getValue()) { + printNodeInternal(childNode, level + 1, out); + } + printInLineComment(sequenceNode, level, out); + printEndComment(sequenceNode, level, out); + + } else if (node instanceof ScalarNode) { + ScalarNode scalarNode = (ScalarNode) node; + printBlockComment(scalarNode, level, out); + printWithIndent(scalarNode.getClass().getSimpleName() + ": " + scalarNode.getValue(), level, + out); + printInLineComment(scalarNode, level, out); + printEndComment(scalarNode, level, out); + + } else { + printBlockComment(node, level, out); + printWithIndent(node.getClass().getSimpleName(), level, out); + printInLineComment(node, level, out); + printEndComment(node, level, out); + } + } + + private void printNodeList(List<Node> nodeList) { + if (DEBUG) { + System.out.println("BEGIN"); + boolean first = true; + for (Node node : nodeList) { + if (first) { + first = false; + } else { + System.out.println("---"); + } + printNodeInternal(node, 1, System.out); + } + System.out.println("DONE\n"); + } + } + + private List<Node> getNodeList(Composer composer) { + List<Node> nodeList = new ArrayList<>(); + while (composer.checkNode()) { + nodeList.add(composer.getNode()); + } + return nodeList; + } + + private void assertNodesEqual(String[] expected, List<Node> nodeList) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + boolean first = true; + try (PrintStream out = new PrintStream(baos)) { + for (Node node : nodeList) { + if (first) { + first = false; + } else { + out.print("---\n"); + } + printNodeInternal(node, 0, out); + } + } + String actualString = baos.toString(); + String[] actuals = actualString.split("\n"); + for (int ix = 0; ix < Math.min(expected.length, actuals.length); ix++) { + assertEquals(expected[ix], actuals[ix]); + } + assertEquals(expected.length, actuals.length); + } + + public Composer newComposerWithCommentsEnabled(String data) { + return new Composer(new ParserImpl(new StreamReader(data), true), new Resolver()); + } + + @Test + public void testEmpty() { + String data = ""; + String[] expected = new String[] { // + "" // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testParseWithOnlyComment() { + String data = "# Comment"; + String[] expected = new String[] { // + "Block Comment", // + "MappingNode", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testCommentEndingALine() { + String data = "" + // + "key: # Comment\n" + // + " value\n"; + + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " ScalarNode: key", // + " InLine Comment", // + " ScalarNode: value" // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testMultiLineComment() { + String data = "" + // + "key: # Comment\n" + // + " # lines\n" + // + " value\n" + // + "\n"; + + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " ScalarNode: key", // + " InLine Comment", // + " InLine Comment", // + " ScalarNode: value", // + "End Comment" // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testBlankLine() { + String data = "" + // + "\n"; + + String[] expected = new String[] { // + "Block Comment", // + "MappingNode", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testBlankLineComments() { + String data = "" + // + "\n" + // + "abc: def # commment\n" + // + "\n" + // + "\n"; + + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " Block Comment", // + " ScalarNode: abc", // + " ScalarNode: def", // + " InLine Comment", // + "End Comment", // + "End Comment", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void test_blockScalar() { + String data = "" + // + "abc: > # Comment\n" + // + " def\n" + // + " hij\n" + // + "\n"; + + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " ScalarNode: abc", // + " InLine Comment", // + " ScalarNode: def hij" // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testDirectiveLineEndComment() { + String data = "%YAML 1.1 #Comment\n"; + + String[] expected = new String[] { // + "" // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testSequence() { + String data = "" + // + "# Comment\n" + // + "list: # InlineComment1\n" + // + "# Block Comment\n" + // + "- item # InlineComment2\n" + // + "# Comment\n"; + + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " Block Comment", // + " ScalarNode: list", // + " InLine Comment", // + " SequenceNode", // + " Block Comment", // + " ScalarNode: item", // + " InLine Comment", // + "End Comment" // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testAllComments1() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "key: # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + " # Block Comment3a\n" + // + " # Block Comment3b\n" + // + " value # Inline Comment2\n" + // + "# Block Comment4\n" + // + "list: # InlineComment3a\n" + // + " # InlineComment3b\n" + // + "# Block Comment5\n" + // + "- item1 # InlineComment4\n" + // + "- item2: [ value2a, value2b ] # InlineComment5\n" + // + "- item3: { key3a: [ value3a1, value3a2 ], key3b: value3b } # InlineComment6\n" + // + "# Block Comment6\n" + // + "---\n" + // + "# Block Comment7\n" + // + ""; + + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " Block Comment", // + " Block Comment", // + " ScalarNode: key", // + " InLine Comment", // + " InLine Comment", // + " Block Comment", // + " Block Comment", // + " ScalarNode: value", // + " InLine Comment", // + " Tuple", // + " Block Comment", // + " ScalarNode: list", // + " InLine Comment", // + " InLine Comment", // + " SequenceNode", // + " Block Comment", // + " ScalarNode: item1", // + " InLine Comment", // + " MappingNode", // + " Tuple", // + " ScalarNode: item2", // + " SequenceNode", // + " ScalarNode: value2a", // + " ScalarNode: value2b", // + " InLine Comment", // + " MappingNode", // + " Tuple", // + " ScalarNode: item3", // + " MappingNode", // + " Tuple", // + " ScalarNode: key3a", // + " SequenceNode", // + " ScalarNode: value3a1", // + " ScalarNode: value3a2", // + " Tuple", // + " ScalarNode: key3b", // + " ScalarNode: value3b", // + " InLine Comment", // + "End Comment", // + "---", // + "Block Comment", // + "ScalarNode: ", // This is an empty scalar created as this is an empty document + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testAllComments2() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "- item1 # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + "# Block Comment3a\n" + // + "# Block Comment3b\n" + // + "- item2: value # Inline Comment2\n" + // + "# Block Comment4\n" + // + ""; + + String[] expected = new String[] { // + "SequenceNode", // + " Block Comment", // + " Block Comment", // + " ScalarNode: item1", // + " InLine Comment", // + " InLine Comment", // + " MappingNode", // + " Tuple", // + " Block Comment", // + " Block Comment", // + " ScalarNode: item2", // + " ScalarNode: value", // + " InLine Comment", // + "End Comment", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testAllComments3() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "[ item1, item2: value2, {item3: value3} ] # Inline Comment1\n" + // + "# Block Comment2\n" + // + ""; + + String[] expected = new String[] { // + "Block Comment", // + "SequenceNode", // + " ScalarNode: item1", // + " MappingNode", // + " Tuple", // + " ScalarNode: item2", // + " ScalarNode: value2", // + " MappingNode", // + " Tuple", // + " ScalarNode: item3", // + " ScalarNode: value3", // + " InLine Comment", // + "End Comment", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = getNodeList(sut); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testGetSingleNode() { + String data = "" + // + "\n" + // + "abc: def # commment\n" + // + "\n" + // + "\n"; + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " Block Comment", " ScalarNode: abc", // + " ScalarNode: def", // + " InLine Comment", // + "End Comment", // + "End Comment", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = Collections.singletonList(sut.getSingleNode()); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + @Test + public void testGetSingleNodeHeaderComment() { + String data = "" + // + "\n" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "abc: def # commment\n" + // + "\n" + // + "\n"; + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " Block Comment", // + " Block Comment", // + " Block Comment", // + " ScalarNode: abc", // + " ScalarNode: def", // + " InLine Comment", // + "End Comment", // + "End Comment", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = Collections.singletonList(sut.getSingleNode()); + + printNodeList(result); + assertNodesEqual(expected, result); + } + + private static class TestConstructor extends SafeConstructor { + + } + + @Test + public void testBaseConstructorGetData() { + String data = "" + // + "\n" + // + "abc: def # commment\n" + // + "\n" + // + "\n"; + + TestConstructor sut = new TestConstructor(); + sut.setComposer(newComposerWithCommentsEnabled(data)); + Object result = sut.getData(); + assertTrue(result instanceof LinkedHashMap); + @SuppressWarnings("unchecked") + LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result; + assertEquals(1, map.size()); + assertEquals(map.get("abc"), "def"); + } + + @Test + public void testEmptyEntryInMap() { + String data = "userProps:\n" + // + "#password\n" + // + "pass: mySecret\n"; + String[] expected = new String[] { // + "MappingNode", // + " Tuple", // + " ScalarNode: userProps", // + " ScalarNode: ", // + " Tuple", // + " Block Comment", // + " ScalarNode: pass", // + " ScalarNode: mySecret", // + }; + + Composer sut = newComposerWithCommentsEnabled(data); + List<Node> result = Collections.singletonList(sut.getSingleNode()); + + printNodeList(result); + assertNodesEqual(expected, result); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/comment/EmitterWithCommentEnabledTest.java b/src/test/java/org/yaml/snakeyaml/comment/EmitterWithCommentEnabledTest.java new file mode 100644 index 00000000..5eda36c4 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/comment/EmitterWithCommentEnabledTest.java @@ -0,0 +1,498 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comment; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.StringWriter; +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.DumperOptions.ScalarStyle; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.comments.CommentType; +import org.yaml.snakeyaml.composer.Composer; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.emitter.Emitter; +import org.yaml.snakeyaml.events.CommentEvent; +import org.yaml.snakeyaml.events.DocumentEndEvent; +import org.yaml.snakeyaml.events.DocumentStartEvent; +import org.yaml.snakeyaml.events.ImplicitTuple; +import org.yaml.snakeyaml.events.MappingEndEvent; +import org.yaml.snakeyaml.events.MappingStartEvent; +import org.yaml.snakeyaml.events.ScalarEvent; +import org.yaml.snakeyaml.events.SequenceEndEvent; +import org.yaml.snakeyaml.events.SequenceStartEvent; +import org.yaml.snakeyaml.events.StreamEndEvent; +import org.yaml.snakeyaml.events.StreamStartEvent; +import org.yaml.snakeyaml.parser.ParserImpl; +import org.yaml.snakeyaml.reader.StreamReader; +import org.yaml.snakeyaml.representer.Representer; +import org.yaml.snakeyaml.resolver.Resolver; +import org.yaml.snakeyaml.serializer.Serializer; + +public class EmitterWithCommentEnabledTest { + + private String runEmitterWithCommentsEnabled(String data) throws IOException { + StringWriter output = new StringWriter(); + + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.PLAIN); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setProcessComments(true); + Serializer serializer = + new Serializer(new Emitter(output, options), new Resolver(), options, null); + + serializer.open(); + Composer composer = new Composer(new ParserImpl(new StreamReader(data), true), new Resolver()); + while (composer.checkNode()) { + serializer.serialize(composer.getNode()); + } + serializer.close(); + + return output.toString(); + } + + private Emitter producePrettyFlowEmitter(StringWriter output) { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.PLAIN); + options.setDefaultFlowStyle(FlowStyle.FLOW); + options.setProcessComments(true); + options.setPrettyFlow(true); + return new Emitter(output, options); + } + + @Test + public void testEmpty() throws Exception { + String data = ""; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testWithOnlyComment() throws Exception { + String data = "# Comment\n\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testCommentEndingALine() throws Exception { + String data = "" + // + "key: # Comment\n" + // + " value\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testMultiLineComment() throws Exception { + String data = "" + // + "key: # Comment\n" + // + " # lines\n" + // + " value\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testBlankLine() throws Exception { + String data = "" + // + "\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testBlankLineComments() throws Exception { + String data = "" + // + "\n" + // + "abc: def # comment\n" + // + "\n" + // + "\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testBlockScalar() throws Exception { + String data = "" + // + "abc: | # Comment\n" + // + " def\n" + // + " hij\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testDirectiveLineEndComment() throws Exception { + String data = "%YAML 1.1 #Comment\n"; + + String result = runEmitterWithCommentsEnabled(data); + // We currently strip Directive comments + assertEquals("", result); + } + + @Test + public void testSequence() throws Exception { + String data = "" + // + "# Comment\n" + // + "list: # InlineComment1\n" + // + " - # Block Comment\n" + // + " item # InlineComment2\n" + // + "# Comment\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testAllComments1() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "key: # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + " # Block Comment3a\n" + // + " # Block Comment3b\n" + // + " value # Inline Comment2\n" + // + "# Block Comment4\n" + // + "list: # InlineComment3a\n" + // + " # InlineComment3b\n" + // + " - # Block Comment5\n" + // + " item1 # InlineComment4\n" + // + " - item2: [value2a, value2b] # InlineComment5\n" + // + " - item3: {key3a: [value3a1, value3a2], key3b: value3b} # InlineComment6\n" + // + "# Block Comment6\n" + // + "---\n" + // + "# Block Comment7\n" + // + ""; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testMultiDoc() throws Exception { + String data = "" + // + "key: value\n" + // + "# Block Comment\n" + // + "---\n" + // + "# Block Comment\n" + // + "key: value\n" + // + ""; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testAllComments2() throws Exception { + String data = "" + // + "key:\n" + " key:\n" + " key:\n" + " - # Block Comment1\n" + " item1a\n" + + " - # Block Comment2\n" + " - item1b\n" + " - # Block Comment3\n" + + " MapKey_1: MapValue1\n" + " MapKey_2: MapValue2\n" + "key2:\n" + + "- # Block Comment4\n" + // + " # Block Comment5\n" + // + " item1 # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + "- # Block Comment6a\n" + // + " # Block Comment6b\n" + // + " item2: value # Inline Comment2\n" + // + "# Block Comment7\n" + // + ""; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testAllComments3() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "[item1, {item2: value2}, {item3: value3}] # Inline Comment1\n" + // + "# Block Comment2\n" + // + ""; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testKeepingNewLineInsideSequence() throws Exception { + String data = "" + "\n" + "key:\n" + + // " \n" + // only supported in a sequence right now + "- item1\n" + + // "\n" + // Per Spec this is part of plain scalar above + "- item2\n" + + // "\n" + // Per Spec this is part of plain scalar above + "- item3\n" + "\n" + "key2: value2\n" + "\n" + "key3: value3\n" + "\n" + ""; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testKeepingNewLineInsideSequence2() throws Exception { + String data = "" + "apiVersion: kustomize.config.k8s.io/v1beta1\n" + "kind: Kustomization\n" + + "\n" + "namePrefix: acquisition-gateway-\n" + "\n" + "bases:\n" + + /** + * Not supported right now " \n" + "#- + * https://github.intuit.com/dev-patterns/intuit-kustomize/intuit-service-appd-noingress-base?ref=v3.1.2\n" + * + "# Add the following base and HPA-patch.yaml, fill in correct minReplicas and + * maxReplcias in Hpa-patch.yaml\n" + "#- + * https://github.intuit.com/dev-patterns/intuit-kustomize//intuit-service-hpa-base?ref=v3.1.2\n" + * + + */ + "- https://github.intuit.com/dev-patterns/intuit-kustomize//intuit-service-canary-appd-noingress-base?ref=v3.2.0\n" + + "- https://github.intuit.com/dev-patterns/intuit-kustomize//intuit-service-rollout-hpa-base?ref=v3.2.0\n" + + "# resources:\n" + "# - Nginx-ConfigMap.yaml\n" + "\n" + "resources:\n" + + "- ConfigMap-v1-splunk-sidecar-config.yaml\n" + "- CronJob-patch.yaml\n" + "\n" + + "patchesStrategicMerge:\n" + "- app-rollout-patch.yaml\n" + "- Service-patch.yaml\n" + + "- Service-metrics-patch.yaml\n" + + // "\n" + + "- Hpa-patch.yaml\n" + "#- SignalSciences-patch.yaml\n" + "\n" + + "# Uncomment HPA-patch when you need to enable HPA\n" + "#- Hpa-patch.yaml\n" + + "# Uncomment SignalSciences-patch when you need to enable Signal Sciences\n" + + "#- SignalSciences-patch.yaml\n" + ""; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testCommentsIndentFirstLineBlank() throws Exception { + String data = "# Comment 1\n" + "key1:\n" + " \n" + " # Comment 2\n" + " # Comment 3\n" + + " key2: value1\n" + "# \"Fun\" options\n" + "key3:\n" + " # Comment 4\n" + + " # Comment 5\n" + " key4: value2\n" + "key5:\n" + " key6: value3\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testMultiLineString() throws Exception { + String data = "# YAML load and save bug with keep block chomping indicator\n" + "example:\n" + + " description: |+\n" + " These lines have a carrage return after them.\n" + + " And the carrage return will be duplicated with each save if the\n" + + " block chomping indicator + is used. (\"keep\": keep the line feed, keep trailing blank lines.)\n" + + "\n" + "successfully-loaded: test\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void test100Comments() throws IOException { + StringBuilder commentBuilder = new StringBuilder(); + for (int i = 0; i < 100; i++) { + commentBuilder.append("# Comment ").append(i).append("\n"); + } + final String data = "" + commentBuilder + "simpleKey: simpleValue\n" + "\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(data, result); + } + + @Test + public void testCommentsOnReference() throws Exception { + String data = "dummy: &a test\n" + "conf:\n" + "- # comment not ok here\n" + + " *a #comment not ok here\n"; + String expected = "dummy: &a test\n" + "conf:\n" + "- *a\n"; + + String result = runEmitterWithCommentsEnabled(data); + assertEquals(expected.replace("a", "id001"), result); + } + + @Test + public void testCommentsAtDataWindowBreak() { + String data = getComplexConfig(); + + final DumperOptions yamlOptions = new DumperOptions(); + final LoaderOptions loaderOptions = new LoaderOptions(); + final Representer yamlRepresenter = new Representer(); + + yamlOptions.setIndent(4); + yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + loaderOptions.setMaxAliasesForCollections(Integer.MAX_VALUE); + final Yaml yaml = new Yaml(new SafeConstructor(), yamlRepresenter, yamlOptions, loaderOptions); + + yaml.load(data); + } + + @Test + public void testCommentsInFlowMapping() throws IOException { + StringWriter output = new StringWriter(); + Emitter emitter = producePrettyFlowEmitter(output); + + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter + .emit(new MappingStartEvent(null, "yaml.org,2002:map", true, null, null, FlowStyle.FLOW)); + emitter.emit(new CommentEvent(CommentType.BLOCK, " I'm first", null, null)); + ImplicitTuple allImplicit = new ImplicitTuple(true, true); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "a", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "Hello", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "b", null, null, + ScalarStyle.PLAIN)); + emitter + .emit(new MappingStartEvent(null, "yaml.org,2002:map", true, null, null, FlowStyle.FLOW)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "one", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "World", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new CommentEvent(CommentType.BLOCK, " also me", null, null)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "two", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "eee", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new MappingEndEvent(null, null)); + emitter.emit(new MappingEndEvent(null, null)); + emitter.emit(new DocumentEndEvent(null, null, false)); + emitter.emit(new StreamEndEvent(null, null)); + + String result = output.toString(); + final String data = "{\n" + " # I'm first\n" + " a: Hello,\n" + " b: {\n" + + " one: World,\n" + " # also me\n" + " two: eee\n" + " }\n" + "}\n"; + + assertEquals(data, result); + } + + @Test + public void testCommentInEmptyFlowMapping() throws IOException { + StringWriter output = new StringWriter(); + Emitter emitter = producePrettyFlowEmitter(output); + + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter + .emit(new MappingStartEvent(null, "yaml.org,2002:map", true, null, null, FlowStyle.FLOW)); + emitter.emit(new CommentEvent(CommentType.BLOCK, " nobody home", null, null)); + emitter.emit(new MappingEndEvent(null, null)); + emitter.emit(new DocumentEndEvent(null, null, false)); + emitter.emit(new StreamEndEvent(null, null)); + + String result = output.toString(); + final String data = "{\n" + " # nobody home\n" + "}\n"; + + assertEquals(data, result); + } + + @Test + public void testCommentInFlowSequence() throws IOException { + StringWriter output = new StringWriter(); + Emitter emitter = producePrettyFlowEmitter(output); + ImplicitTuple allImplicit = new ImplicitTuple(true, true); + + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter + .emit(new SequenceStartEvent(null, "yaml.org,2002:seq", true, null, null, FlowStyle.FLOW)); + emitter.emit(new CommentEvent(CommentType.BLOCK, " red", null, null)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "one", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new CommentEvent(CommentType.BLOCK, " blue", null, null)); + emitter.emit(new ScalarEvent(null, "yaml.org,2002:str", allImplicit, "two", null, null, + ScalarStyle.PLAIN)); + emitter.emit(new SequenceEndEvent(null, null)); + emitter.emit(new DocumentEndEvent(null, null, false)); + emitter.emit(new StreamEndEvent(null, null)); + + String result = output.toString(); + final String data = "[\n" + " # red\n" + " one,\n" + " # blue\n" + " two\n" + "]\n"; + + assertEquals(data, result); + } + + @Test + public void testCommentInEmptySequence() throws IOException { + StringWriter output = new StringWriter(); + Emitter emitter = producePrettyFlowEmitter(output); + + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter + .emit(new SequenceStartEvent(null, "yaml.org,2002:seq", true, null, null, FlowStyle.FLOW)); + emitter.emit(new CommentEvent(CommentType.BLOCK, " nobody home", null, null)); + emitter.emit(new SequenceEndEvent(null, null)); + emitter.emit(new DocumentEndEvent(null, null, false)); + emitter.emit(new StreamEndEvent(null, null)); + + String result = output.toString(); + final String data = "[\n" + " # nobody home\n" + "]\n"; + + assertEquals(data, result); + } + + private String getComplexConfig() { + return "# Core configurable options for LWC\n" + "core:\n" + "\n" + + " # The language LWC will use, specified by the shortname. For example, English = en, French = fr, German = de,\n" + + " # and so on\n" + " locale: en\n" + "\n" + + " # How often updates are batched to the database (in seconds). If set to a higher value than 10, you may have\n" + + " # some unexpected results, especially if your server is prone to crashing.\n" + + " flushInterval: 10\n" + "\n" + + " # LWC regularly caches protections locally to prevent the database from being queried as often. The default is 10000\n" + + " # and for most servers is OK. LWC will also fill up to <precache> when the server is started automatically.\n" + + " cacheSize: 10000\n" + "\n" + + " # How many protections are precached on startup. If set to -1, it will use the cacheSize value instead and precache\n" + + " # as much as possible\n" + " precache: -1\n" + "\n" + + " # If true, players will be sent a notice in their chat box when they open a protection they have access to, but\n" + + " # not their own unless <showMyNotices> is set to true\n" + " showNotices: true\n" + + "\n" + + " # If true, players will be sent a notice in their chat box when they open a protection they own.\n" + + " showMyNotices: false\n"; + } + + @Test + public void emitOnlyScalarWithComment() throws IOException { + StringWriter output = new StringWriter(); + Emitter emitter = producePrettyFlowEmitter(output); + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter.emit(new CommentEvent(CommentType.BLOCK, "Hello world!", null, null)); + emitter.emit(new ScalarEvent(null, null, new ImplicitTuple(true, true), "This is the scalar", + null, null, ScalarStyle.DOUBLE_QUOTED)); + emitter.emit(new DocumentEndEvent(null, null, false)); + emitter.emit(new StreamEndEvent(null, null)); + + final String data = "#Hello world!\n" + "\"This is the scalar\"\n"; + + assertEquals(data, output.toString()); + } + + @Test + public void emitOnlyComment() throws IOException { + StringWriter output = new StringWriter(); + Emitter emitter = producePrettyFlowEmitter(output); + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter.emit(new CommentEvent(CommentType.BLOCK, "Hello world!", null, null)); + emitter.emit(new DocumentEndEvent(null, null, false)); + emitter.emit(new StreamEndEvent(null, null)); + + assertEquals("#Hello world!\n", output.toString()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/comment/ParserWithCommentEnabledTest.java b/src/test/java/org/yaml/snakeyaml/comment/ParserWithCommentEnabledTest.java new file mode 100644 index 00000000..4d5e696e --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/comment/ParserWithCommentEnabledTest.java @@ -0,0 +1,404 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comment; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.events.Event; +import org.yaml.snakeyaml.events.Event.ID; +import org.yaml.snakeyaml.parser.Parser; +import org.yaml.snakeyaml.parser.ParserImpl; +import org.yaml.snakeyaml.reader.StreamReader; + +public class ParserWithCommentEnabledTest { + + private final boolean DEBUG = false; + + private void println(String s) { + if (DEBUG) { + System.out.println(s); + } + } + + private void println() { + if (DEBUG) { + System.out.println(); + } + } + + + private void assertEventListEquals(List<ID> expectedEventIdList, Parser parser) { + for (ID expectedEventId : expectedEventIdList) { + parser.checkEvent(expectedEventId); + Event event = parser.getEvent(); + println("Expected: " + expectedEventId); + println("Got: " + event); + println(); + if (event == null) { + fail("Missing event: " + expectedEventId); + } + assertEquals(expectedEventId, event.getEventId()); + } + } + + @SuppressWarnings("unused") + private void printEventList(Parser parser) { + for (Event event = parser.getEvent(); event != null; event = parser.getEvent()) { + println("Got: " + event); + println(); + } + } + + private Parser createParser(String data) { + return new ParserImpl(new StreamReader(data), true); + } + + @Test + public void testEmpty() { + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, ID.StreamEnd); + String data = ""; + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testParseWithOnlyComment() { + String data = "# Comment"; + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.Comment, // + ID.StreamEnd // + ); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testCommentEndingALine() { + String data = "" + // + "key: # Comment\n" + // + " value\n"; + + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, ID.Scalar, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testMultiLineComment() { + String data = "" + // + "key: # Comment\n" + // + " # lines\n" + // + " value\n" + // + "\n"; + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, ID.Comment, ID.Scalar, // + ID.Comment, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testBlankLine() { + String data = "" + // + "\n"; + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, // + ID.Comment, // + ID.StreamEnd); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testBlankLineComments() { + String data = "" + // + "\n" + // + "abc: def # commment\n" + // + "\n" + // + "\n"; + + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, // + ID.Comment, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Scalar, ID.Comment, // + ID.Comment, // + ID.Comment, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void test_blockScalar() { + String data = "" + // + "abc: > # Comment\n" + // + " def\n" + // + " hij\n" + // + "\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, // + ID.Scalar, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testDirectiveLineEndComment() { + String data = "%YAML 1.1 #Comment\n"; + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.StreamEnd // + ); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testSequence() { + String data = "" + // + "# Comment\n" + // + "list: # InlineComment1\n" + // + "# Block Comment\n" + // + "- item # InlineComment2\n" + // + "# Comment\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.Comment, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, ID.Comment, // + ID.SequenceStart, // + ID.Scalar, ID.Comment, // + ID.Comment, // + ID.SequenceEnd, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testAllComments1() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "key: # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + " # Block Comment3a\n" + // + " # Block Comment3b\n" + // + " value # Inline Comment2\n" + // + "# Block Comment4\n" + // + "list: # InlineComment3a\n" + // + " # InlineComment3b\n" + // + "# Block Comment5\n" + // + "- item1 # InlineComment4\n" + // + "- item2: [ value2a, value2b ] # InlineComment5\n" + // + "- item3: { key3a: [ value3a1, value3a2 ], key3b: value3b } # InlineComment6\n" + // + "# Block Comment6\n" + // + "---\n" + // + "# Block Comment7\n" + // + ""; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.Comment, // + ID.Comment, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, ID.Comment, // + + ID.Comment, ID.Comment, // + ID.Scalar, ID.Comment, // + + ID.Comment, // + ID.Scalar, ID.Comment, ID.Comment, // + ID.Comment, // + + ID.SequenceStart, // + ID.Scalar, ID.Comment, // + ID.MappingStart, // + ID.Scalar, ID.SequenceStart, ID.Scalar, ID.Scalar, ID.SequenceEnd, ID.Comment, // + ID.MappingEnd, + + ID.MappingStart, // + ID.Scalar, // value=item3 + ID.MappingStart, // + ID.Scalar, // value=key3a + ID.SequenceStart, // + ID.Scalar, // value=value3a + ID.Scalar, // value=value3a2 + ID.SequenceEnd, // + ID.Scalar, // value=key3b + ID.Scalar, // value=value3b + ID.MappingEnd, // + ID.Comment, // type=IN_LINE, value= InlineComment6 + ID.Comment, // + ID.MappingEnd, // + ID.SequenceEnd, // + ID.MappingEnd, ID.DocumentEnd, // + + ID.DocumentStart, // + ID.Comment, // + ID.Scalar, // Empty + ID.DocumentEnd, // + ID.StreamEnd // + ); + Parser sut = createParser(data); + // printEventList(sut); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testAllComments2() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "- item1 # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + "# Block Comment3a\n" + // + "# Block Comment3b\n" + // + "- item2: value # Inline Comment2\n" + // + "# Block Comment4\n" + // + ""; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.Comment, // + ID.Comment, // + ID.DocumentStart, // + ID.SequenceStart, // + ID.Scalar, ID.Comment, ID.Comment, // + ID.Comment, // + ID.Comment, // + ID.MappingStart, // + ID.Scalar, ID.Scalar, ID.Comment, // + ID.Comment, // + ID.MappingEnd, // + ID.SequenceEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + Parser sut = createParser(data); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testAllComments3() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "[ item1, item2: value2, {item3: value3} ] # Inline Comment1\n" + // + "# Block Comment2\n" + // + ""; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.Comment, // + ID.DocumentStart, // + ID.SequenceStart, // + ID.Scalar, ID.MappingStart, // + ID.Scalar, ID.Scalar, // + ID.MappingEnd, // + ID.MappingStart, // + ID.Scalar, ID.Scalar, // + ID.MappingEnd, // + ID.SequenceEnd, // + ID.Comment, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + Parser sut = createParser(data); + // printEventList(sut); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testKeepingNewLineInsideSequence() throws Exception { + String data = "" + "\n" + "key:\n" + "\n" + "- item1\n" + "\n" + // Per Spec this is part of + // plain scalar above + "- item2\n" + "\n" + // Per Spec this is part of plain scalar above + "- item3\n" + "\n" + // FIXME: ?Should be comment? + "key2: value2\n" + "\n" + // FIXME: ?Should be comment? + "key3: value3\n" + "\n" + // FIXME: ?Should be comment? + ""; + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.Comment, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, // + ID.Comment, // + ID.SequenceStart, // + ID.Scalar, // + ID.Scalar, // + ID.Scalar, // + ID.Comment, // + ID.SequenceEnd, // + ID.Scalar, // + ID.Scalar, // + ID.Comment, // + ID.Scalar, // + ID.Scalar, // + ID.Comment, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + Parser sut = new ParserImpl(new StreamReader(data), true); + // printEventList(sut); + assertEventListEquals(expectedEventIdList, sut); + } + + @Test + public void testCommentsInFlowMapping() { + String data = "" + "# Beginning\n" + "{\n" + " # Hello\n" + " key1: meow,\n" + + " # World\n" + " key2: purr\n" + "}\n"; + + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, ID.Comment, ID.DocumentStart, + ID.MappingStart, ID.Comment, ID.Scalar, ID.Scalar, ID.Comment, ID.Scalar, ID.Scalar, + ID.MappingEnd, ID.DocumentEnd, ID.StreamEnd); + Parser sut = new ParserImpl(new StreamReader(data), true); + // printEventList(sut); + assertEventListEquals(expectedEventIdList, sut); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/comment/ProblematicYamlTest.java b/src/test/java/org/yaml/snakeyaml/comment/ProblematicYamlTest.java new file mode 100644 index 00000000..f387d0c7 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/comment/ProblematicYamlTest.java @@ -0,0 +1,231 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comment; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.comments.CommentType; +import org.yaml.snakeyaml.events.CommentEvent; +import org.yaml.snakeyaml.events.Event; +import org.yaml.snakeyaml.events.Event.ID; +import org.yaml.snakeyaml.parser.Parser; +import org.yaml.snakeyaml.parser.ParserImpl; +import org.yaml.snakeyaml.reader.StreamReader; + +public class ProblematicYamlTest { + + private final boolean DEBUG = false; + + private void println(String s) { + if (DEBUG) { + System.out.println(s); + } + } + + private void println() { + if (DEBUG) { + System.out.println(); + } + } + + private static final LoaderOptions LOAD_OPTIONS = new LoaderOptions(); + + static { + LOAD_OPTIONS.setProcessComments(true); + } + + private void assertEventListEquals(List<ID> expectedEventIdList, + List<CommentType> expectedCommentTypeList, Parser parser) { + Iterator<CommentType> commentTypeIterator = expectedCommentTypeList.iterator(); + for (ID expectedEventId : expectedEventIdList) { + parser.checkEvent(expectedEventId); + Event event = parser.getEvent(); + println("Expected: " + expectedEventId); + if (event == null) { + fail("Missing event: " + expectedEventId); + } + println("Got: " + event + + (event.getEventId() == ID.Comment ? " " + ((CommentEvent) event).getCommentType() + : "")); + println(); + if (event.getEventId() == ID.Comment) { + assertEquals(commentTypeIterator.next(), ((CommentEvent) event).getCommentType()); + } + assertEquals(expectedEventId, event.getEventId()); + } + } + + @SuppressWarnings("unused") + private void printEventList(Parser parser) { + for (Event event = parser.getEvent(); event != null; event = parser.getEvent()) { + println("Got: " + event + + (event.getEventId() == ID.Comment ? " " + ((CommentEvent) event).getCommentType() + : "")); + println(); + } + } + + @Test + public void testParseProblematicYaml1() { + final String yamlString1 = "" + // + "key: value\n" + // + " # Comment 1\n" + // s.b BLOCK, classified as INLINE + "\n" + // + " # Comment 2\n" + // + ""; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, // + ID.Scalar, // + ID.Comment, // + ID.Comment, // + ID.Comment, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + List<CommentType> expectedCommentTypeList = Arrays.asList(// + CommentType.BLOCK, CommentType.BLANK_LINE, CommentType.BLOCK); + ParserImpl parser = new ParserImpl(new StreamReader(new StringReader(yamlString1)), + LOAD_OPTIONS.isProcessComments()); + assertEventListEquals(expectedEventIdList, expectedCommentTypeList, parser); + } + + @Test + public void testParseProblematicYaml2() { + final String yamlString2 = "" + // + "key: value\n" + // + "\n" + // + " # Comment 1\n" + // s.b BLOCK, classified as INLINE + "\n" + // + " # Comment 2\n" + // + ""; + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, // + ID.Scalar, // + ID.Comment, // + ID.Comment, // + ID.Comment, // + ID.Comment, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + List<CommentType> expectedCommentTypeList = Arrays.asList(// + CommentType.BLANK_LINE, CommentType.BLOCK, CommentType.BLANK_LINE, CommentType.BLOCK); + ParserImpl parser = new ParserImpl(new StreamReader(new StringReader(yamlString2)), + LOAD_OPTIONS.isProcessComments()); + assertEventListEquals(expectedEventIdList, expectedCommentTypeList, parser); + } + + @Test + public void testParseProblematicYaml3() { + final String yamlString3 = "" + // + "key: value\n" + // + "\n" + // + "key: value\n" + // + ""; + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, // + ID.Scalar, // + ID.Comment, // + ID.Scalar, // + ID.Scalar, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + List<CommentType> expectedCommentTypeList = Collections.singletonList(CommentType.BLANK_LINE); + ParserImpl parser = new ParserImpl(new StreamReader(new StringReader(yamlString3)), + LOAD_OPTIONS.isProcessComments()); + assertEventListEquals(expectedEventIdList, expectedCommentTypeList, parser); + } + + @Test + public void testParseProblematicYaml4() { + String yamlString4 = "" + // + "---\n" + // + "in the block context:\n" + // + " indentation should be kept: { \n" + // + " but in the flow context: [\n" + // + "it may be violated]\n" + // + "}\n" + // + "---\n" + // + "the parser does not require scalars\n" + // + "to be indented with at least one space\n" + // + "...\n" + // + "---\n" + // + "\"the parser does not require scalars\n" + // + "to be indented with at least one space\"\n" + // + "---\n" + // + "foo:\n" + // + " bar: 'quoted scalars\n" + // + "may not adhere indentation'\n" + // + ""; + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, // + ID.MappingStart, // + ID.Scalar, // + ID.MappingStart, // + ID.Scalar, // + ID.SequenceStart, // + ID.Scalar, // + ID.SequenceEnd, // + ID.MappingEnd, // + ID.MappingEnd, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.DocumentStart, // + ID.Scalar, // + ID.DocumentEnd, // + ID.DocumentStart, // + ID.Scalar, // + ID.DocumentEnd, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, // + ID.MappingStart, // + ID.Scalar, // + ID.Scalar, // + ID.MappingEnd, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd// + ); + ParserImpl parser = new ParserImpl(new StreamReader(new StringReader(yamlString4)), + LOAD_OPTIONS.isProcessComments()); + assertEventListEquals(expectedEventIdList, new ArrayList<CommentType>(), parser); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/comment/ScannerWithCommentEnabledTest.java b/src/test/java/org/yaml/snakeyaml/comment/ScannerWithCommentEnabledTest.java new file mode 100644 index 00000000..def86e38 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/comment/ScannerWithCommentEnabledTest.java @@ -0,0 +1,301 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comment; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.io.StringReader; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.reader.StreamReader; +import org.yaml.snakeyaml.scanner.Scanner; +import org.yaml.snakeyaml.scanner.ScannerImpl; +import org.yaml.snakeyaml.tokens.CommentToken; +import org.yaml.snakeyaml.tokens.ScalarToken; +import org.yaml.snakeyaml.tokens.Token; +import org.yaml.snakeyaml.tokens.Token.ID; + +public class ScannerWithCommentEnabledTest { + + private void assertTokensEqual(List<ID> expected, Scanner sut) { + assertTokensEqual(expected, null, sut); + } + + private void printToken(Token token) { + String value; + switch (token.getTokenId()) { + case Scalar: + value = "(value='" + ((ScalarToken) token).getValue() + "')"; + break; + case Comment: + CommentToken commentToken = (CommentToken) token; + value = "(type='" + commentToken.getCommentType() + ", value='" + commentToken.getValue() + + "')"; + break; + default: + value = ""; + break; + } + // System.out.println(token.getTokenId().name() + value); + } + + private void assertTokenEquals(Iterator<ID> expectedIdIterator, + Iterator<String> expectedScalarValueIterator, Token token) { + printToken(token); + assertTrue(expectedIdIterator.hasNext()); + ID expectedValue = expectedIdIterator.next(); + assertSame(expectedValue, token.getTokenId()); + if (expectedScalarValueIterator != null && token.getTokenId() == ID.Scalar) { + assertEquals(expectedScalarValueIterator.next(), ((ScalarToken) token).getValue()); + } + } + + private void assertTokensEqual(List<ID> expectedList, List<String> expectedScalarValueList, + Scanner sut) { + Iterator<ID> expectedIterator = expectedList.iterator(); + Iterator<String> expectedScalarValueIterator = + expectedScalarValueList == null ? null : expectedScalarValueList.iterator(); + while (!sut.checkToken(Token.ID.StreamEnd)) { + Token token = sut.getToken(); + assertTokenEquals(expectedIterator, expectedScalarValueIterator, token); + } + Token token = sut.peekToken(); + assertTokenEquals(expectedIterator, expectedScalarValueIterator, token); + assertFalse(expectedIterator.hasNext()); + } + + private Scanner constructScanner(String input) { + LoaderOptions options = new LoaderOptions(); + options.setProcessComments(true); + return new ScannerImpl(new StreamReader(new StringReader(input)), options); + } + + @Test + public void testEmpty() { + List<ID> expected = Arrays.asList(ID.StreamStart, ID.StreamEnd); + + Scanner sut = constructScanner(""); + + assertTokensEqual(expected, sut); + } + + @Test + public void testOnlyCommentLines() { + List<ID> expected = Arrays.asList(ID.StreamStart, // + ID.Comment, // + ID.Comment, // + ID.StreamEnd); + + Scanner sut = constructScanner("" + // + "# This stream contains no\n" + // + "# documents, only comments."); + + assertTokensEqual(expected, sut); + } + + @Test + public void testCommentEndingALine() { + List<ID> expected = Arrays.asList(ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, // + ID.Scalar, // + ID.BlockEnd, // + ID.StreamEnd); + List<String> expectedScalarValue = Arrays.asList(// + "key", "value"); + + Scanner sut = constructScanner("" + // + "key: # Comment\n" + // + " value\n"); + + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void testMultiLineComment() { + List<ID> expected = Arrays.asList(ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, ID.Comment, // + ID.Scalar, // + ID.Comment, // + ID.BlockEnd, // + ID.StreamEnd); + List<String> expectedScalarValue = Arrays.asList(// + "key", "value"); + + Scanner sut = constructScanner("" + // + "key: # Comment\n" + // + " # lines\n" + // + " value\n" + // + "\n"); + + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void testBlankLine() { + List<ID> expected = Arrays.asList(ID.StreamStart, // + ID.Comment, // + ID.StreamEnd); + + Scanner sut = constructScanner("" + // + "\n"); + + assertTokensEqual(expected, sut); + } + + @Test + public void testBlankLineComments() { + List<ID> expected = Arrays.asList(ID.StreamStart, // + ID.Comment, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Scalar, ID.Comment, // + ID.Comment, // + ID.Comment, // + ID.BlockEnd, // + ID.StreamEnd); + + Scanner sut = constructScanner("" + // + "\n" + // + "abc: def # commment\n" + // + "\n" + // + "\n"); + + assertTokensEqual(expected, sut); + } + + @Test + public void test_blockScalar_replaceNLwithSpaces_singleNLatEnd() { + List<ID> expected = Arrays.asList(// + ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, // + ID.Scalar, // + ID.BlockEnd, // + ID.StreamEnd // + ); + List<String> expectedScalarValue = Arrays.asList(// + "abc", "def hij\n"); + + Scanner sut = constructScanner("abc: > # Comment\n def\n hij\n\n"); + + // printTokens(sut); + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void test_blockScalar_replaceNLwithSpaces_noNLatEnd() { + List<ID> expected = Arrays.asList(// + ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, ID.Scalar, // + ID.BlockEnd, // + ID.StreamEnd // + ); + List<String> expectedScalarValue = Arrays.asList(// + "abc", "def hij"); + + Scanner sut = constructScanner("abc: >- # Comment\n def\n hij\n\n"); + + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void test_blockScalar_replaceNLwithSpaces_allNLatEnd() { + List<ID> expected = Arrays.asList(// + ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, ID.Scalar, // + ID.BlockEnd, // + ID.StreamEnd // + ); + List<String> expectedScalarValue = Arrays.asList(// + "abc", "def hij\n\n"); + + Scanner sut = constructScanner("abc: >+ # Comment\n def\n hij\n\n"); + + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void test_blockScalar_keepNL_singleNLatEnd() { + List<ID> expected = Arrays.asList(// + ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, ID.Scalar, // + ID.BlockEnd, // + ID.StreamEnd // + ); + List<String> expectedScalarValue = Arrays.asList(// + "abc", "def\nhij\n"); + + Scanner sut = constructScanner("abc: | # Comment\n def\n hij\n\n"); + + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void test_blockScalar_keepNL_noNLatEnd() { + List<ID> expected = Arrays.asList(// + ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, ID.Scalar, // + ID.BlockEnd, // + ID.StreamEnd // + ); + List<String> expectedScalarValue = Arrays.asList(// + "abc", "def\nhij"); + + Scanner sut = constructScanner("abc: |- # Comment\n def\n hij\n\n"); + + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void test_blockScalar_keepNL_allNLatEnd() { + List<ID> expected = Arrays.asList(// + ID.StreamStart, // + ID.BlockMappingStart, // + ID.Key, ID.Scalar, ID.Value, ID.Comment, ID.Scalar, // + ID.BlockEnd, // + ID.StreamEnd // + ); + List<String> expectedScalarValue = Arrays.asList(// + "abc", "def\nhij\n\n"); + + Scanner sut = constructScanner("abc: |+ # Comment\n def\n hij\n\n"); + + assertTokensEqual(expected, expectedScalarValue, sut); + } + + @Test + public void testDirectiveLineEndComment() { + List<ID> expected = Arrays.asList(// + ID.StreamStart, // + ID.Directive, // + ID.Comment, // + ID.StreamEnd // + ); + + Scanner sut = constructScanner("%YAML 1.1 #Comment\n"); + + assertTokensEqual(expected, sut); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/comment/SerializerWithCommentEnabledTest.java b/src/test/java/org/yaml/snakeyaml/comment/SerializerWithCommentEnabledTest.java new file mode 100644 index 00000000..1cc9af58 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/comment/SerializerWithCommentEnabledTest.java @@ -0,0 +1,419 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.comment; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.composer.Composer; +import org.yaml.snakeyaml.emitter.Emitable; +import org.yaml.snakeyaml.events.Event; +import org.yaml.snakeyaml.events.Event.ID; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.parser.ParserImpl; +import org.yaml.snakeyaml.reader.StreamReader; +import org.yaml.snakeyaml.resolver.Resolver; +import org.yaml.snakeyaml.serializer.Serializer; + +public class SerializerWithCommentEnabledTest { + + private final boolean DEBUG = false; + + private void println(String s) { + if (DEBUG) { + System.out.println(s); + } + } + + private void println() { + if (DEBUG) { + System.out.println(); + } + } + + private void assertEventListEquals(List<ID> expectedEventIdList, List<Event> actualEvents) { + Iterator<Event> iterator = actualEvents.iterator(); + for (ID expectedEventId : expectedEventIdList) { + println("Expected: " + expectedEventId); + assertTrue(iterator.hasNext()); + Event event = iterator.next(); + println("Got: " + event); + println(); + assertEquals(expectedEventId, event.getEventId()); + } + } + + private static class TestEmitter implements Emitable { + + private final List<Event> eventList = new ArrayList<>(); + + @Override + public void emit(Event event) throws IOException { + eventList.add(event); + } + + public List<Event> getEventList() { + return eventList; + } + } + + public List<Event> serializeWithCommentsEnabled(String data) throws IOException { + TestEmitter emitter = new TestEmitter(); + Tag rootTag = null; + Serializer serializer = new Serializer(emitter, new Resolver(), new DumperOptions(), rootTag); + serializer.open(); + Composer composer = new Composer(new ParserImpl(new StreamReader(data), true), new Resolver()); + while (composer.checkNode()) { + serializer.serialize(composer.getNode()); + } + serializer.close(); + List<Event> events = emitter.getEventList(); + println("RESULT: "); + for (Event event : events) { + println(event.toString()); + } + println(); + return events; + } + + + @Test + public void testEmpty() throws Exception { + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, ID.StreamEnd); + + String data = ""; + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testParseWithOnlyComment() throws Exception { + String data = "# Comment"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testCommentEndingALine() throws Exception { + String data = "" + // + "key: # Comment\n" + // + " value\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, ID.Scalar, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testMultiLineComment() throws Exception { + String data = "" + // + "key: # Comment\n" + // + " # lines\n" + // + " value\n" + // + "\n"; + + List<ID> expectedEventIdList = Arrays.asList(ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, ID.Comment, ID.Scalar, // + ID.MappingEnd, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testBlankLine() throws Exception { + String data = "" + // + "\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testBlankLineComments() throws Exception { + String data = "" + // + "\n" + // + "abc: def # comment\n" + // + "\n" + // + "\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Comment, // + ID.Scalar, ID.Scalar, ID.Comment, // + ID.MappingEnd, // + ID.Comment, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void test_blockScalar() throws Exception { + String data = "" + // + "abc: > # Comment\n" + // + " def\n" + // + " hij\n" + // + "\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Scalar, ID.Comment, // + ID.Scalar, // + ID.MappingEnd, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testDirectiveLineEndComment() throws Exception { + String data = "%YAML 1.1 #Comment\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.StreamEnd // + ); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testSequence() throws Exception { + String data = "" + // + "# Comment\n" + // + "list: # InlineComment1\n" + // + "# Block Comment\n" + // + "- item # InlineComment2\n" + // + "# Comment\n"; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Comment, // + ID.Scalar, ID.Comment, // + ID.SequenceStart, // + ID.Comment, // + ID.Scalar, ID.Comment, // + ID.SequenceEnd, // + ID.MappingEnd, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testAllComments1() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "key: # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + " # Block Comment3a\n" + // + " # Block Comment3b\n" + // + " value # Inline Comment2\n" + // + "# Block Comment4\n" + // + "list: # InlineComment3a\n" + // + " # InlineComment3b\n" + // + "# Block Comment5\n" + // + "- item1 # InlineComment4\n" + // + "- item2: [ value2a, value2b ] # InlineComment5\n" + // + "- item3: { key3a: [ value3a1, value3a2 ], key3b: value3b } # InlineComment6\n" + // + "# Block Comment6\n" + // + "---\n" + // + "# Block Comment7\n" + // + ""; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.MappingStart, // + ID.Comment, // + ID.Comment, // + ID.Scalar, ID.Comment, ID.Comment, // + + ID.Comment, ID.Comment, // + ID.Scalar, ID.Comment, // + + ID.Comment, // + ID.Scalar, ID.Comment, ID.Comment, // + + ID.SequenceStart, // + ID.Comment, // + ID.Scalar, // + ID.Comment, // + + ID.MappingStart, // + ID.Scalar, ID.SequenceStart, ID.Scalar, ID.Scalar, ID.SequenceEnd, ID.Comment, // + ID.MappingEnd, + + ID.MappingStart, // + ID.Scalar, // value=item3 + ID.MappingStart, // + ID.Scalar, // value=key3a + ID.SequenceStart, // + ID.Scalar, // value=value3a + ID.Scalar, // value=value3a2 + ID.SequenceEnd, // + ID.Scalar, // value=key3b + ID.Scalar, // value=value3b + ID.MappingEnd, // + ID.Comment, // type=IN_LINE, value= InlineComment6 + ID.MappingEnd, // + ID.SequenceEnd, // + ID.MappingEnd, // + ID.Comment, // + ID.DocumentEnd, // + + ID.DocumentStart, // + ID.Comment, // + ID.Scalar, // Empty + ID.DocumentEnd, // + ID.StreamEnd // + ); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testAllComments2() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "# Block Comment2\n" + // + "- item1 # Inline Comment1a\n" + // + " # Inline Comment1b\n" + // + "# Block Comment3a\n" + // + "# Block Comment3b\n" + // + "- item2: value # Inline Comment2\n" + // + "# Block Comment4\n" + // + ""; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.SequenceStart, // + ID.Comment, // + ID.Comment, // + ID.Scalar, ID.Comment, ID.Comment, // + ID.MappingStart, // + ID.Comment, // + ID.Comment, // + ID.Scalar, ID.Scalar, ID.Comment, // + ID.MappingEnd, // + ID.SequenceEnd, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } + + @Test + public void testAllComments3() throws Exception { + String data = "" + // + "# Block Comment1\n" + // + "[ item1, item2: value2, {item3: value3} ] # Inline Comment1\n" + // + "# Block Comment2\n" + // + ""; + + List<ID> expectedEventIdList = Arrays.asList(// + ID.StreamStart, // + ID.DocumentStart, // + ID.Comment, // + ID.SequenceStart, // + ID.Scalar, ID.MappingStart, // + ID.Scalar, ID.Scalar, // + ID.MappingEnd, // + ID.MappingStart, // + ID.Scalar, ID.Scalar, // + ID.MappingEnd, // + ID.SequenceEnd, // + ID.Comment, // + ID.Comment, // + ID.DocumentEnd, // + ID.StreamEnd // + ); + + List<Event> result = serializeWithCommentsEnabled(data); + + assertEventListEquals(expectedEventIdList, result); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/composer/ComposerImplTest.java b/src/test/java/org/yaml/snakeyaml/composer/ComposerImplTest.java index 038da907..5dabe82e 100644 --- a/src/test/java/org/yaml/snakeyaml/composer/ComposerImplTest.java +++ b/src/test/java/org/yaml/snakeyaml/composer/ComposerImplTest.java @@ -1,24 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.composer; -import java.io.StringReader; +import static org.junit.Assert.assertNotEquals; +import java.io.StringReader; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; @@ -26,49 +24,59 @@ import org.yaml.snakeyaml.nodes.NodeId; public class ComposerImplTest extends TestCase { - public void testGetNode() { - String data = "american:\n - Boston Red Sox"; - Yaml yaml = new Yaml(); - Node node = yaml.compose(new StringReader(data)); - assertNotNull(node); - assertTrue(node instanceof MappingNode); - String data2 = "---\namerican:\n- Boston Red Sox"; - Node node2 = yaml.compose(new StringReader(data2)); - assertNotNull(node2); - assertFalse(node.equals(node2)); - } + public void testGetNode() { + String data = "american:\n - Boston Red Sox"; + Yaml yaml = new Yaml(); + Node node = yaml.compose(new StringReader(data)); + assertNotNull(node); + assertTrue(node instanceof MappingNode); + String data2 = "---\namerican:\n- Boston Red Sox"; + Node node2 = yaml.compose(new StringReader(data2)); + assertNotNull(node2); + assertNotEquals(node, node2); + } - public void testComposeBean() { - String data = "!!org.yaml.snakeyaml.composer.ComposerImplTest$BeanToCompose {name: Bill, age: 18}"; - Yaml yaml = new Yaml(); - Node node = yaml.compose(new StringReader(data)); - assertNotNull(node); - assertTrue(node instanceof MappingNode); - assertEquals( - "tag:yaml.org,2002:org.yaml.snakeyaml.composer.ComposerImplTest$BeanToCompose", - node.getTag().getValue()); - assertEquals(NodeId.mapping, node.getNodeId()); - assertEquals(Object.class, node.getType()); - } + public void testComposeBean() { + String data = + "!!org.yaml.snakeyaml.composer.ComposerImplTest$BeanToCompose {name: Bill, age: 18}"; + Yaml yaml = new Yaml(); + Node node = yaml.compose(new StringReader(data)); + assertNotNull(node); + assertTrue(node instanceof MappingNode); + assertEquals("tag:yaml.org,2002:org.yaml.snakeyaml.composer.ComposerImplTest$BeanToCompose", + node.getTag().getValue()); + assertEquals(NodeId.mapping, node.getNodeId()); + assertEquals(Object.class, node.getType()); + } - public static class BeanToCompose { - private String name; - private int age; + public void testNodeAnchor() { + String data = "--- &113\n{name: Bill, age: 18}"; + Yaml yaml = new Yaml(); + Node node = yaml.compose(new StringReader(data)); + assertNotNull(node); + assertTrue(node instanceof MappingNode); + assertEquals("113", node.getAnchor()); + } - public String getName() { - return name; - } + public static class BeanToCompose { - public void setName(String name) { - this.name = name; - } + private String name; + private int age; - public int getAge() { - return age; - } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } + public void setAge(int age) { + this.age = age; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/AbstractConstructTest.java b/src/test/java/org/yaml/snakeyaml/constructor/AbstractConstructTest.java index d0c58937..4d7e5f54 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/AbstractConstructTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/AbstractConstructTest.java @@ -1,59 +1,62 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; +import java.util.ArrayList; import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.SequenceNode; import org.yaml.snakeyaml.nodes.Tag; -import java.util.ArrayList; - public class AbstractConstructTest extends TestCase { - public void testNotRecursive() { - AbstractConstruct abstractConstruct = new AbstractConstruct() { - public Object construct(Node node) { - return null; - } - }; - Node node = new SequenceNode(Tag.SEQ, true, new ArrayList<Node>(), null, null, false); - try { - abstractConstruct.construct2ndStep(node, ""); - fail(); - } catch (YAMLException e) { - assertEquals("Unexpected recursive structure for Node: <org.yaml.snakeyaml.nodes.SequenceNode (tag=tag:yaml.org,2002:seq, value=[])>", e.getMessage()); - } + public void testNotRecursive() { + AbstractConstruct abstractConstruct = new AbstractConstruct() { + public Object construct(Node node) { + return null; + } + }; + Node node = new SequenceNode(Tag.SEQ, true, new ArrayList<Node>(), null, null, + DumperOptions.FlowStyle.BLOCK); + try { + abstractConstruct.construct2ndStep(node, ""); + fail(); + } catch (YAMLException e) { + assertEquals( + "Unexpected recursive structure for Node: <org.yaml.snakeyaml.nodes.SequenceNode (tag=tag:yaml.org,2002:seq, value=[])>", + e.getMessage()); } + } - public void testRecursive() { - AbstractConstruct abstractConstruct = new AbstractConstruct() { + public void testRecursive() { + AbstractConstruct abstractConstruct = new AbstractConstruct() { - public Object construct(Node node) { - return null; - } - }; - Node node = new SequenceNode(Tag.SEQ, true, new ArrayList<Node>(), null, null, false); - node.setTwoStepsConstruction(true); - try { - abstractConstruct.construct2ndStep(node, ""); - fail(); - } catch (IllegalStateException e) { - assertEquals("Not Implemented in org.yaml.snakeyaml.constructor.AbstractConstructTest$2", e.getMessage()); - } + public Object construct(Node node) { + return null; + } + }; + Node node = new SequenceNode(Tag.SEQ, true, new ArrayList<Node>(), null, null, + DumperOptions.FlowStyle.BLOCK); + node.setTwoStepsConstruction(true); + try { + abstractConstruct.construct2ndStep(node, ""); + fail(); + } catch (IllegalStateException e) { + assertEquals("Not Implemented in org.yaml.snakeyaml.constructor.AbstractConstructTest$2", + e.getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/ArrayTagsTest.java b/src/test/java/org/yaml/snakeyaml/constructor/ArrayTagsTest.java index ce4e2503..7d73ab02 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/ArrayTagsTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/ArrayTagsTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.TypeDescription; @@ -27,86 +23,86 @@ import org.yaml.snakeyaml.Yaml; public class ArrayTagsTest extends TestCase { - public void testDefaultRepresenter() { - CarWithArray car = new CarWithArray(); - car.setPlate("12-XP-F4"); - Wheel[] wheels = new Wheel[5]; - for (int i = 1; i < 6; i++) { - Wheel wheel = new Wheel(); - wheel.setId(i); - wheels[i - 1] = wheel; - } - car.setWheels(wheels); - assertEquals(Util.getLocalResource("constructor/cararray-with-tags-flow-auto.yaml"), - new Yaml().dump(car)); + public void testDefaultRepresenter() { + CarWithArray car = new CarWithArray(); + car.setPlate("12-XP-F4"); + Wheel[] wheels = new Wheel[5]; + for (int i = 1; i < 6; i++) { + Wheel wheel = new Wheel(); + wheel.setId(i); + wheels[i - 1] = wheel; } + car.setWheels(wheels); + assertEquals(Util.getLocalResource("constructor/cararray-with-tags-flow-auto.yaml"), + new Yaml().dump(car)); + } - public void testFlowBlock() { - CarWithArray car = new CarWithArray(); - car.setPlate("12-XP-F4"); - Wheel[] wheels = new Wheel[5]; - for (int i = 1; i < 6; i++) { - Wheel wheel = new Wheel(); - wheel.setId(i); - wheels[i - 1] = wheel; - } - car.setWheels(wheels); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - assertEquals(Util.getLocalResource("constructor/cararray-with-tags.yaml"), yaml.dump(car)); + public void testFlowBlock() { + CarWithArray car = new CarWithArray(); + car.setPlate("12-XP-F4"); + Wheel[] wheels = new Wheel[5]; + for (int i = 1; i < 6; i++) { + Wheel wheel = new Wheel(); + wheel.setId(i); + wheels[i - 1] = wheel; } + car.setWheels(wheels); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + assertEquals(Util.getLocalResource("constructor/cararray-with-tags.yaml"), yaml.dump(car)); + } - public void testLoadClassTag() { - Constructor constructor = new Constructor(); - constructor.addTypeDescription(new TypeDescription(Car.class, "!car")); - Yaml yaml = new Yaml(constructor); - Car car = (Car) yaml.load(Util.getLocalResource("constructor/car-without-tags.yaml")); - assertEquals("12-XP-F4", car.getPlate()); - List<Wheel> wheels = car.getWheels(); - assertNotNull(wheels); - assertEquals(5, wheels.size()); - } + public void testLoadClassTag() { + Constructor constructor = new Constructor(); + constructor.addTypeDescription(new TypeDescription(Car.class, "!car")); + Yaml yaml = new Yaml(constructor); + Car car = yaml.load(Util.getLocalResource("constructor/car-without-tags.yaml")); + assertEquals("12-XP-F4", car.getPlate()); + List<Wheel> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + } - public void testNullDescription() { - Constructor constructor = new Constructor(); - try { - constructor.addTypeDescription(null); - fail("Description is required."); - } catch (Exception e) { - assertEquals("TypeDescription is required.", e.getMessage()); - } + public void testNullDescription() { + Constructor constructor = new Constructor(); + try { + constructor.addTypeDescription(null); + fail("Description is required."); + } catch (Exception e) { + assertEquals("TypeDescription is required.", e.getMessage()); } + } - public void testLoadClassNoRoot() { - Constructor constructor = new Constructor(new TypeDescription(CarWithArray.class)); - Yaml yaml = new Yaml(constructor); - CarWithArray car = (CarWithArray) yaml.load(Util - .getLocalResource("constructor/car-no-root-class.yaml")); - assertEquals("12-XP-F4", car.getPlate()); - Wheel[] wheels = car.getWheels(); - assertNotNull(wheels); - assertEquals(5, wheels.length); - } + public void testLoadClassNoRoot() { + Constructor constructor = new Constructor(new TypeDescription(CarWithArray.class)); + Yaml yaml = new Yaml(constructor); + CarWithArray car = yaml.load(Util.getLocalResource("constructor/car-no-root-class.yaml")); + assertEquals("12-XP-F4", car.getPlate()); + Wheel[] wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.length); + } - public static class CarWithArray { - private String plate; - private Wheel[] wheels; + public static class CarWithArray { - public String getPlate() { - return plate; - } + private String plate; + private Wheel[] wheels; - public void setPlate(String plate) { - this.plate = plate; - } + public String getPlate() { + return plate; + } + + public void setPlate(String plate) { + this.plate = plate; + } - public Wheel[] getWheels() { - return wheels; - } + public Wheel[] getWheels() { + return wheels; + } - public void setWheels(Wheel[] wheels) { - this.wheels = wheels; - } + public void setWheels(Wheel[] wheels) { + this.wheels = wheels; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/AtomicJavaBean.java b/src/test/java/org/yaml/snakeyaml/constructor/AtomicJavaBean.java index 946ff25a..221df5e8 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/AtomicJavaBean.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/AtomicJavaBean.java @@ -1,44 +1,43 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.concurrent.atomic.AtomicLong; public class AtomicJavaBean { - private float amount; - private AtomicLong atomic; - - public float getAmount() { - return amount; - } - - public void setAmount(float amount) { - this.amount = amount; - } - - public AtomicLong getAtomic() { - return atomic; - } - - public void setAtomic(AtomicLong atomic) { - this.atomic = atomic; - } - - @Override - public String toString() { - return "AtomicJavaBean"; - } -}
\ No newline at end of file + + private float amount; + private AtomicLong atomic; + + public float getAmount() { + return amount; + } + + public void setAmount(float amount) { + this.amount = amount; + } + + public AtomicLong getAtomic() { + return atomic; + } + + public void setAtomic(AtomicLong atomic) { + this.atomic = atomic; + } + + @Override + public String toString() { + return "AtomicJavaBean"; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/constructor/BeanConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/BeanConstructorTest.java index d36c733f..c2d3aa93 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/BeanConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/BeanConstructorTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.math.BigInteger; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -26,225 +22,224 @@ import org.yaml.snakeyaml.error.YAMLException; public class BeanConstructorTest extends TestCase { - public void testPrimitivesConstructor() { - Yaml yaml = new Yaml(new Constructor(TestBean1.class)); - String document = Util.getLocalResource("constructor/test-primitives1.yaml"); - TestBean1 result = (TestBean1) yaml.load(document); - assertNotNull(result); - assertEquals(new Byte((byte) 1), result.getByteClass()); - assertEquals((byte) -3, result.getBytePrimitive()); - assertEquals(new Short((short) 0), result.getShortClass()); - assertEquals((short) -13, result.getShortPrimitive()); - assertEquals(new Integer(5), result.getInteger()); - assertEquals(17, result.getIntPrimitive()); - assertEquals("the text", result.getText()); - assertEquals("13", result.getId()); - assertEquals(new Long(11111111111L), result.getLongClass()); - assertEquals(9999999999L, result.getLongPrimitive()); - assertEquals(Boolean.TRUE, result.getBooleanClass()); - assertTrue(result.isBooleanPrimitive()); - assertEquals(Character.valueOf('2'), result.getCharClass()); - assertEquals('#', result.getCharPrimitive()); - assertEquals(new BigInteger("1234567890123456789012345678901234567890"), - result.getBigInteger()); - assertEquals(new Float(2), result.getFloatClass()); - assertEquals(new Float(3.1416), result.getFloatPrimitive()); - assertEquals(new Double(4), result.getDoubleClass()); - assertEquals(new Double(11200), result.getDoublePrimitive()); - assertEquals(1199836800000L, result.getDate().getTime()); - assertEquals("public", result.publicField); - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yamlToDump = new Yaml(options); - String output = yamlToDump.dump(result); - TestBean1 result2 = (TestBean1) yaml.load(output); - assertNotNull(result2); - TestBean1 result3 = (TestBean1) new Yaml().load(output); - assertNotNull(result3); - } - - public void testNoClassConstructor() { - try { - new Yaml(new Constructor((Class<? extends Object>) null)); - fail("Class must be provided."); - } catch (NullPointerException e) { - assertEquals("Root class must be provided.", e.getMessage()); - } - } - - public void testNoClassConstructorString() throws ClassNotFoundException { - try { - new Yaml(new Constructor((String) null)); - fail("Class must be provided."); - } catch (NullPointerException e) { - assertEquals("Root type must be provided.", e.getMessage()); - } - } - - public void testNoClassConstructorEmptyString() throws ClassNotFoundException { - try { - new Yaml(new Constructor(" ")); - fail("Class must be provided."); - } catch (YAMLException e) { - assertEquals("Root type must be provided.", e.getMessage()); - } - } - - public void testCharacter() { - Yaml yaml = new Yaml(new Constructor(TestBean1.class)); - String document = "charClass: id"; - try { - yaml.load(document); - fail("Only one char must be allowed."); - } catch (Exception e) { - assertTrue(e.getMessage(), - e.getMessage().contains("Invalid node Character: 'id'; length: 2")); - } - document = "charClass: #"; - TestBean1 bean = (TestBean1) yaml.load(document); - assertNull("Null must be accepted.", bean.getCharClass()); - document = "charClass: ''"; - bean = (TestBean1) yaml.load(document); - assertNull("Null must be accepted.", bean.getCharClass()); - document = "charClass:\n"; - bean = (TestBean1) yaml.load(document); - assertNull("Null must be accepted.", bean.getCharClass()); - document = "charClass: 1\n"; - bean = (TestBean1) yaml.load(document); - assertEquals(Character.valueOf('1'), bean.getCharClass()); - } - - public void testNoEmptyConstructor() { - Yaml yaml = new Yaml(new Constructor(TestBean2.class)); - String document = "text: qwerty"; - try { - yaml.load(document); - fail("No empty constructor available"); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("NoSuchMethodException")); - } - TestBean2 bean = new TestBean2(); - assertEquals("", bean.getText()); - } - - private class TestBean2 { - private String text; - - public TestBean2() { - setText(""); - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - } - - public void testPrivateMethod() { - // TODO: Are we sure no private ???? - Yaml yaml = new Yaml(new Constructor(TestBean2.class)); - String document = "text: qwerty"; - try { - yaml.load(document); - fail("Private method cannot be called."); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("NoSuchMethodException")); - } - } - - public void testKeyNotScalar() { - Yaml yaml = new Yaml(new Constructor(TestBean1.class)); - String document = "[1, 2]: qwerty"; - try { - yaml.load(document); - fail("Keys must be scalars."); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("Keys must be scalars but found")); - } - } - - public void testInvalidKey() { - Yaml yaml = new Yaml(new Constructor(TestBean1.class)); - String document = "something: qwerty"; - try { - yaml.load(document); - fail("Non-existing property must fail."); - } catch (Exception e) { - assertTrue(e.getMessage(), - e.getMessage().contains("Unable to find property 'something'")); - } - } - - public void testStaticField() { - Yaml yaml = new Yaml(new Constructor(TestBean1.class)); - String document = "staticInteger: 123"; - try { - yaml.load(document); - fail("Staic variables must not be used."); - } catch (Exception e) { - assertTrue(e.getMessage(), - e.getMessage().contains("Unable to find property 'staticInteger'")); - } - } - - public void testScalarContructor() { - Yaml yaml = new Yaml(new Constructor(Parent1.class)); - String document = "id: 123\nchild: 25"; - Parent1 parent = (Parent1) yaml.load(document); - assertEquals("123", parent.getId()); - Child1 child = parent.getChild(); - assertEquals(new Integer(25), child.getCode()); - } - - public void testScalarContructorException() { - Yaml yaml = new Yaml(new Constructor(ExceptionParent.class)); - String document = "id: 123\nchild: 25"; - try { - yaml.load(document); - fail("ExceptionParent should not be created."); - } catch (Exception e) { - assertTrue( - e.getMessage(), - e.getMessage().contains( - "Can't construct a java object for scalar tag:yaml.org,2002:int")); - } - } - - static public class ExceptionParent { - private String id; - private ExceptionChild child; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public ExceptionChild getChild() { - return child; - } - - public void setChild(ExceptionChild child) { - this.child = child; - } - - } - - public static class ExceptionChild { - private Integer code; - - public ExceptionChild(Integer code) { - throw new RuntimeException("ExceptionChild cannot be created."); - } - - public Integer getCode() { - return code; - } + public void testPrimitivesConstructor() { + Yaml yaml = new Yaml(new Constructor(TestBean1.class)); + String document = Util.getLocalResource("constructor/test-primitives1.yaml"); + TestBean1 result = yaml.load(document); + assertNotNull(result); + assertEquals(Byte.valueOf((byte) 1), result.getByteClass()); + assertEquals((byte) -3, result.getBytePrimitive()); + assertEquals(Short.valueOf((short) 0), result.getShortClass()); + assertEquals((short) -13, result.getShortPrimitive()); + assertEquals(Integer.valueOf(5), result.getInteger()); + assertEquals(17, result.getIntPrimitive()); + assertEquals("the text", result.getText()); + assertEquals("13", result.getId()); + assertEquals(Long.valueOf(11111111111L), result.getLongClass()); + assertEquals(9999999999L, result.getLongPrimitive()); + assertEquals(Boolean.TRUE, result.getBooleanClass()); + assertTrue(result.isBooleanPrimitive()); + assertEquals(Character.valueOf('2'), result.getCharClass()); + assertEquals('#', result.getCharPrimitive()); + assertEquals(new BigInteger("1234567890123456789012345678901234567890"), + result.getBigInteger()); + assertEquals(Float.valueOf(2), result.getFloatClass()); + assertEquals(Float.valueOf(3.1416f), result.getFloatPrimitive()); + assertEquals(Double.valueOf(4), result.getDoubleClass()); + assertEquals(Double.valueOf(11200), result.getDoublePrimitive()); + assertEquals(1199836800000L, result.getDate().getTime()); + assertEquals("public", result.publicField); + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yamlToDump = new Yaml(options); + String output = yamlToDump.dump(result); + TestBean1 result2 = yaml.load(output); + assertNotNull(result2); + TestBean1 result3 = new Yaml().load(output); + assertNotNull(result3); + } + + public void testNoClassConstructor() { + try { + new Yaml(new Constructor((Class<? extends Object>) null)); + fail("Class must be provided."); + } catch (NullPointerException e) { + assertEquals("Root class must be provided.", e.getMessage()); + } + } + + public void testNoClassConstructorString() throws ClassNotFoundException { + try { + new Yaml(new Constructor((String) null)); + fail("Class must be provided."); + } catch (NullPointerException e) { + assertEquals("Root type must be provided.", e.getMessage()); + } + } + + public void testNoClassConstructorEmptyString() throws ClassNotFoundException { + try { + new Yaml(new Constructor(" ")); + fail("Class must be provided."); + } catch (YAMLException e) { + assertEquals("Root type must be provided.", e.getMessage()); + } + } + + public void testCharacter() { + Yaml yaml = new Yaml(new Constructor(TestBean1.class)); + String document = "charClass: id"; + try { + yaml.load(document); + fail("Only one char must be allowed."); + } catch (Exception e) { + assertTrue(e.getMessage(), + e.getMessage().contains("Invalid node Character: 'id'; length: 2")); + } + document = "charClass: #"; + TestBean1 bean = yaml.load(document); + assertNull("Null must be accepted.", bean.getCharClass()); + document = "charClass: ''"; + bean = yaml.load(document); + assertNull("Null must be accepted.", bean.getCharClass()); + document = "charClass:\n"; + bean = yaml.load(document); + assertNull("Null must be accepted.", bean.getCharClass()); + document = "charClass: 1\n"; + bean = yaml.load(document); + assertEquals(Character.valueOf('1'), bean.getCharClass()); + } + + public void testNoEmptyConstructor() { + Yaml yaml = new Yaml(new Constructor(TestBean2.class)); + String document = "text: qwerty"; + try { + yaml.load(document); + fail("No empty constructor available"); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("NoSuchMethodException")); + } + TestBean2 bean = new TestBean2(); + assertEquals("", bean.getText()); + } + + private class TestBean2 { + + private String text; + + public TestBean2() { + setText(""); + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + } + + public void testPrivateMethod() { + Yaml yaml = new Yaml(new Constructor(TestBean2.class)); + String document = "text: qwerty"; + try { + yaml.load(document); + fail("Private method cannot be called."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("NoSuchMethodException")); + } + } + + public void testKeyNotScalar() { + Yaml yaml = new Yaml(new Constructor(TestBean1.class)); + String document = "[1, 2]: qwerty"; + try { + yaml.load(document); + fail("Keys must be scalars."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("Keys must be scalars but found")); + } + } + + public void testInvalidKey() { + Yaml yaml = new Yaml(new Constructor(TestBean1.class)); + String document = "something: qwerty"; + try { + yaml.load(document); + fail("Non-existing property must fail."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("Unable to find property 'something'")); + } + } + + public void testStaticField() { + Yaml yaml = new Yaml(new Constructor(TestBean1.class)); + String document = "staticInteger: 123"; + try { + yaml.load(document); + fail("Staic variables must not be used."); + } catch (Exception e) { + assertTrue(e.getMessage(), + e.getMessage().contains("Unable to find property 'staticInteger'")); + } + } + + public void testScalarContructor() { + Yaml yaml = new Yaml(new Constructor(Parent1.class)); + String document = "id: 123\nchild: 25"; + Parent1 parent = yaml.load(document); + assertEquals("123", parent.getId()); + Child1 child = parent.getChild(); + assertEquals(Integer.valueOf(25), child.getCode()); + } + + public void testScalarContructorException() { + Yaml yaml = new Yaml(new Constructor(ExceptionParent.class)); + String document = "id: 123\nchild: 25"; + try { + yaml.load(document); + fail("ExceptionParent should not be created."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage() + .contains("Can't construct a java object for scalar tag:yaml.org,2002:int")); + } + } + + static public class ExceptionParent { + + private String id; + private ExceptionChild child; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public ExceptionChild getChild() { + return child; + } + + public void setChild(ExceptionChild child) { + this.child = child; + } + + } + + public static class ExceptionChild { + + private final Integer code; + + public ExceptionChild(Integer code) { + throw new RuntimeException("ExceptionChild cannot be created."); + } + + public Integer getCode() { + return code; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalBeanConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalBeanConstructorTest.java index e5f0fb46..543bcd47 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalBeanConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalBeanConstructorTest.java @@ -1,58 +1,53 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.math.BigDecimal; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class BigDecimalBeanConstructorTest extends TestCase { - public void testRepresentor() { - BigDecimalJavaBean bean = new BigDecimalJavaBean(); - bean.setAmount(1.5f); - bean.setNumber(new BigDecimal("3.1416")); - Yaml yaml = new Yaml(); - String output = yaml.dump(bean); - String className = this.getClass().getPackage().getName(); - assertEquals("!!" + className + ".BigDecimalJavaBean {amount: 1.5, number: 3.1416}\n", - output); - } + public void testRepresentor() { + BigDecimalJavaBean bean = new BigDecimalJavaBean(); + bean.setAmount(1.5f); + bean.setNumber(new BigDecimal("3.1416")); + Yaml yaml = new Yaml(); + String output = yaml.dump(bean); + String className = this.getClass().getPackage().getName(); + assertEquals("!!" + className + ".BigDecimalJavaBean {amount: 1.5, number: 3.1416}\n", output); + } - public void testConstructor() { - String className = "!!" + this.getClass().getPackage().getName() - + ".BigDecimalJavaBean {amount: 1.5, number: 3.1416}"; - Yaml yaml = new Yaml(); - BigDecimalJavaBean bean = (BigDecimalJavaBean) yaml.load(className); - assertNotNull(bean); - assertTrue(1.5 - bean.getAmount() < 0.0000001); - assertTrue((new BigDecimal("3.1416")).add(bean.getNumber().negate()).doubleValue() < 0.0000001); - } + public void testConstructor() { + String className = "!!" + this.getClass().getPackage().getName() + + ".BigDecimalJavaBean {amount: 1.5, number: 3.1416}"; + Yaml yaml = new Yaml(); + BigDecimalJavaBean bean = yaml.load(className); + assertNotNull(bean); + assertTrue(1.5 - bean.getAmount() < 0.0000001); + assertTrue((new BigDecimal("3.1416")).add(bean.getNumber().negate()).doubleValue() < 0.0000001); + } - public void testConstructorAtomic() { - String className = "!!" + this.getClass().getPackage().getName() - + ".AtomicJavaBean {amount: 1.5, atomic: 0}"; - Yaml yaml = new Yaml(); - try { - yaml.load(className); - fail("AtomicLong is not supported."); - } catch (Exception e) { - assertEquals("argument type mismatch", e.getCause().getMessage()); - } + public void testConstructorAtomic() { + String className = + "!!" + this.getClass().getPackage().getName() + ".AtomicJavaBean {amount: 1.5, atomic: 0}"; + Yaml yaml = new Yaml(); + try { + yaml.load(className); + fail("AtomicLong is not supported."); + } catch (Exception e) { + assertEquals("argument type mismatch", e.getCause().getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalJavaBean.java b/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalJavaBean.java index 516f4cd3..b558c487 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalJavaBean.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/BigDecimalJavaBean.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.math.BigDecimal; public class BigDecimalJavaBean { - private BigDecimal number; - private float amount; - public BigDecimal getNumber() { - return number; - } + private BigDecimal number; + private float amount; - public void setNumber(BigDecimal number) { - this.number = number; - } + public BigDecimal getNumber() { + return number; + } - public float getAmount() { - return amount; - } + public void setNumber(BigDecimal number) { + this.number = number; + } - public void setAmount(float amount) { - this.amount = amount; - } -}
\ No newline at end of file + public float getAmount() { + return amount; + } + + public void setAmount(float amount) { + this.amount = amount; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/constructor/Car.java b/src/test/java/org/yaml/snakeyaml/constructor/Car.java index d19a713a..c58d1ffa 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/Car.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/Car.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.List; public class Car { - private String plate; - private List<Wheel> wheels; - public String getPlate() { - return plate; - } + private String plate; + private List<Wheel> wheels; - public void setPlate(String plate) { - this.plate = plate; - } + public String getPlate() { + return plate; + } - public List<Wheel> getWheels() { - return wheels; - } + public void setPlate(String plate) { + this.plate = plate; + } - public void setWheels(List<Wheel> wheels) { - this.wheels = wheels; - } + public List<Wheel> getWheels() { + return wheels; + } + + public void setWheels(List<Wheel> wheels) { + this.wheels = wheels; + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/Child1.java b/src/test/java/org/yaml/snakeyaml/constructor/Child1.java index 592265c7..2ba4a9c1 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/Child1.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/Child1.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; public class Child1 { - private Integer code; - public Child1(Integer code) { - this.code = code; - } + private final Integer code; - public Integer getCode() { - return code; - } -}
\ No newline at end of file + public Child1(Integer code) { + this.code = code; + } + + public Integer getCode() { + return code; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/constructor/ClassTagsTest.java b/src/test/java/org/yaml/snakeyaml/constructor/ClassTagsTest.java index b14c5e79..07b69059 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/ClassTagsTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/ClassTagsTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -29,77 +25,77 @@ import org.yaml.snakeyaml.representer.Representer; public class ClassTagsTest extends TestCase { - public void testDefaultRepresenter() { - Car car = new Car(); - car.setPlate("12-XP-F4"); - List<Wheel> wheels = new ArrayList<Wheel>(); - for (int i = 1; i < 6; i++) { - Wheel wheel = new Wheel(); - wheel.setId(i); - wheels.add(wheel); - } - car.setWheels(wheels); - assertEquals(Util.getLocalResource("constructor/car-with-tags.yaml"), new Yaml().dump(car)); + public void testDefaultRepresenter() { + Car car = new Car(); + car.setPlate("12-XP-F4"); + List<Wheel> wheels = new ArrayList<Wheel>(); + for (int i = 1; i < 6; i++) { + Wheel wheel = new Wheel(); + wheel.setId(i); + wheels.add(wheel); } + car.setWheels(wheels); + assertEquals(Util.getLocalResource("constructor/car-with-tags.yaml"), new Yaml().dump(car)); + } - public void testDumpClassTag() { - Car car = new Car(); - car.setPlate("12-XP-F4"); - List<Wheel> wheels = new ArrayList<Wheel>(); - for (int i = 1; i < 6; i++) { - Wheel wheel = new Wheel(); - wheel.setId(i); - wheels.add(wheel); - } - car.setWheels(wheels); - Representer representer = new Representer(); - representer.addClassTag(Car.class, new Tag("!car")); - representer.addClassTag(Wheel.class, Tag.MAP); - Yaml yaml = new Yaml(representer); - String output = yaml.dump(car); - assertEquals(Util.getLocalResource("constructor/car-without-tags.yaml"), output); + public void testDumpClassTag() { + Car car = new Car(); + car.setPlate("12-XP-F4"); + List<Wheel> wheels = new ArrayList<Wheel>(); + for (int i = 1; i < 6; i++) { + Wheel wheel = new Wheel(); + wheel.setId(i); + wheels.add(wheel); } + car.setWheels(wheels); + Representer representer = new Representer(); + representer.addClassTag(Car.class, new Tag("!car")); + representer.addClassTag(Wheel.class, Tag.MAP); + Yaml yaml = new Yaml(representer); + String output = yaml.dump(car); + assertEquals(Util.getLocalResource("constructor/car-without-tags.yaml"), output); + } - public void testLoadUnknounClassTag() { - try { - Yaml yaml = new Yaml(); - yaml.load(Util.getLocalResource("constructor/car-without-tags.yaml")); - fail("Must fail because of unknown tag: !car"); - } catch (YAMLException e) { - assertTrue(e.getMessage().contains("Invalid tag: !car")); - } - + public void testLoadUnknounClassTag() { + try { + Yaml yaml = new Yaml(); + yaml.load(Util.getLocalResource("constructor/car-without-tags.yaml")); + fail("Must fail because of unknown tag: !car"); + } catch (YAMLException e) { + assertTrue(e.getMessage().contains("Invalid tag: !car")); } - public void testLoadClassTag() { - Constructor constructor = new Constructor(); - constructor.addTypeDescription(new TypeDescription(Car.class, "!car")); - Yaml yaml = new Yaml(constructor); - String source = Util.getLocalResource("constructor/car-without-tags.yaml"); - Car car = (Car) yaml.load(source); - assertEquals("12-XP-F4", car.getPlate()); - List<Wheel> wheels = car.getWheels(); - assertNotNull(wheels); - assertEquals(5, wheels.size()); - } + } - public void testNullDescription() { - Constructor constructor = new Constructor(); - try { - constructor.addTypeDescription(null); - fail("Description is required."); - } catch (Exception e) { - assertEquals("TypeDescription is required.", e.getMessage()); - } - } + public void testLoadClassTag() { + Constructor constructor = new Constructor(); + constructor.addTypeDescription(new TypeDescription(Car.class, "!car")); + Yaml yaml = new Yaml(constructor); + String source = Util.getLocalResource("constructor/car-without-tags.yaml"); + Car car = yaml.load(source); + assertEquals("12-XP-F4", car.getPlate()); + List<Wheel> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + } - public void testLoadClassNoRoot() { - Constructor constructor = new Constructor(new TypeDescription(Car.class)); - Yaml yaml = new Yaml(constructor); - Car car = (Car) yaml.load(Util.getLocalResource("constructor/car-no-root-class.yaml")); - assertEquals("12-XP-F4", car.getPlate()); - List<Wheel> wheels = car.getWheels(); - assertNotNull(wheels); - assertEquals(5, wheels.size()); + public void testNullDescription() { + Constructor constructor = new Constructor(); + try { + constructor.addTypeDescription(null); + fail("Description is required."); + } catch (Exception e) { + assertEquals("TypeDescription is required.", e.getMessage()); } + } + + public void testLoadClassNoRoot() { + Constructor constructor = new Constructor(new TypeDescription(Car.class)); + Yaml yaml = new Yaml(constructor); + Car car = yaml.load(Util.getLocalResource("constructor/car-no-root-class.yaml")); + assertEquals("12-XP-F4", car.getPlate()); + List<Wheel> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/ConstructorMappingTest.java b/src/test/java/org/yaml/snakeyaml/constructor/ConstructorMappingTest.java index 7d6b1f39..6a68ab92 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/ConstructorMappingTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/ConstructorMappingTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.parser.Parser; import org.yaml.snakeyaml.parser.ParserImpl; @@ -29,39 +25,40 @@ import org.yaml.snakeyaml.resolver.Resolver; public class ConstructorMappingTest extends TestCase { - @SuppressWarnings("unchecked") - public void testGetDefaultMap() { - String data = "{ one: 1, two: 2, three: 3 }"; - Map<Object, Object> map = (Map<Object, Object>) construct(new CustomConstructor(), data); - assertNotNull(map); - assertTrue(map.getClass().toString(), map instanceof TreeMap); - } + @SuppressWarnings("unchecked") + public void testGetDefaultMap() { + String data = "{ one: 1, two: 2, three: 3 }"; + Map<Object, Object> map = (Map<Object, Object>) construct(new CustomConstructor(), data); + assertNotNull(map); + assertTrue(map.getClass().toString(), map instanceof TreeMap); + } - @SuppressWarnings("unchecked") - public void testGetArrayList() { - String data = "{ one: 1, two: 2, three: 3 }"; - Map<Object, Object> map = (Map<Object, Object>) construct(data); - assertNotNull(map); - assertTrue(map.getClass().toString(), map instanceof LinkedHashMap); - } + @SuppressWarnings("unchecked") + public void testGetArrayList() { + String data = "{ one: 1, two: 2, three: 3 }"; + Map<Object, Object> map = (Map<Object, Object>) construct(data); + assertNotNull(map); + assertTrue(map.getClass().toString(), map instanceof LinkedHashMap); + } - private Object construct(String data) { - return construct(new Constructor(), data); - } + private Object construct(String data) { + return construct(new Constructor(), data); + } - private Object construct(Constructor constructor, String data) { - StreamReader reader = new StreamReader(data); - Parser parser = new ParserImpl(reader); - Resolver resolver = new Resolver(); - Composer composer = new Composer(parser, resolver); - constructor.setComposer(composer); - return constructor.getSingleData(Object.class); - } + private Object construct(Constructor constructor, String data) { + StreamReader reader = new StreamReader(data); + Parser parser = new ParserImpl(reader); + Resolver resolver = new Resolver(); + Composer composer = new Composer(parser, resolver); + constructor.setComposer(composer); + return constructor.getSingleData(Object.class); + } + + class CustomConstructor extends Constructor { - class CustomConstructor extends Constructor { - @Override - protected Map<Object, Object> createDefaultMap() { - return new TreeMap<Object, Object>(); - } + @Override + protected Map<Object, Object> createDefaultMap(int initSize) { + return new TreeMap<Object, Object>(); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/ConstructorSequenceTest.java b/src/test/java/org/yaml/snakeyaml/constructor/ConstructorSequenceTest.java index 26412015..45459b61 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/ConstructorSequenceTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/ConstructorSequenceTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.parser.Parser; @@ -29,57 +25,58 @@ import org.yaml.snakeyaml.resolver.Resolver; public class ConstructorSequenceTest extends TestCase { - public void testGetList() { - String data = "[ 1, 2, 3 ]"; - List<Object> list = construct(new CustomConstructor(), data); - assertNotNull(list); - assertTrue(list.getClass().toString(), list instanceof ArrayList<?>); - } + public void testGetList() { + String data = "[ 1, 2, 3 ]"; + List<Object> list = construct(new CustomConstructor(), data); + assertNotNull(list); + assertTrue(list.getClass().toString(), list instanceof ArrayList<?>); + } - public void testGetArrayList() { - String data = "[ 1, 2, 3 ]"; - List<Object> list = construct(data); - assertNotNull(list); - assertTrue(list.getClass().toString(), list instanceof ArrayList<?>); - } + public void testGetArrayList() { + String data = "[ 1, 2, 3 ]"; + List<Object> list = construct(data); + assertNotNull(list); + assertTrue(list.getClass().toString(), list instanceof ArrayList<?>); + } - public void testDumpList() { - List<Integer> l = new ArrayList<Integer>(2); - l.add(1); - l.add(2); - Yaml yaml = new Yaml(); - String result = yaml.dump(l); - assertEquals("[1, 2]\n", result); - } + public void testDumpList() { + List<Integer> l = new ArrayList<Integer>(2); + l.add(1); + l.add(2); + Yaml yaml = new Yaml(); + String result = yaml.dump(l); + assertEquals("[1, 2]\n", result); + } - public void testDumpListSameIntegers() { - List<Integer> l = new ArrayList<Integer>(2); - l.add(1); - l.add(1); - Yaml yaml = new Yaml(); - String result = yaml.dump(l); - assertEquals("[1, 1]\n", result); - } + public void testDumpListSameIntegers() { + List<Integer> l = new ArrayList<Integer>(2); + l.add(1); + l.add(1); + Yaml yaml = new Yaml(); + String result = yaml.dump(l); + assertEquals("[1, 1]\n", result); + } - private List<Object> construct(String data) { - return construct(new Constructor(), data); - } + private List<Object> construct(String data) { + return construct(new Constructor(), data); + } - @SuppressWarnings("unchecked") - private List<Object> construct(Constructor constructor, String data) { - StreamReader reader = new StreamReader(data); - Parser parser = new ParserImpl(reader); - Resolver resolver = new Resolver(); - Composer composer = new Composer(parser, resolver); - constructor.setComposer(composer); - List<Object> result = (List<Object>) constructor.getSingleData(Object.class); - return result; - } + @SuppressWarnings("unchecked") + private List<Object> construct(Constructor constructor, String data) { + StreamReader reader = new StreamReader(data); + Parser parser = new ParserImpl(reader); + Resolver resolver = new Resolver(); + Composer composer = new Composer(parser, resolver); + constructor.setComposer(composer); + List<Object> result = (List<Object>) constructor.getSingleData(Object.class); + return result; + } + + class CustomConstructor extends Constructor { - class CustomConstructor extends Constructor { - @Override - protected List<Object> createDefaultList(int initSize) { - return new ArrayList<Object>(initSize); - } + @Override + protected List<Object> createDefaultList(int initSize) { + return new ArrayList<Object>(initSize); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/ConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/ConstructorTest.java index 47f9805b..c9b362cd 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/ConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/ConstructorTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,102 +17,99 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.TimeZone; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class ConstructorTest extends TestCase { - @SuppressWarnings("unchecked") - public void testMapOrder() { - String data = "one: zzz\ntwo: ccc\nthree: bbb\nfour: aaa"; - Object map = construct(data); - assertNotNull(map); - assertTrue(map.getClass().toString(), map instanceof LinkedHashMap); - Map<String, String> m = (Map<String, String>) map; - assertEquals(4, m.keySet().size()); - Iterator<String> iter = m.keySet().iterator(); - assertEquals("one", iter.next()); - assertEquals("two", iter.next()); - assertEquals("three", iter.next()); - assertEquals("four", iter.next()); - } + @SuppressWarnings("unchecked") + public void testMapOrder() { + String data = "one: zzz\ntwo: ccc\nthree: bbb\nfour: aaa"; + Object map = construct(data); + assertNotNull(map); + assertTrue(map.getClass().toString(), map instanceof LinkedHashMap); + Map<String, String> m = (Map<String, String>) map; + assertEquals(4, m.keySet().size()); + Iterator<String> iter = m.keySet().iterator(); + assertEquals("one", iter.next()); + assertEquals("two", iter.next()); + assertEquals("three", iter.next()); + assertEquals("four", iter.next()); + } - /** - * create JavaBean - */ - public void testGetBeanAssumeClass() { - String data = "--- !!org.yaml.snakeyaml.constructor.Person\nfirstName: Andrey\nage: 99"; - Object obj = construct(data); - assertNotNull(obj); - assertTrue("Unexpected: " + obj.getClass().toString(), obj instanceof Person); - Person person = (Person) obj; - assertEquals("Andrey", person.getFirstName()); - assertNull(person.getLastName()); - assertEquals(99, person.getAge().intValue()); - } + /** + * create JavaBean + */ + public void testGetBeanAssumeClass() { + String data = "--- !!org.yaml.snakeyaml.constructor.Person\nfirstName: Andrey\nage: 99"; + Object obj = construct(data); + assertNotNull(obj); + assertTrue("Unexpected: " + obj.getClass().toString(), obj instanceof Person); + Person person = (Person) obj; + assertEquals("Andrey", person.getFirstName()); + assertNull(person.getLastName()); + assertEquals(99, person.getAge().intValue()); + } - /** - * create instance using constructor arguments - */ - public void testGetConstructorBean() { - String data = "--- !!org.yaml.snakeyaml.constructor.Person [ Andrey, Somov, 99 ]"; - Object obj = construct(data); - assertNotNull(obj); - assertTrue(obj.getClass().toString(), obj instanceof Person); - Person person = (Person) obj; - assertEquals("Andrey", person.getFirstName()); - assertEquals("Somov", person.getLastName()); - assertEquals(99, person.getAge().intValue()); - } + /** + * create instance using constructor arguments + */ + public void testGetConstructorBean() { + String data = "--- !!org.yaml.snakeyaml.constructor.Person [ Andrey, Somov, 99 ]"; + Object obj = construct(data); + assertNotNull(obj); + assertTrue(obj.getClass().toString(), obj instanceof Person); + Person person = (Person) obj; + assertEquals("Andrey", person.getFirstName()); + assertEquals("Somov", person.getLastName()); + assertEquals(99, person.getAge().intValue()); + } - /** - * create instance using scalar argument - */ - public void testGetConstructorFromScalar() { - String data = "--- !!org.yaml.snakeyaml.constructor.Person 'Somov'"; - Object obj = construct(data); - assertNotNull(obj); - assertTrue(obj.getClass().toString(), obj instanceof Person); - Person person = (Person) obj; - assertNull("Andrey", person.getFirstName()); - assertEquals("Somov", person.getLastName()); - assertNull(person.getAge()); - } + /** + * create instance using scalar argument + */ + public void testGetConstructorFromScalar() { + String data = "--- !!org.yaml.snakeyaml.constructor.Person 'Somov'"; + Object obj = construct(data); + assertNotNull(obj); + assertTrue(obj.getClass().toString(), obj instanceof Person); + Person person = (Person) obj; + assertNull("Andrey", person.getFirstName()); + assertEquals("Somov", person.getLastName()); + assertNull(person.getAge()); + } - public void testJavaBeanLoad() { - java.util.Calendar cal = java.util.Calendar.getInstance(TimeZone.getTimeZone("UTC")); - cal.clear(); - cal.set(1982, 5 - 1, 3); // Java's months are zero-based... + public void testJavaBeanLoad() { + java.util.Calendar cal = java.util.Calendar.getInstance(TimeZone.getTimeZone("UTC")); + cal.clear(); + cal.set(1982, 5 - 1, 3); // Java's months are zero-based... - TestBean expected = new TestBean("Ola Bini", 24, cal.getTime()); - assertEquals( - expected, - construct("--- !!org.yaml.snakeyaml.constructor.TestBean\nname: Ola Bini\nage: 24\nborn: 1982-05-03\n")); - } + TestBean expected = new TestBean("Ola Bini", 24, cal.getTime()); + assertEquals(expected, construct( + "--- !!org.yaml.snakeyaml.constructor.TestBean\nname: Ola Bini\nage: 24\nborn: 1982-05-03\n")); + } - public void testWrongName() { - try { - construct("--- !!org.yaml.snakeyaml.constructor.TestBean\nwrongName: No one\nage: 24\nborn: 1982-05-03\n"); - fail("IntrospectionException expected."); - } catch (Exception e) { - // TODO improve the error message - the pointer should be at the - // property name, not value - assertEquals( - "Cannot create property=wrongName for JavaBean=#<org.jvyaml.TestBean name=\"null\" age=0 born=\"null\">\n" - + " in 'string', line 1, column 5:\n" - + " --- !!org.yaml.snakeyaml.constructor ... \n" - + " ^\n" - + "Unable to find property 'wrongName' on class: org.yaml.snakeyaml.constructor.TestBean\n" - + " in 'string', line 2, column 12:\n" - + " wrongName: No one\n" - + " ^\n", e.getMessage()); - } + public void testWrongName() { + try { + construct( + "--- !!org.yaml.snakeyaml.constructor.TestBean\nwrongName: No one\nage: 24\nborn: 1982-05-03\n"); + fail("IntrospectionException expected."); + } catch (Exception e) { + // TODO improve the error message - the pointer should be at the + // property name, not value + assertEquals( + "Cannot create property=wrongName for JavaBean=#<org.jvyaml.TestBean name=\"null\" age=0 born=\"null\">\n" + + " in 'string', line 1, column 5:\n" + + " --- !!org.yaml.snakeyaml.constructor ... \n" + " ^\n" + + "Unable to find property 'wrongName' on class: org.yaml.snakeyaml.constructor.TestBean\n" + + " in 'string', line 2, column 12:\n" + " wrongName: No one\n" + + " ^\n", + e.getMessage()); } + } - private Object construct(String data) { - Yaml yaml = new Yaml(); - return yaml.load(data); - } + private Object construct(String data) { + Yaml yaml = new Yaml(); + return yaml.load(data); + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructorTest.java index c236e234..2287aa9a 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/CustomClassLoaderConstructorTest.java @@ -1,83 +1,81 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class CustomClassLoaderConstructorTest extends TestCase { - public void testGetClassForNameNull() { - try { - new CustomClassLoaderConstructor(null); - fail(); - } catch (Exception e) { - assertEquals("Loader must be provided.", e.getMessage()); - } + public void testGetClassForNameNull() { + try { + new CustomClassLoaderConstructor(null); + fail(); + } catch (Exception e) { + assertEquals("Loader must be provided.", e.getMessage()); } + } - public void testGetClassForName() { - CustomClassLoaderConstructor constr = new CustomClassLoaderConstructor( - CustomClassLoaderConstructorTest.class.getClassLoader()); - Yaml yaml = new Yaml(constr); - String s = (String) yaml.load("abc"); - assertEquals("abc", s); - } + public void testGetClassForName() { + CustomClassLoaderConstructor constr = + new CustomClassLoaderConstructor(CustomClassLoaderConstructorTest.class.getClassLoader()); + Yaml yaml = new Yaml(constr); + String s = yaml.load("abc"); + assertEquals("abc", s); + } - public void testGetClassForNameWithRoot() throws ClassNotFoundException { - Class<?> clazz = Class.forName( - "org.yaml.snakeyaml.constructor.CustomClassLoaderConstructorTest$LoaderBean", true, - CustomClassLoaderConstructorTest.class.getClassLoader()); - CustomClassLoaderConstructor constr = new CustomClassLoaderConstructor(clazz, - CustomClassLoaderConstructorTest.class.getClassLoader()); - Yaml yaml = new Yaml(constr); - LoaderBean bean = (LoaderBean) yaml.load("{name: Andrey, number: 555}"); - assertEquals("Andrey", bean.getName()); - assertEquals(555, bean.getNumber()); - } + public void testGetClassForNameWithRoot() throws ClassNotFoundException { + Class<?> clazz = + Class.forName("org.yaml.snakeyaml.constructor.CustomClassLoaderConstructorTest$LoaderBean", + true, CustomClassLoaderConstructorTest.class.getClassLoader()); + CustomClassLoaderConstructor constr = new CustomClassLoaderConstructor(clazz, + CustomClassLoaderConstructorTest.class.getClassLoader()); + Yaml yaml = new Yaml(constr); + LoaderBean bean = yaml.load("{name: Andrey, number: 555}"); + assertEquals("Andrey", bean.getName()); + assertEquals(555, bean.getNumber()); + } - public void testGetClassForNameBean() { - CustomClassLoaderConstructor constr = new CustomClassLoaderConstructor( - CustomClassLoaderConstructorTest.class.getClassLoader()); - Yaml yaml = new Yaml(constr); - LoaderBean bean = (LoaderBean) yaml - .load("!!org.yaml.snakeyaml.constructor.CustomClassLoaderConstructorTest$LoaderBean {name: Andrey, number: 555}"); - assertEquals("Andrey", bean.getName()); - assertEquals(555, bean.getNumber()); - } + public void testGetClassForNameBean() { + CustomClassLoaderConstructor constr = + new CustomClassLoaderConstructor(CustomClassLoaderConstructorTest.class.getClassLoader()); + Yaml yaml = new Yaml(constr); + LoaderBean bean = yaml.load( + "!!org.yaml.snakeyaml.constructor.CustomClassLoaderConstructorTest$LoaderBean {name: Andrey, number: 555}"); + assertEquals("Andrey", bean.getName()); + assertEquals(555, bean.getNumber()); + } - public static class LoaderBean { - private String name; - private int number; + public static class LoaderBean { - public String getName() { - return name; - } + private String name; + private int number; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } - public int getNumber() { - return number; - } + public int getNumber() { + return number; + } - public void setNumber(int number) { - this.number = number; - } + public void setNumber(int number) { + this.number = number; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/FilterClassesConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/FilterClassesConstructorTest.java index 734a58e4..edf1e192 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/FilterClassesConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/FilterClassesConstructorTest.java @@ -1,74 +1,74 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class FilterClassesConstructorTest extends TestCase { - public void testGetClassForName() { - Yaml yaml = new Yaml(new FilterConstructor(true)); - String input = "!!org.yaml.snakeyaml.constructor.FilterClassesConstructorTest$FilteredBean {name: Andrey, number: 543}"; - try { - yaml.load(input); - fail("Filter is expected."); - } catch (Exception e) { - assertTrue(e.getMessage().contains("Filter is applied.")); - } - yaml = new Yaml(new FilterConstructor(false)); - FilteredBean s = (FilteredBean) yaml.load(input); - assertEquals("Andrey", s.getName()); + public void testGetClassForName() { + Yaml yaml = new Yaml(new FilterConstructor(true)); + String input = + "!!org.yaml.snakeyaml.constructor.FilterClassesConstructorTest$FilteredBean {name: Andrey, number: 543}"; + try { + yaml.load(input); + fail("Filter is expected."); + } catch (Exception e) { + assertTrue(e.getMessage().contains("Filter is applied.")); } + yaml = new Yaml(new FilterConstructor(false)); + FilteredBean s = yaml.load(input); + assertEquals("Andrey", s.getName()); + } + + class FilterConstructor extends Constructor { - class FilterConstructor extends Constructor { - private boolean filter; + private final boolean filter; - public FilterConstructor(boolean f) { - filter = f; - } + public FilterConstructor(boolean f) { + filter = f; + } - @Override - protected Class<?> getClassForName(String name) throws ClassNotFoundException { - if (filter && name.startsWith("org.yaml")) { - throw new RuntimeException("Filter is applied."); - } - return super.getClassForName(name); - } + @Override + protected Class<?> getClassForName(String name) throws ClassNotFoundException { + if (filter && name.startsWith("org.yaml")) { + throw new RuntimeException("Filter is applied."); + } + return super.getClassForName(name); } + } - public static class FilteredBean { - private String name; - private int number; + public static class FilteredBean { - public String getName() { - return name; - } + private String name; + private int number; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public int getNumber() { - return number; - } + public void setName(String name) { + this.name = name; + } + + public int getNumber() { + return number; + } - public void setNumber(int number) { - this.number = number; - } + public void setNumber(int number) { + this.number = number; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/ImplicitTagsTest.java b/src/test/java/org/yaml/snakeyaml/constructor/ImplicitTagsTest.java index 0c1482de..6f5d7463 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/ImplicitTagsTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/ImplicitTagsTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,9 +17,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; @@ -31,129 +27,130 @@ import org.yaml.snakeyaml.representer.Representer; public class ImplicitTagsTest extends TestCase { - public void testDefaultRepresenter() { - CarWithWheel car1 = new CarWithWheel(); - car1.setPlate("12-XP-F4"); - Wheel wheel = new Wheel(); - wheel.setId(2); - car1.setWheel(wheel); - Map<String, Integer> map = new HashMap<String, Integer>(); - map.put("id", 3); - car1.setMap(map); - car1.setPart(new Wheel(4)); - car1.setYear("2008"); - String carYaml1 = new Yaml().dump(car1); - assertEquals(Util.getLocalResource("constructor/carwheel-without-tags.yaml"), carYaml1); - CarWithWheel car2 = (CarWithWheel) new Yaml().load(carYaml1); - String carYaml2 = new Yaml().dump(car2); - assertEquals(carYaml1, carYaml2); + public void testDefaultRepresenter() { + CarWithWheel car1 = new CarWithWheel(); + car1.setPlate("12-XP-F4"); + Wheel wheel = new Wheel(); + wheel.setId(2); + car1.setWheel(wheel); + Map<String, Integer> map = new HashMap<String, Integer>(); + map.put("id", 3); + car1.setMap(map); + car1.setPart(new Wheel(4)); + car1.setYear("2008"); + String carYaml1 = new Yaml().dump(car1); + assertEquals(Util.getLocalResource("constructor/carwheel-without-tags.yaml"), carYaml1); + CarWithWheel car2 = new Yaml().load(carYaml1); + String carYaml2 = new Yaml().dump(car2); + assertEquals(carYaml1, carYaml2); + } + + public void testNoRootTag() { + CarWithWheel car1 = new CarWithWheel(); + car1.setPlate("12-XP-F4"); + Wheel wheel = new Wheel(); + wheel.setId(2); + car1.setWheel(wheel); + Map<String, Integer> map = new HashMap<String, Integer>(); + map.put("id", 3); + car1.setMap(map); + car1.setYear("2008"); + String carYaml1 = new Yaml().dumpAs(car1, Tag.MAP, FlowStyle.AUTO); + assertEquals(Util.getLocalResource("constructor/car-without-root-tag.yaml"), carYaml1); + // + Constructor contructor = new Constructor(CarWithWheel.class); + CarWithWheel car2 = new Yaml(contructor).load(carYaml1); + String carYaml2 = new Yaml().dumpAs(car2, Tag.MAP, FlowStyle.AUTO); + assertEquals(carYaml1, carYaml2); + } + + @SuppressWarnings("unchecked") + public void testRootMap() { + Map<Object, Object> car1 = new LinkedHashMap<Object, Object>(); + Wheel wheel = new Wheel(); + wheel.setId(2); + Map<String, Integer> map = new HashMap<String, Integer>(); + map.put("id", 3); + + car1.put("wheel", wheel); + car1.put("map", map); + car1.put("plate", "12-XP-F4"); + + String carYaml1 = new Yaml().dump(car1); + assertEquals(Util.getLocalResource("constructor/carwheel-root-map.yaml"), carYaml1); + Map<Object, Object> car2 = new Yaml().load(carYaml1); + assertEquals(car1, car2); + assertEquals(carYaml1, new Yaml().dump(car2)); + } + + public void testLoadClassTag() { + Constructor constructor = new Constructor(); + constructor.addTypeDescription(new TypeDescription(Car.class, "!car")); + Yaml yaml = new Yaml(constructor); + Car car = yaml.load(Util.getLocalResource("constructor/car-without-tags.yaml")); + assertEquals("12-XP-F4", car.getPlate()); + List<Wheel> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + Wheel w1 = wheels.get(0); + assertEquals(1, w1.getId()); + // + String carYaml1 = new Yaml().dump(car); + assertTrue(carYaml1.startsWith("!!org.yaml.snakeyaml.constructor.Car")); + // + Representer representer = new Representer(); + representer.addClassTag(Car.class, new Tag("!car")); + yaml = new Yaml(representer); + String carYaml2 = yaml.dump(car); + assertEquals(Util.getLocalResource("constructor/car-without-tags.yaml"), carYaml2); + } + + public static class CarWithWheel { + + private String plate; + private String year; + private Wheel wheel; + private Object part; + private Map<String, Integer> map; + + public String getPlate() { + return plate; } - public void testNoRootTag() { - CarWithWheel car1 = new CarWithWheel(); - car1.setPlate("12-XP-F4"); - Wheel wheel = new Wheel(); - wheel.setId(2); - car1.setWheel(wheel); - Map<String, Integer> map = new HashMap<String, Integer>(); - map.put("id", 3); - car1.setMap(map); - car1.setYear("2008"); - String carYaml1 = new Yaml().dumpAs(car1, Tag.MAP, FlowStyle.AUTO); - assertEquals(Util.getLocalResource("constructor/car-without-root-tag.yaml"), carYaml1); - // - Constructor contructor = new Constructor(CarWithWheel.class); - CarWithWheel car2 = (CarWithWheel) new Yaml(contructor).load(carYaml1); - String carYaml2 = new Yaml().dumpAs(car2, Tag.MAP, FlowStyle.AUTO); - assertEquals(carYaml1, carYaml2); + public void setPlate(String plate) { + this.plate = plate; } - @SuppressWarnings("unchecked") - public void testRootMap() { - Map<Object, Object> car1 = new LinkedHashMap<Object, Object>(); - Wheel wheel = new Wheel(); - wheel.setId(2); - Map<String, Integer> map = new HashMap<String, Integer>(); - map.put("id", 3); - - car1.put("wheel", wheel); - car1.put("map", map); - car1.put("plate", "12-XP-F4"); - - String carYaml1 = new Yaml().dump(car1); - assertEquals(Util.getLocalResource("constructor/carwheel-root-map.yaml"), carYaml1); - Map<Object, Object> car2 = (Map<Object, Object>) new Yaml().load(carYaml1); - assertEquals(car1, car2); - assertEquals(carYaml1, new Yaml().dump(car2)); + public Wheel getWheel() { + return wheel; } - public void testLoadClassTag() { - Constructor constructor = new Constructor(); - constructor.addTypeDescription(new TypeDescription(Car.class, "!car")); - Yaml yaml = new Yaml(constructor); - Car car = (Car) yaml.load(Util.getLocalResource("constructor/car-without-tags.yaml")); - assertEquals("12-XP-F4", car.getPlate()); - List<Wheel> wheels = car.getWheels(); - assertNotNull(wheels); - assertEquals(5, wheels.size()); - Wheel w1 = wheels.get(0); - assertEquals(1, w1.getId()); - // - String carYaml1 = new Yaml().dump(car); - assertTrue(carYaml1.startsWith("!!org.yaml.snakeyaml.constructor.Car")); - // - Representer representer = new Representer(); - representer.addClassTag(Car.class, new Tag("!car")); - yaml = new Yaml(representer); - String carYaml2 = yaml.dump(car); - assertEquals(Util.getLocalResource("constructor/car-without-tags.yaml"), carYaml2); + public void setWheel(Wheel wheel) { + this.wheel = wheel; } - public static class CarWithWheel { - private String plate; - private String year; - private Wheel wheel; - private Object part; - private Map<String, Integer> map; - - public String getPlate() { - return plate; - } - - public void setPlate(String plate) { - this.plate = plate; - } - - public Wheel getWheel() { - return wheel; - } - - public void setWheel(Wheel wheel) { - this.wheel = wheel; - } - - public Map<String, Integer> getMap() { - return map; - } + public Map<String, Integer> getMap() { + return map; + } - public void setMap(Map<String, Integer> map) { - this.map = map; - } + public void setMap(Map<String, Integer> map) { + this.map = map; + } - public Object getPart() { - return part; - } + public Object getPart() { + return part; + } - public void setPart(Object part) { - this.part = part; - } + public void setPart(Object part) { + this.part = part; + } - public String getYear() { - return year; - } + public String getYear() { + return year; + } - public void setYear(String year) { - this.year = year; - } + public void setYear(String year) { + this.year = year; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/IncompleteBeanConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/IncompleteBeanConstructorTest.java index d3c8ba03..db79b408 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/IncompleteBeanConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/IncompleteBeanConstructorTest.java @@ -1,59 +1,56 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.YAMLException; public class IncompleteBeanConstructorTest extends TestCase { - public void testRepresentor() { - IncompleteJavaBean bean = new IncompleteJavaBean(); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - String output = yaml.dump(bean); - String className = this.getClass().getPackage().getName(); - assertEquals("!!" + className + ".IncompleteJavaBean {name: No name}\n", output); - } + public void testRepresentor() { + IncompleteJavaBean bean = new IncompleteJavaBean(); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + String output = yaml.dump(bean); + String className = this.getClass().getPackage().getName(); + assertEquals("!!" + className + ".IncompleteJavaBean {name: No name}\n", output); + } - public void testConstructor() { - String className = "!!" + this.getClass().getPackage().getName() - + ".IncompleteJavaBean {number: 2}"; - Yaml yaml = new Yaml(); - IncompleteJavaBean bean = (IncompleteJavaBean) yaml.load(className); - assertNotNull(bean); - assertEquals("No name", bean.getName()); - assertEquals(2, bean.obtainNumber()); - } + public void testConstructor() { + String className = + "!!" + this.getClass().getPackage().getName() + ".IncompleteJavaBean {number: 2}"; + Yaml yaml = new Yaml(); + IncompleteJavaBean bean = yaml.load(className); + assertNotNull(bean); + assertEquals("No name", bean.getName()); + assertEquals(2, bean.obtainNumber()); + } - public void testConstructor2() { - String className = "!!" + this.getClass().getPackage().getName() - + ".IncompleteJavaBean {number: 2, name: Bill}"; - Yaml yaml = new Yaml(); - try { - yaml.load(className); - fail("'name' property does not have setter."); - } catch (YAMLException e) { - assertEquals( - "Unable to find property 'name' on class: org.yaml.snakeyaml.constructor.IncompleteJavaBean", - e.getCause().getMessage()); - } + public void testConstructor2() { + String className = "!!" + this.getClass().getPackage().getName() + + ".IncompleteJavaBean {number: 2, name: Bill}"; + Yaml yaml = new Yaml(); + try { + yaml.load(className); + fail("'name' property does not have setter."); + } catch (YAMLException e) { + assertEquals( + "No writable property 'name' on class: org.yaml.snakeyaml.constructor.IncompleteJavaBean", + e.getCause().getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/IncompleteJavaBean.java b/src/test/java/org/yaml/snakeyaml/constructor/IncompleteJavaBean.java index d849680e..a9dfbc85 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/IncompleteJavaBean.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/IncompleteJavaBean.java @@ -1,40 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; public class IncompleteJavaBean { - private int number; - private String name = "No name"; - private float amount; - public String getName() { - return name; - } + private int number; + private final String name = "No name"; + private float amount; - public void setNumber(int number) { - this.number = number; - amount += number; - } + public String getName() { + return name; + } - public int obtainNumber() { - return number; - } + public void setNumber(int number) { + this.number = number; + amount += number; + } - @Override - public String toString() { - return "<IncompleteJavaBean name=" + name + ">"; - } -}
\ No newline at end of file + public int obtainNumber() { + return number; + } + + @Override + public String toString() { + return "<IncompleteJavaBean name=" + name + ">"; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/constructor/MockDateBeanConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/MockDateBeanConstructorTest.java index 9b8d7941..f8846a87 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/MockDateBeanConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/MockDateBeanConstructorTest.java @@ -1,72 +1,71 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.Date; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class MockDateBeanConstructorTest extends TestCase { - public void testConstructor() { - String className = "!!org.yaml.snakeyaml.constructor.MockDateBeanConstructorTest$DateBean {number: 24, date: 2009-07-24}"; - Yaml yaml = new Yaml(); - try { - yaml.load(className); - fail("MockDate cannot be constructed."); - } catch (Exception e) { - assertEquals( - "Cannot construct: 'class org.yaml.snakeyaml.constructor.MockDateBeanConstructorTest$MockDate'", - e.getCause().getMessage()); - } + public void testConstructor() { + String className = + "!!org.yaml.snakeyaml.constructor.MockDateBeanConstructorTest$DateBean {number: 24, date: 2009-07-24}"; + Yaml yaml = new Yaml(); + try { + yaml.load(className); + fail("MockDate cannot be constructed."); + } catch (Exception e) { + assertEquals( + "Cannot construct: 'class org.yaml.snakeyaml.constructor.MockDateBeanConstructorTest$MockDate'", + e.getCause().getMessage()); } + } - public static class DateBean { - private int number; - private MockDate date; + public static class DateBean { - public int getNumber() { - return number; - } + private int number; + private MockDate date; + + public int getNumber() { + return number; + } - public void setNumber(int number) { - this.number = number; - } + public void setNumber(int number) { + this.number = number; + } - public MockDate getDate() { - return date; - } + public MockDate getDate() { + return date; + } - public void setDate(MockDate date) { - this.date = date; - } + public void setDate(MockDate date) { + this.date = date; + } - @Override - public String toString() { - return "<DateBean n=" + number + ">"; - } + @Override + public String toString() { + return "<DateBean n=" + number + ">"; } + } + + public static class MockDate extends Date { - public static class MockDate extends Date { - private static final long serialVersionUID = 621384692653658062L; + private static final long serialVersionUID = 621384692653658062L; - public MockDate(long date) { - throw new RuntimeException("Test error."); - } + public MockDate(long date) { + throw new RuntimeException("Test error."); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/MyCar.java b/src/test/java/org/yaml/snakeyaml/constructor/MyCar.java index 4753f3e1..34a7badd 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/MyCar.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/MyCar.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,31 +17,32 @@ import java.util.Date; import java.util.Map; public class MyCar { - private String plate; - private Map<MyWheel, Date> wheels; - private Map<String, Integer> windows; - public String getPlate() { - return plate; - } + private String plate; + private Map<MyWheel, Date> wheels; + private Map<String, Integer> windows; - public void setPlate(String plate) { - this.plate = plate; - } + public String getPlate() { + return plate; + } - public Map<MyWheel, Date> getWheels() { - return wheels; - } + public void setPlate(String plate) { + this.plate = plate; + } - public void setWheels(Map<MyWheel, Date> wheels) { - this.wheels = wheels; - } + public Map<MyWheel, Date> getWheels() { + return wheels; + } - public Map<String, Integer> getWindows() { - return windows; - } + public void setWheels(Map<MyWheel, Date> wheels) { + this.wheels = wheels; + } - public void setWindows(Map<String, Integer> windows) { - this.windows = windows; - } + public Map<String, Integer> getWindows() { + return windows; + } + + public void setWindows(Map<String, Integer> windows) { + this.windows = windows; + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/MyWheel.java b/src/test/java/org/yaml/snakeyaml/constructor/MyWheel.java index 67fbeaba..098d88c0 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/MyWheel.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/MyWheel.java @@ -1,65 +1,64 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; public class MyWheel implements Comparable<MyWheel> { - private int id; - private String brand; - public MyWheel() { - brand = "Pirelli"; - } + private int id; + private String brand; - public int getId() { - return id; - } + public MyWheel() { + brand = "Pirelli"; + } - public void setId(int id) { - this.id = id; - } + public int getId() { + return id; + } - @Override - public String toString() { - return "Wheel id=" + id; - } + public void setId(int id) { + this.id = id; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof MyWheel) { - MyWheel wheel = (MyWheel) obj; - return id == wheel.getId(); - } else { - return false; - } - } + @Override + public String toString() { + return "Wheel id=" + id; + } - @Override - public int hashCode() { - return new Integer(id).hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof MyWheel) { + MyWheel wheel = (MyWheel) obj; + return id == wheel.getId(); + } else { + return false; } + } - public String getBrand() { - return brand; - } + @Override + public int hashCode() { + return Integer.valueOf(id).hashCode(); + } - public void setBrand(String brand) { - this.brand = brand; - } + public String getBrand() { + return brand; + } - public int compareTo(MyWheel arg0) { - return new Integer(id).compareTo(new Integer(arg0.id)); - } + public void setBrand(String brand) { + this.brand = brand; + } + + public int compareTo(MyWheel arg0) { + return Integer.valueOf(id).compareTo(Integer.valueOf(arg0.id)); + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/Parent1.java b/src/test/java/org/yaml/snakeyaml/constructor/Parent1.java index 3703dbc0..c8230930 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/Parent1.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/Parent1.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; public class Parent1 { - private String id; - private Child1 child; - public String getId() { - return id; - } + private String id; + private Child1 child; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public Child1 getChild() { - return child; - } + public void setId(String id) { + this.id = id; + } - public void setChild(Child1 child) { - this.child = child; - } -}
\ No newline at end of file + public Child1 getChild() { + return child; + } + + public void setChild(Child1 child) { + this.child = child; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/constructor/Person.java b/src/test/java/org/yaml/snakeyaml/constructor/Person.java index a681ac8d..06ba846f 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/Person.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/Person.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,45 +17,45 @@ package org.yaml.snakeyaml.constructor; * Test JavaBean */ public class Person { - private String firstName; - private String lastName; - private Integer age; - - public Person(String firstName, String lastName, Integer age) { - this.firstName = firstName; - this.lastName = lastName; - this.age = age; - } - - public Person() { - } - - public Person(String lastName) { - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } + + private String firstName; + private String lastName; + private Integer age; + + public Person(String firstName, String lastName, Integer age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public Person() {} + + public Person(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/PrefixConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/PrefixConstructorTest.java index 6a6a5e06..10ecdaca 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/PrefixConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/PrefixConstructorTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; @@ -26,111 +22,115 @@ import org.yaml.snakeyaml.nodes.SequenceNode; import org.yaml.snakeyaml.nodes.Tag; /** - * Example to process a family of tags with the same prefix with one constructor - * (PrefixConstruct) + * Example to process a family of tags with the same prefix with one constructor (PrefixConstruct) */ public class PrefixConstructorTest extends TestCase { - @SuppressWarnings("unchecked") - public void test1() { - Yaml yaml = new Yaml(new CustomConstructor()); - String input = "- !org.yaml.Foo 123\n- !org.yaml.Bar 456\n- !org.yaml.Exact 789\n- !Immutable [aaa, bbb]"; - List<Extra> list = (List<Extra>) yaml.load(input); - assertEquals(4, list.size()); - Extra foo = list.get(0); - assertEquals("Foo", foo.getName()); - assertEquals("123", foo.getValue()); - // - Extra bar = list.get(1); - assertEquals("Bar", bar.getName()); - assertEquals("456", bar.getValue()); - // - Extra item = list.get(2); - assertEquals("Item", item.getName()); - assertEquals("789", item.getValue()); - // - Extra immut = list.get(3); - assertEquals("aaa", immut.getName()); - assertEquals("bbb", immut.getValue()); + @SuppressWarnings("unchecked") + public void test1() { + Yaml yaml = new Yaml(new CustomConstructor()); + String input = + "- !org.yaml.Foo 123\n- !org.yaml.Bar 456\n- !org.yaml.Exact 789\n- !Immutable [aaa, bbb]"; + List<Extra> list = yaml.load(input); + assertEquals(4, list.size()); + Extra foo = list.get(0); + assertEquals("Foo", foo.getName()); + assertEquals("123", foo.getValue()); + // + Extra bar = list.get(1); + assertEquals("Bar", bar.getName()); + assertEquals("456", bar.getValue()); + // + Extra item = list.get(2); + assertEquals("Item", item.getName()); + assertEquals("789", item.getValue()); + // + Extra immut = list.get(3); + assertEquals("aaa", immut.getName()); + assertEquals("bbb", immut.getValue()); + } + + private class CustomConstructor extends SafeConstructor { + + public CustomConstructor() { + // define tags which begin with !org.yaml. + String prefix = "!org.yaml."; + this.yamlMultiConstructors.put(prefix, new PrefixConstruct(prefix, CustomConstructor.this)); + this.yamlConstructors.put(null, new ConstructUnknown(CustomConstructor.this)); + this.yamlConstructors.put(new Tag("!org.yaml.Exact"), + new ExactConstruct(CustomConstructor.this)); } + } + + /** + * Process tags which start with '!org.yaml.' + */ + private class PrefixConstruct extends AbstractConstruct { - private class CustomConstructor extends SafeConstructor { - public CustomConstructor() { - // define tags which begin with !org.yaml. - String prefix = "!org.yaml."; - this.yamlMultiConstructors.put(prefix, new PrefixConstruct(prefix, - CustomConstructor.this)); - this.yamlConstructors.put(null, new ConstructUnknown(CustomConstructor.this)); - this.yamlConstructors.put(new Tag("!org.yaml.Exact"), new ExactConstruct( - CustomConstructor.this)); - } + private final String prefix; + private final BaseConstructor con; + + public PrefixConstruct(String prefix, BaseConstructor con) { + this.prefix = prefix; + this.con = con; } - /** - * Process tags which start with '!org.yaml.' - */ - private class PrefixConstruct extends AbstractConstruct { - private String prefix; - private BaseConstructor con; - - public PrefixConstruct(String prefix, BaseConstructor con) { - this.prefix = prefix; - this.con = con; - } - - public Object construct(Node node) { - String suffix = node.getTag().getValue().substring(prefix.length()); - return new Extra(suffix, con.constructScalar((ScalarNode) node).toString()); - } + public Object construct(Node node) { + String suffix = node.getTag().getValue().substring(prefix.length()); + return new Extra(suffix, con.constructScalar((ScalarNode) node)); } + } - /** - * This has more priority then PrefixConstruct - */ - private class ExactConstruct extends AbstractConstruct { - private BaseConstructor con; + /** + * This has more priority then PrefixConstruct + */ + private class ExactConstruct extends AbstractConstruct { - public ExactConstruct(BaseConstructor con) { - this.con = con; - } + private final BaseConstructor con; - public Object construct(Node node) { - return new Extra("Item", con.constructScalar((ScalarNode) node).toString()); - } + public ExactConstruct(BaseConstructor con) { + this.con = con; } - /** - * Process unrecognised tags - */ - private class ConstructUnknown extends AbstractConstruct { - private BaseConstructor con; - - public ConstructUnknown(BaseConstructor con) { - this.con = con; - } - - @SuppressWarnings("unchecked") - public Object construct(Node node) { - List<String> list = (List<String>) con.constructSequence((SequenceNode) node); - return new Extra(list.get(0), list.get(1)); - } + public Object construct(Node node) { + return new Extra("Item", con.constructScalar((ScalarNode) node)); } + } + + /** + * Process unrecognised tags + */ + private class ConstructUnknown extends AbstractConstruct { - private class Extra { - private String name; - private String value; + private final BaseConstructor con; - public Extra(String name, String value) { - this.name = name; - this.value = value; - } + public ConstructUnknown(BaseConstructor con) { + this.con = con; + } - public String getValue() { - return value; - } + @SuppressWarnings("unchecked") + public Object construct(Node node) { + List<String> list = (List<String>) con.constructSequence((SequenceNode) node); + return new Extra(list.get(0), list.get(1)); + } + } + + private class Extra { + + private final String name; + private final String value; + + public Extra(String name, String value) { + this.name = name; + this.value = value; + } + + public String getValue() { + return value; + } - public String getName() { - return name; - } + public String getName() { + return name; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/SafeConstructorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/SafeConstructorTest.java index 32fb36f8..9fe8a90c 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/SafeConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/SafeConstructorTest.java @@ -1,50 +1,45 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class SafeConstructorTest extends TestCase { - public void testConstructFloat() { - Yaml yaml = new Yaml(); - assertEquals(3.1416, yaml.load("+3.1416")); - assertEquals(Double.POSITIVE_INFINITY, yaml.load("+.inf")); - assertEquals(Double.POSITIVE_INFINITY, yaml.load(".inf")); - assertEquals(Double.NEGATIVE_INFINITY, yaml.load("-.inf")); - } + public void testConstructFloat() { + Yaml yaml = new Yaml(); + assertEquals(3.1416, yaml.load("+3.1416")); + assertEquals(Double.POSITIVE_INFINITY, yaml.load("+.inf")); + assertEquals(Double.POSITIVE_INFINITY, yaml.load(".inf")); + assertEquals(Double.NEGATIVE_INFINITY, yaml.load("-.inf")); + } - public void testSafeConstruct() { - Yaml yaml = new Yaml(new SafeConstructor()); - assertEquals(3.1416, yaml.load("+3.1416")); - } + public void testSafeConstruct() { + Yaml yaml = new Yaml(new SafeConstructor()); + assertEquals(3.1416, yaml.load("+3.1416")); + } - public void testSafeConstructJavaBean() { - Yaml yaml = new Yaml(new SafeConstructor()); - String data = "--- !!org.yaml.snakeyaml.constructor.Person\nfirstName: Andrey\nage: 99"; - try { - yaml.load(data); - fail("JavaBeans cannot be created by SafeConstructor."); - } catch (ConstructorException e) { - assertTrue(e - .getMessage() - .contains( - "could not determine a constructor for the tag tag:yaml.org,2002:org.yaml.snakeyaml.constructor.Person")); - } + public void testSafeConstructJavaBean() { + Yaml yaml = new Yaml(new SafeConstructor()); + String data = "--- !!org.yaml.snakeyaml.constructor.Person\nfirstName: Andrey\nage: 99"; + try { + yaml.load(data); + fail("JavaBeans cannot be created by SafeConstructor."); + } catch (ConstructorException e) { + assertTrue(e.getMessage().contains( + "could not determine a constructor for the tag tag:yaml.org,2002:org.yaml.snakeyaml.constructor.Person")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/TestBean.java b/src/test/java/org/yaml/snakeyaml/constructor/TestBean.java index 31d91941..8a45edec 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/TestBean.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/TestBean.java @@ -1,83 +1,78 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.Date; -/** - * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a> - */ public class TestBean { - private String name; - private int age; - private Date born; - public TestBean() { - } + private String name; + private int age; + private Date born; - public TestBean(final String name, final int age, final Date born) { - this.name = name; - this.age = age; - this.born = born; - } + public TestBean() {} - public String getName() { - return this.name; - } + public TestBean(final String name, final int age, final Date born) { + this.name = name; + this.age = age; + this.born = born; + } - public int getAge() { - return age; - } + public String getName() { + return this.name; + } - public Date getBorn() { - return born; - } + public int getAge() { + return age; + } - public void setName(final String name) { - this.name = name; - } + public Date getBorn() { + return born; + } - public void setAge(final int age) { - this.age = age; - } + public void setName(final String name) { + this.name = name; + } - public void setBorn(final Date born) { - this.born = born; - } + public void setAge(final int age) { + this.age = age; + } - public boolean equals(final Object other) { - boolean ret = this == other; - if (!ret && other instanceof TestBean) { - TestBean o = (TestBean) other; - ret = this.name == null ? o.name == null : this.name.equals(o.name) - && this.age == o.age && this.born == null ? o.born == null : this.born - .equals(o.born); - } - return ret; - } + public void setBorn(final Date born) { + this.born = born; + } - public int hashCode() { - int val = 3; - val += 3 * (name == null ? 0 : name.hashCode()); - val += 3 * age; - val += 3 * (born == null ? 0 : born.hashCode()); - return val; + public boolean equals(final Object other) { + boolean ret = this == other; + if (!ret && other instanceof TestBean) { + TestBean o = (TestBean) other; + ret = this.name == null ? o.name == null + : this.name.equals(o.name) && this.age == o.age && this.born == null ? o.born == null + : this.born.equals(o.born); } + return ret; + } - public String toString() { - return "#<org.jvyaml.TestBean name=\"" + name + "\" age=" + age + " born=\"" + born + "\">"; - } + public int hashCode() { + int val = 3; + val += 3 * (name == null ? 0 : name.hashCode()); + val += 3 * age; + val += 3 * (born == null ? 0 : born.hashCode()); + return val; + } + + public String toString() { + return "#<org.jvyaml.TestBean name=\"" + name + "\" age=" + age + " born=\"" + born + "\">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/TestBean1.java b/src/test/java/org/yaml/snakeyaml/constructor/TestBean1.java index be9cf975..173d1453 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/TestBean1.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/TestBean1.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,186 +17,187 @@ import java.math.BigInteger; import java.util.Date; public class TestBean1 { - private String text; - private String id; - private Byte byteClass; - private byte bytePrimitive; - private Short shortClass; - private short shortPrimitive; - private Integer integer; - private int intPrimitive; - private Long longClass; - private long longPrimitive; - private Boolean booleanClass; - private boolean booleanPrimitive; - private Character charClass; - private char charPrimitive; - private BigInteger bigInteger; - private Float floatClass; - private float floatPrimitive; - private Double doubleClass; - private double doublePrimitive; - private Date date; - public String publicField; - static public Integer staticInteger; - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public Integer getInteger() { - return integer; - } - - public void setInteger(Integer integer) { - this.integer = integer; - } - - public int getIntPrimitive() { - return intPrimitive; - } - - public void setIntPrimitive(int intPrimitive) { - this.intPrimitive = intPrimitive; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Byte getByteClass() { - return byteClass; - } - - public void setByteClass(Byte byteClass) { - this.byteClass = byteClass; - } - - public byte getBytePrimitive() { - return bytePrimitive; - } - - public void setBytePrimitive(byte bytePrimitive) { - this.bytePrimitive = bytePrimitive; - } - - public Short getShortClass() { - return shortClass; - } - - public void setShortClass(Short shortClass) { - this.shortClass = shortClass; - } - - public short getShortPrimitive() { - return shortPrimitive; - } - - public void setShortPrimitive(short shortPrimitive) { - this.shortPrimitive = shortPrimitive; - } - - public Long getLongClass() { - return longClass; - } - - public void setLongClass(Long longClass) { - this.longClass = longClass; - } - - public long getLongPrimitive() { - return longPrimitive; - } - - public void setLongPrimitive(long longPrimitive) { - this.longPrimitive = longPrimitive; - } - - public Boolean getBooleanClass() { - return booleanClass; - } - - public void setBooleanClass(Boolean booleanClass) { - this.booleanClass = booleanClass; - } - - public boolean isBooleanPrimitive() { - return booleanPrimitive; - } - - public void setBooleanPrimitive(boolean booleanPrimitive) { - this.booleanPrimitive = booleanPrimitive; - } - - public Character getCharClass() { - return charClass; - } - public void setCharClass(Character charClass) { - this.charClass = charClass; - } + private String text; + private String id; + private Byte byteClass; + private byte bytePrimitive; + private Short shortClass; + private short shortPrimitive; + private Integer integer; + private int intPrimitive; + private Long longClass; + private long longPrimitive; + private Boolean booleanClass; + private boolean booleanPrimitive; + private Character charClass; + private char charPrimitive; + private BigInteger bigInteger; + private Float floatClass; + private float floatPrimitive; + private Double doubleClass; + private double doublePrimitive; + private Date date; + public String publicField; + static public Integer staticInteger; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public int getIntPrimitive() { + return intPrimitive; + } + + public void setIntPrimitive(int intPrimitive) { + this.intPrimitive = intPrimitive; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Byte getByteClass() { + return byteClass; + } + + public void setByteClass(Byte byteClass) { + this.byteClass = byteClass; + } + + public byte getBytePrimitive() { + return bytePrimitive; + } + + public void setBytePrimitive(byte bytePrimitive) { + this.bytePrimitive = bytePrimitive; + } + + public Short getShortClass() { + return shortClass; + } + + public void setShortClass(Short shortClass) { + this.shortClass = shortClass; + } + + public short getShortPrimitive() { + return shortPrimitive; + } + + public void setShortPrimitive(short shortPrimitive) { + this.shortPrimitive = shortPrimitive; + } + + public Long getLongClass() { + return longClass; + } + + public void setLongClass(Long longClass) { + this.longClass = longClass; + } + + public long getLongPrimitive() { + return longPrimitive; + } + + public void setLongPrimitive(long longPrimitive) { + this.longPrimitive = longPrimitive; + } + + public Boolean getBooleanClass() { + return booleanClass; + } + + public void setBooleanClass(Boolean booleanClass) { + this.booleanClass = booleanClass; + } + + public boolean isBooleanPrimitive() { + return booleanPrimitive; + } + + public void setBooleanPrimitive(boolean booleanPrimitive) { + this.booleanPrimitive = booleanPrimitive; + } + + public Character getCharClass() { + return charClass; + } - public char getCharPrimitive() { - return charPrimitive; - } + public void setCharClass(Character charClass) { + this.charClass = charClass; + } - public void setCharPrimitive(char charPrimitive) { - this.charPrimitive = charPrimitive; - } + public char getCharPrimitive() { + return charPrimitive; + } - public BigInteger getBigInteger() { - return bigInteger; - } + public void setCharPrimitive(char charPrimitive) { + this.charPrimitive = charPrimitive; + } - public void setBigInteger(BigInteger bigInteger) { - this.bigInteger = bigInteger; - } + public BigInteger getBigInteger() { + return bigInteger; + } - public Float getFloatClass() { - return floatClass; - } + public void setBigInteger(BigInteger bigInteger) { + this.bigInteger = bigInteger; + } - public void setFloatClass(Float floatClass) { - this.floatClass = floatClass; - } + public Float getFloatClass() { + return floatClass; + } - public float getFloatPrimitive() { - return floatPrimitive; - } + public void setFloatClass(Float floatClass) { + this.floatClass = floatClass; + } - public void setFloatPrimitive(float floatPrimitive) { - this.floatPrimitive = floatPrimitive; - } + public float getFloatPrimitive() { + return floatPrimitive; + } - public Double getDoubleClass() { - return doubleClass; - } + public void setFloatPrimitive(float floatPrimitive) { + this.floatPrimitive = floatPrimitive; + } - public void setDoubleClass(Double doubleClass) { - this.doubleClass = doubleClass; - } + public Double getDoubleClass() { + return doubleClass; + } - public double getDoublePrimitive() { - return doublePrimitive; - } + public void setDoubleClass(Double doubleClass) { + this.doubleClass = doubleClass; + } - public void setDoublePrimitive(double doublePrimitive) { - this.doublePrimitive = doublePrimitive; - } + public double getDoublePrimitive() { + return doublePrimitive; + } - public Date getDate() { - return date; - } + public void setDoublePrimitive(double doublePrimitive) { + this.doublePrimitive = doublePrimitive; + } - public void setDate(Date date) { - this.date = date; - } -}
\ No newline at end of file + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/constructor/TypeSafeCollectionsTest.java b/src/test/java/org/yaml/snakeyaml/constructor/TypeSafeCollectionsTest.java index 8afe3cef..35c56dcb 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/TypeSafeCollectionsTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/TypeSafeCollectionsTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; @@ -19,9 +17,7 @@ import java.util.Date; import java.util.List; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -30,74 +26,108 @@ import org.yaml.snakeyaml.representer.Representer; public class TypeSafeCollectionsTest extends TestCase { - public void testTypeSafeList() { - Constructor constructor = new Constructor(Car.class); - TypeDescription carDescription = new TypeDescription(Car.class); - carDescription.putListPropertyType("wheels", Wheel.class); - constructor.addTypeDescription(carDescription); - Yaml yaml = new Yaml(constructor); - Car car = (Car) yaml.load(Util.getLocalResource("constructor/car-no-root-class.yaml")); - assertEquals("12-XP-F4", car.getPlate()); - List<Wheel> wheels = car.getWheels(); - assertNotNull(wheels); - assertEquals(5, wheels.size()); - for (Wheel wheel : wheels) { - assertTrue(wheel.getId() > 0); - } + public void testTypeSafeList() { + Constructor constructor = new Constructor(Car.class); + TypeDescription carDescription = new TypeDescription(Car.class); + carDescription.putListPropertyType("wheels", Wheel.class); + constructor.addTypeDescription(carDescription); + Yaml yaml = new Yaml(constructor); + Car car = yaml.load(Util.getLocalResource("constructor/car-no-root-class.yaml")); + assertEquals("12-XP-F4", car.getPlate()); + List<Wheel> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + for (Wheel wheel : wheels) { + assertTrue(wheel.getId() > 0); + } + } + + public void testTypeSafeMap() { + Constructor constructor = new Constructor(MyCar.class); + TypeDescription carDescription = new TypeDescription(MyCar.class); + carDescription.putMapPropertyType("wheels", MyWheel.class, Object.class); + constructor.addTypeDescription(carDescription); + Yaml yaml = new Yaml(constructor); + MyCar car = yaml.load(Util.getLocalResource("constructor/car-no-root-class-map.yaml")); + assertEquals("00-FF-Q2", car.getPlate()); + Map<MyWheel, Date> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + for (MyWheel wheel : wheels.keySet()) { + assertTrue(wheel.getId() > 0); + Date date = wheels.get(wheel); + long time = date.getTime(); + assertEquals("It must be midnight.", 0, time % 10000); } + } - public void testTypeSafeMap() { - Constructor constructor = new Constructor(MyCar.class); - TypeDescription carDescription = new TypeDescription(MyCar.class); - carDescription.putMapPropertyType("wheels", MyWheel.class, Object.class); - constructor.addTypeDescription(carDescription); - Yaml yaml = new Yaml(constructor); - MyCar car = (MyCar) yaml.load(Util - .getLocalResource("constructor/car-no-root-class-map.yaml")); - assertEquals("00-FF-Q2", car.getPlate()); - Map<MyWheel, Date> wheels = car.getWheels(); - assertNotNull(wheels); - assertEquals(5, wheels.size()); - for (MyWheel wheel : wheels.keySet()) { - assertTrue(wheel.getId() > 0); - Date date = wheels.get(wheel); - long time = date.getTime(); - assertTrue("It must be midnight.", time % 10000 == 0); - } + public void testTypeSafeList2() { + Constructor constructor = new Constructor(Car.class); + TypeDescription carDescription = new TypeDescription(Car.class); + carDescription.addPropertyParameters("wheels", Wheel.class); + constructor.addTypeDescription(carDescription); + Yaml yaml = new Yaml(constructor); + Car car = yaml.load(Util.getLocalResource("constructor/car-no-root-class.yaml")); + assertEquals("12-XP-F4", car.getPlate()); + List<Wheel> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + for (Wheel wheel : wheels) { + assertTrue(wheel.getId() > 0); } + } - public void testWithGlobalTag() { - Map<MyWheel, Date> wheels = new TreeMap<MyWheel, Date>(); - long time = 1248212168084L; - for (int i = 1; i < 6; i++) { - MyWheel mw = new MyWheel(); - mw.setId(i); - mw.setBrand(mw.getBrand() + String.valueOf(i)); - wheels.put(mw, new Date(time + i)); - } - MyCar c = new MyCar(); - c.setPlate("00-FF-Q2"); - c.setWheels(wheels); - Representer representer = new Representer(); - representer.addClassTag(MyWheel.class, Tag.MAP); - Yaml yaml = new Yaml(representer); - String output = yaml.dump(c); - assertEquals(Util.getLocalResource("javabeans/mycar-with-global-tag1.yaml"), output); - // load - Yaml beanLoader = new Yaml(); - MyCar car = beanLoader.loadAs(output, MyCar.class); - assertNotNull(car); - assertEquals("00-FF-Q2", car.getPlate()); - assertEquals(5, car.getWheels().size()); - for (Date d : car.getWheels().values()) { - // give a day for any timezone - assertTrue(d.before(new Date(time + 1000 * 60 * 60 * 24))); - assertTrue(d.after(new Date(time))); - } - Object wheel = car.getWheels().keySet().iterator().next(); - assertTrue(wheel instanceof MyWheel); - MyWheel w = (MyWheel) wheel; - assertEquals(1, w.getId()); - assertEquals("Pirelli1", w.getBrand()); + public void testTypeSafeMap2() { + Constructor constructor = new Constructor(MyCar.class); + TypeDescription carDescription = new TypeDescription(MyCar.class); + carDescription.addPropertyParameters("wheels", MyWheel.class, Object.class); + constructor.addTypeDescription(carDescription); + Yaml yaml = new Yaml(constructor); + MyCar car = yaml.load(Util.getLocalResource("constructor/car-no-root-class-map.yaml")); + assertEquals("00-FF-Q2", car.getPlate()); + Map<MyWheel, Date> wheels = car.getWheels(); + assertNotNull(wheels); + assertEquals(5, wheels.size()); + for (MyWheel wheel : wheels.keySet()) { + assertTrue(wheel.getId() > 0); + Date date = wheels.get(wheel); + long time = date.getTime(); + assertEquals("It must be midnight.", 0, time % 10000); + } + } + + public void testWithGlobalTag() { + Map<MyWheel, Date> wheels = new TreeMap<MyWheel, Date>(); + long time = 1248212168084L; + for (int i = 1; i < 6; i++) { + MyWheel mw = new MyWheel(); + mw.setId(i); + mw.setBrand(mw.getBrand() + i); + wheels.put(mw, new Date(time + i)); + } + MyCar c = new MyCar(); + c.setPlate("00-FF-Q2"); + c.setWheels(wheels); + Representer representer = new Representer(); + representer.addClassTag(MyWheel.class, Tag.MAP); + Yaml yaml = new Yaml(representer); + String output = yaml.dump(c); + assertEquals(Util.getLocalResource("javabeans/mycar-with-global-tag1.yaml"), output); + // load + Yaml beanLoader = new Yaml(); + MyCar car = beanLoader.loadAs(output, MyCar.class); + assertNotNull(car); + assertEquals("00-FF-Q2", car.getPlate()); + assertEquals(5, car.getWheels().size()); + for (Date d : car.getWheels().values()) { + // give a day for any timezone + assertTrue(d.before(new Date(time + 1000 * 60 * 60 * 24))); + assertTrue(d.after(new Date(time))); } + Object wheel = car.getWheels().keySet().iterator().next(); + assertTrue(wheel instanceof MyWheel); + MyWheel w = (MyWheel) wheel; + assertEquals(1, w.getId()); + assertEquals("Pirelli1", w.getBrand()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/VectorTest.java b/src/test/java/org/yaml/snakeyaml/constructor/VectorTest.java index 0edb6b9f..e413d175 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/VectorTest.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/VectorTest.java @@ -1,46 +1,42 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; import java.util.Vector; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class VectorTest extends TestCase { - @SuppressWarnings("unchecked") - public void testVector() throws ClassNotFoundException { - // Data to serialise - Vector<String> srcVector = new Vector<String>(); - srcVector.add("this"); - srcVector.add("is"); - srcVector.add("a"); - srcVector.add("test"); - // System.out.println("Source Vector: " + srcVector); - Yaml yaml = new Yaml(); - String instance = yaml.dump(srcVector); - //System.out.println("YAML String: " + instance); - yaml = new Yaml(new Constructor("java.util.Vector")); - // If I try to get a Vector I receive a class cast exception. - Vector<String> vector = (Vector<String>) yaml.load(instance); - // System.out.println("Vector: " + vector); - assertEquals(4, vector.size()); - assertEquals("this", vector.firstElement()); - assertEquals("test", vector.lastElement()); - } + @SuppressWarnings("unchecked") + public void testVector() throws ClassNotFoundException { + // Data to serialise + Vector<String> srcVector = new Vector<String>(); + srcVector.add("this"); + srcVector.add("is"); + srcVector.add("a"); + srcVector.add("test"); + // System.out.println("Source Vector: " + srcVector); + Yaml yaml = new Yaml(); + String instance = yaml.dump(srcVector); + // System.out.println("YAML String: " + instance); + yaml = new Yaml(new Constructor("java.util.Vector")); + // If I try to get a Vector I receive a class cast exception. + Vector<String> vector = yaml.load(instance); + // System.out.println("Vector: " + vector); + assertEquals(4, vector.size()); + assertEquals("this", vector.firstElement()); + assertEquals("test", vector.lastElement()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/constructor/Wheel.java b/src/test/java/org/yaml/snakeyaml/constructor/Wheel.java index 91c740e7..30031151 100644 --- a/src/test/java/org/yaml/snakeyaml/constructor/Wheel.java +++ b/src/test/java/org/yaml/snakeyaml/constructor/Wheel.java @@ -1,56 +1,55 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.constructor; public class Wheel { - private int id; - public Wheel(int id) { - this.id = id; - } + private int id; - public Wheel() { - this(0); - } + public Wheel(int id) { + this.id = id; + } - public int getId() { - return id; - } + public Wheel() { + this(0); + } - public void setId(int id) { - this.id = id; - } + public int getId() { + return id; + } - @Override - public String toString() { - return "Wheel id=" + id; - } + public void setId(int id) { + this.id = id; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Wheel) { - Wheel wheel = (Wheel) obj; - return id == wheel.getId(); - } else { - return false; - } - } + @Override + public String toString() { + return "Wheel id=" + id; + } - @Override - public int hashCode() { - return new Integer(id).hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Wheel) { + Wheel wheel = (Wheel) obj; + return id == wheel.getId(); + } else { + return false; } + } + + @Override + public int hashCode() { + return Integer.valueOf(id).hashCode(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/emitter/EmitterMultiLineTest.java b/src/test/java/org/yaml/snakeyaml/emitter/EmitterMultiLineTest.java index 77c5d2e2..716457af 100644 --- a/src/test/java/org/yaml/snakeyaml/emitter/EmitterMultiLineTest.java +++ b/src/test/java/org/yaml/snakeyaml/emitter/EmitterMultiLineTest.java @@ -1,109 +1,106 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; import java.util.ArrayList; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; public class EmitterMultiLineTest extends TestCase { - public void testWriteMultiLineLiteral() { - String plain = "mama\nmila\nramu"; - Yaml yaml = new Yaml(); - String output = yaml.dump(plain); - // System.out.println(output); - assertEquals("|-\n mama\n mila\n ramu\n", output); - String parsed = (String) yaml.load(output); - // System.out.println(parsed); - assertEquals(plain, parsed); - } + public void testWriteMultiLineLiteral() { + String plain = "mama\nmila\nramu"; + Yaml yaml = new Yaml(); + String output = yaml.dump(plain); + // System.out.println(output); + assertEquals("|-\n mama\n mila\n ramu\n", output); + String parsed = yaml.load(output); + // System.out.println(parsed); + assertEquals(plain, parsed); + } - public void testWriteMultiLineList() { - String one = "first\nsecond\nthird"; - String two = "one\ntwo\nthree\n"; - byte[] binary = { 8, 14, 15, 10, 126, 32, 65, 65, 65 }; - List<Object> list = new ArrayList<Object>(2); - list.add(one); - list.add(two); - list.add(binary); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String output = yaml.dump(list); - // System.out.println(output); - String etalon = "- |-\n first\n second\n third\n- |\n one\n two\n three\n- !!binary |-\n CA4PCn4gQUFB\n"; - assertEquals(etalon, output); - @SuppressWarnings("unchecked") - List<Object> parsed = (List<Object>) yaml.load(etalon); - assertEquals(3, parsed.size()); - assertEquals(one, parsed.get(0)); - assertEquals(two, parsed.get(1)); - assertEquals(new String(binary), new String((byte[]) parsed.get(2))); - } + public void testWriteMultiLineList() { + String one = "first\nsecond\nthird"; + String two = "one\ntwo\nthree\n"; + byte[] binary = {8, 14, 15, 10, 126, 32, 65, 65, 65}; + List<Object> list = new ArrayList<Object>(2); + list.add(one); + list.add(two); + list.add(binary); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String output = yaml.dump(list); + // System.out.println(output); + String etalon = + "- |-\n first\n second\n third\n- |\n one\n two\n three\n- !!binary |-\n CA4PCn4gQUFB\n"; + assertEquals(etalon, output); + @SuppressWarnings("unchecked") + List<Object> parsed = yaml.load(etalon); + assertEquals(3, parsed.size()); + assertEquals(one, parsed.get(0)); + assertEquals(two, parsed.get(1)); + assertEquals(new String(binary), new String((byte[]) parsed.get(2))); + } - public void testWriteMultiLineLiteralWithClipChomping() { - String source = "a: 1\nb: |\n mama\n mila\n ramu\n"; - // System.out.println("Source:\n" + source); - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map<String, Object> parsed = (Map<String, Object>) yaml.load(source); - String value = (String) parsed.get("b"); - // System.out.println(value); - assertEquals("mama\nmila\nramu\n", value); - String dumped = yaml.dump(parsed); - // System.out.println(dumped); - assertEquals("a: 1\nb: |\n mama\n mila\n ramu\n", dumped); - } + public void testWriteMultiLineLiteralWithClipChomping() { + String source = "a: 1\nb: |\n mama\n mila\n ramu\n"; + // System.out.println("Source:\n" + source); + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<String, Object> parsed = yaml.load(source); + String value = (String) parsed.get("b"); + // System.out.println(value); + assertEquals("mama\nmila\nramu\n", value); + String dumped = yaml.dump(parsed); + // System.out.println(dumped); + assertEquals("a: 1\nb: |\n mama\n mila\n ramu\n", dumped); + } - public void testWriteMultiLineQuotedInFlowContext() { - String source = "{a: 1, b: 'mama\n\n mila\n\n ramu'}\n"; - // System.out.println("Source:\n" + source); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.FLOW); - Yaml yaml = new Yaml(options); - @SuppressWarnings("unchecked") - Map<String, Object> parsed = (Map<String, Object>) yaml.load(source); - String value = (String) parsed.get("b"); - // System.out.println(value); - assertEquals("mama\nmila\nramu", value); - String dumped = yaml.dump(parsed); - // System.out.println(dumped); - assertEquals("{a: 1, b: \"mama\\nmila\\nramu\"}\n", dumped); - } + public void testWriteMultiLineQuotedInFlowContext() { + String source = "{a: 1, b: 'mama\n\n mila\n\n ramu'}\n"; + // System.out.println("Source:\n" + source); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.FLOW); + Yaml yaml = new Yaml(options); + @SuppressWarnings("unchecked") + Map<String, Object> parsed = yaml.load(source); + String value = (String) parsed.get("b"); + // System.out.println(value); + assertEquals("mama\nmila\nramu", value); + String dumped = yaml.dump(parsed); + // System.out.println(dumped); + assertEquals("{a: 1, b: \"mama\\nmila\\nramu\"}\n", dumped); + } - public void testWriteMultiLineLiteralWithStripChomping() { - String source = "a: 1\nb: |-\n mama\n mila\n ramu\n"; - // System.out.println("Source:\n" + source); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - @SuppressWarnings("unchecked") - Map<String, Object> parsed = (Map<String, Object>) yaml.load(source); - String value = (String) parsed.get("b"); - // System.out.println(value); - assertEquals("mama\nmila\nramu", value); - String dumped = yaml.dump(parsed); - // System.out.println(dumped); - assertEquals(source, dumped); - } + public void testWriteMultiLineLiteralWithStripChomping() { + String source = "a: 1\nb: |-\n mama\n mila\n ramu\n"; + // System.out.println("Source:\n" + source); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + @SuppressWarnings("unchecked") + Map<String, Object> parsed = yaml.load(source); + String value = (String) parsed.get("b"); + // System.out.println(value); + assertEquals("mama\nmila\nramu", value); + String dumped = yaml.dump(parsed); + // System.out.println(dumped); + assertEquals(source, dumped); + } } diff --git a/src/test/java/org/yaml/snakeyaml/emitter/EmitterTest.java b/src/test/java/org/yaml/snakeyaml/emitter/EmitterTest.java index b50310eb..2c5f2432 100644 --- a/src/test/java/org/yaml/snakeyaml/emitter/EmitterTest.java +++ b/src/test/java/org/yaml/snakeyaml/emitter/EmitterTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; @@ -23,13 +21,11 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.DumperOptions.ScalarStyle; +import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.events.DocumentStartEvent; import org.yaml.snakeyaml.events.ImplicitTuple; import org.yaml.snakeyaml.events.ScalarEvent; @@ -37,227 +33,256 @@ import org.yaml.snakeyaml.events.StreamStartEvent; public class EmitterTest extends TestCase { - public void testWriteFolded() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.FOLDED); - String folded = "0123456789 0123456789\n0123456789 0123456789"; - Map<String, String> map = new LinkedHashMap<String, String>(); - map.put("aaa", folded); - map.put("bbb", "\nbla-bla\n"); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - String etalon = "\"aaa\": >-\n 0123456789 0123456789\n\n 0123456789 0123456789\n\"bbb\": >2\n\n bla-bla\n"; - assertEquals(etalon, output); - } + public void testWriteFolded() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.FOLDED); + String folded = "0123456789 0123456789\n0123456789 0123456789"; + Map<String, String> map = new LinkedHashMap<String, String>(); + map.put("aaa", folded); + map.put("bbb", "\nbla-bla\n"); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + String etalon = + "\"aaa\": >-\n 0123456789 0123456789\n\n 0123456789 0123456789\n\"bbb\": >2\n\n bla-bla\n"; + assertEquals(etalon, output); + } - public void testWriteLiteral() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.LITERAL); - String folded = "0123456789 0123456789 0123456789 0123456789"; - Map<String, String> map = new LinkedHashMap<String, String>(); - map.put("aaa", folded); - map.put("bbb", "\nbla-bla\n"); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - String etalon = "\"aaa\": |-\n 0123456789 0123456789 0123456789 0123456789\n\"bbb\": |2\n\n bla-bla\n"; - assertEquals(etalon, output); - } + public void testWriteLiteral() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.LITERAL); + String folded = "0123456789 0123456789 0123456789 0123456789"; + Map<String, String> map = new LinkedHashMap<String, String>(); + map.put("aaa", folded); + map.put("bbb", "\nbla-bla\n"); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + String etalon = + "\"aaa\": |-\n 0123456789 0123456789 0123456789 0123456789\n\"bbb\": |2\n\n bla-bla\n"; + assertEquals(etalon, output); + } - public void testWritePlain() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.PLAIN); - String folded = "0123456789 0123456789\n0123456789 0123456789"; - Map<String, String> map = new LinkedHashMap<String, String>(); - map.put("aaa", folded); - map.put("bbb", "\nbla-bla"); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - String etalon = "aaa: |-\n 0123456789 0123456789\n 0123456789 0123456789\nbbb: |2-\n\n bla-bla\n"; - assertEquals(etalon, output); - } + public void testWritePlain() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.PLAIN); + String folded = "0123456789 0123456789\n0123456789 0123456789"; + Map<String, String> map = new LinkedHashMap<String, String>(); + map.put("aaa", folded); + map.put("bbb", "\nbla-bla"); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + String etalon = + "aaa: |-\n 0123456789 0123456789\n 0123456789 0123456789\nbbb: |2-\n\n bla-bla\n"; + assertEquals(etalon, output); + } - public void testWritePlainPretty() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.PLAIN); - options.setPrettyFlow(true); + public void testWritePlainPretty() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.PLAIN); + options.setPrettyFlow(true); - String folded = "0123456789 0123456789\n0123456789 0123456789"; - Map<String, String> map = new LinkedHashMap<String, String>(); - map.put("aaa", folded); - map.put("bbb", "\nbla-bla"); + String folded = "0123456789 0123456789\n0123456789 0123456789"; + Map<String, String> map = new LinkedHashMap<String, String>(); + map.put("aaa", folded); + map.put("bbb", "\nbla-bla"); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - String etalon = "aaa: |-\n 0123456789 0123456789\n 0123456789 0123456789\nbbb: |2-\n\n bla-bla\n"; - assertEquals(etalon, output); - } + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + String etalon = + "aaa: |-\n 0123456789 0123456789\n 0123456789 0123456789\nbbb: |2-\n\n bla-bla\n"; + assertEquals(etalon, output); + } - public void testWriteSingleQuoted() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.SINGLE_QUOTED); - String folded = "0123456789 0123456789\n0123456789 0123456789"; - Map<String, String> map = new LinkedHashMap<String, String>(); - map.put("aaa", folded); - map.put("bbb", "\nbla-bla"); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - String etalon = "'aaa': '0123456789 0123456789\n\n 0123456789 0123456789'\n'bbb': '\n\n bla-bla'\n"; - assertEquals(etalon, output); - } + public void testWriteSingleQuoted() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.SINGLE_QUOTED); + String folded = "0123456789 0123456789\n0123456789 0123456789"; + Map<String, String> map = new LinkedHashMap<String, String>(); + map.put("aaa", folded); + map.put("bbb", "\nbla-bla"); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + String etalon = + "'aaa': '0123456789 0123456789\n\n 0123456789 0123456789'\n'bbb': '\n\n bla-bla'\n"; + assertEquals(etalon, output); + } - public void testWriteDoubleQuoted() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); - String folded = "0123456789 0123456789\n0123456789 0123456789"; - Map<String, String> map = new LinkedHashMap<String, String>(); - map.put("aaa", folded); - map.put("bbb", "\nbla-bla"); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - String etalon = "\"aaa\": \"0123456789 0123456789\\n0123456789 0123456789\"\n\"bbb\": \"\\nbla-bla\"\n"; - assertEquals(etalon, output); - } + public void testWriteDoubleQuoted() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); + String folded = "0123456789 0123456789\n0123456789 0123456789"; + Map<String, String> map = new LinkedHashMap<String, String>(); + map.put("aaa", folded); + map.put("bbb", "\nbla-bla"); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + String etalon = + "\"aaa\": \"0123456789 0123456789\\n0123456789 0123456789\"\n\"bbb\": \"\\nbla-bla\"\n"; + assertEquals(etalon, output); + } - // Issue #158 - public void testWriteSupplementaryUnicode() throws IOException { - DumperOptions options = new DumperOptions(); - String burger = new String(Character.toChars(0x1f354)); - String halfBurger = "\uD83C"; - StringWriter output = new StringWriter(); - Emitter emitter = new Emitter(output, options); + // Issue #158 + public void testWriteSupplementaryUnicode() throws IOException { + DumperOptions options = new DumperOptions(); + String burger = new String(Character.toChars(0x1f354)); + String halfBurger = "\uD83C"; + StringWriter output = new StringWriter(); + Emitter emitter = new Emitter(output, options); - emitter.emit(new StreamStartEvent(null, null)); - emitter.emit(new DocumentStartEvent(null, null, false, null, null)); - emitter.emit(new ScalarEvent(null, null, new ImplicitTuple(true, false), burger - + halfBurger, null, null, '"')); - String expected = "! \"\\U0001f354\\ud83c\""; - assertEquals(expected, output.toString()); - } + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter.emit(new ScalarEvent(null, null, new ImplicitTuple(true, false), burger + halfBurger, + null, null, DumperOptions.ScalarStyle.DOUBLE_QUOTED)); + String expected = "! \"๐\\ud83c\""; + assertEquals(expected, output.toString()); + } - public void testSplitLineExpectFirstFlowSequenceItem() { + public void testSplitLineExpectFirstFlowSequenceItem() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + options.setWidth(8); + Yaml yaml; + String output; + Map<String, Object> map = new TreeMap<String, Object>(); + map.put("12345", Collections.singletonList("1111111111")); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - options.setWidth(8); - Yaml yaml; - String output; - Map<String, Object> map = new TreeMap<String, Object>(); - map.put("12345", Arrays.asList("1111111111")); + // Split lines enabled (default) + yaml = new Yaml(options); + output = yaml.dump(map); + assertEquals("{\"12345\": [\n \"1111111111\"]}\n", output); - // Split lines enabled (default) - yaml = new Yaml(options); - output = yaml.dump(map); - assertEquals("{\"12345\": [\n \"1111111111\"]}\n", output); + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump(map); + assertEquals("{\"12345\": [\"1111111111\"]}\n", output); + } - // Split lines disabled - options.setSplitLines(false); - assertFalse(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump(map); - assertEquals("{\"12345\": [\"1111111111\"]}\n", output); - } + public void testWriteIndicatorIndent() { + DumperOptions options = new DumperOptions(); + options.setIndent(5); + options.setIndicatorIndent(2); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + List<?> topLevel = + Arrays.asList(Collections.singletonMap("k1", "v1"), Collections.singletonMap("k2", "v2")); + Map<String, ?> map = Collections.singletonMap("aaa", topLevel); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + String etalon = "aaa:\n - k1: v1\n - k2: v2\n"; + assertEquals(etalon, output); + } - public void testWriteIndicatorIndent() { - DumperOptions options = new DumperOptions(); - options.setIndent(5); - options.setIndicatorIndent(2); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - List<?> topLevel = Arrays.asList(Collections.singletonMap("k1", "v1"), Collections.singletonMap("k2", "v2")); - Map<String, ?> map = Collections.singletonMap("aaa", topLevel); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - String etalon = "aaa:\n - k1: v1\n - k2: v2\n"; - assertEquals(etalon, output); - } + public void testSplitLineExpectFlowSequenceItem() { - public void testSplitLineExpectFlowSequenceItem() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + options.setWidth(8); + Yaml yaml; + String output; - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - options.setWidth(8); - Yaml yaml; - String output; + // Split lines enabled (default) + yaml = new Yaml(options); + output = yaml.dump(Arrays.asList("1111111111", "2222222222")); + assertEquals("[\"1111111111\",\n \"2222222222\"]\n", output); + output = yaml.dump(Arrays.asList("1", "2")); + assertEquals("[\"1\", \"2\"]\n", output); - // Split lines enabled (default) - yaml = new Yaml(options); - output = yaml.dump(Arrays.asList("1111111111", "2222222222")); - assertEquals("[\"1111111111\",\n \"2222222222\"]\n", output); - output = yaml.dump(Arrays.asList("1", "2")); - assertEquals("[\"1\", \"2\"]\n", output); + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump(Arrays.asList("1111111111", "2222222222")); + assertEquals("[\"1111111111\", \"2222222222\"]\n", output); + output = yaml.dump(Arrays.asList("1", "2")); + assertEquals("[\"1\", \"2\"]\n", output); + } - // Split lines disabled - options.setSplitLines(false); - assertFalse(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump(Arrays.asList("1111111111", "2222222222")); - assertEquals("[\"1111111111\", \"2222222222\"]\n", output); - output = yaml.dump(Arrays.asList("1", "2")); - assertEquals("[\"1\", \"2\"]\n", output); - } + public void testSplitLineExpectFirstFlowMappingKey() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + options.setWidth(16); + Yaml yaml; + String output; + Map<String, String> nonSplitMap = new TreeMap<String, String>(); + nonSplitMap.put("3", "4"); + Map<String, Map<String, String>> nonSplitContainerMap = + new TreeMap<String, Map<String, String>>(); + nonSplitContainerMap.put("1 2", nonSplitMap); + Map<String, String> splitMap = new TreeMap<String, String>(); + splitMap.put("3333333333", "4444444444"); + Map<String, Map<String, String>> splitContainerMap = new TreeMap<String, Map<String, String>>(); + splitContainerMap.put("1111111111 2222222222", splitMap); - public void testSplitLineExpectFirstFlowMappingKey() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - options.setWidth(16); - Yaml yaml; - String output; - Map<String, String> nonSplitMap = new TreeMap<String, String>(); - nonSplitMap.put("3", "4"); - Map<String, Map<String, String>> nonSplitContainerMap = new TreeMap<String, Map<String, String>>(); - nonSplitContainerMap.put("1 2", nonSplitMap); - Map<String, String> splitMap = new TreeMap<String, String>(); - splitMap.put("3333333333", "4444444444"); - Map<String, Map<String, String>> splitContainerMap = new TreeMap<String, Map<String, String>>(); - splitContainerMap.put("1111111111 2222222222", splitMap); + // Split lines enabled (default) + yaml = new Yaml(options); + output = yaml.dump(splitContainerMap); + assertEquals("{\"1111111111 2222222222\": {\n \"3333333333\": \"4444444444\"}}\n", output); + output = yaml.dump(nonSplitContainerMap); + assertEquals("{\"1 2\": {\"3\": \"4\"}}\n", output); - // Split lines enabled (default) - yaml = new Yaml(options); - output = yaml.dump(splitContainerMap); - assertEquals("{\"1111111111 2222222222\": {\n \"3333333333\": \"4444444444\"}}\n", output); - output = yaml.dump(nonSplitContainerMap); - assertEquals("{\"1 2\": {\"3\": \"4\"}}\n", output); + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump(splitContainerMap); + assertEquals("{\"1111111111 2222222222\": {\"3333333333\": \"4444444444\"}}\n", output); + output = yaml.dump(nonSplitContainerMap); + assertEquals("{\"1 2\": {\"3\": \"4\"}}\n", output); + } - // Split lines disabled - options.setSplitLines(false); - assertFalse(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump(splitContainerMap); - assertEquals("{\"1111111111 2222222222\": {\"3333333333\": \"4444444444\"}}\n", output); - output = yaml.dump(nonSplitContainerMap); - assertEquals("{\"1 2\": {\"3\": \"4\"}}\n", output); - } + public void testSplitLineExpectFlowMappingKey() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + options.setWidth(16); + Yaml yaml; + String output; + Map<String, String> nonSplitMap = new TreeMap<String, String>(); + nonSplitMap.put("1", "2"); + nonSplitMap.put("3", "4"); + Map<String, String> splitMap = new TreeMap<String, String>(); + splitMap.put("1111111111", "2222222222"); + splitMap.put("3333333333", "4444444444"); + + // Split lines enabled (default) + yaml = new Yaml(options); + output = yaml.dump(splitMap); + assertEquals("{\"1111111111\": \"2222222222\",\n \"3333333333\": \"4444444444\"}\n", output); + output = yaml.dump(nonSplitMap); + assertEquals("{\"1\": \"2\", \"3\": \"4\"}\n", output); - public void testSplitLineExpectFlowMappingKey() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - options.setWidth(16); - Yaml yaml; - String output; - Map<String, String> nonSplitMap = new TreeMap<String, String>(); - nonSplitMap.put("1", "2"); - nonSplitMap.put("3", "4"); - Map<String, String> splitMap = new TreeMap<String, String>(); - splitMap.put("1111111111", "2222222222"); - splitMap.put("3333333333", "4444444444"); + // Split lines disabled + options.setSplitLines(false); + assertFalse(options.getSplitLines()); + yaml = new Yaml(options); + output = yaml.dump(splitMap); + assertEquals("{\"1111111111\": \"2222222222\", \"3333333333\": \"4444444444\"}\n", output); + output = yaml.dump(nonSplitMap); + assertEquals("{\"1\": \"2\", \"3\": \"4\"}\n", output); + } - // Split lines enabled (default) - yaml = new Yaml(options); - output = yaml.dump(splitMap); - assertEquals("{\"1111111111\": \"2222222222\",\n \"3333333333\": \"4444444444\"}\n", output); - output = yaml.dump(nonSplitMap); - assertEquals("{\"1\": \"2\", \"3\": \"4\"}\n", output); + public void testAnchors() { + assertEquals("a", Emitter.prepareAnchor("a")); + assertEquals("Anchor may not contain spaces: a ", checkAnchor("a ")); + assertEquals("Anchor may not contain spaces: a \t", checkAnchor("a \t")); + assertEquals("Invalid character '[' in the anchor: a[", checkAnchor("a[")); + assertEquals("Invalid character ']' in the anchor: a]", checkAnchor("a]")); + assertEquals("Invalid character '{' in the anchor: {a", checkAnchor("{a")); + assertEquals("Invalid character '}' in the anchor: }a", checkAnchor("}a")); + assertEquals("Invalid character ',' in the anchor: a,b", checkAnchor("a,b")); + assertEquals("Invalid character '*' in the anchor: a*b", checkAnchor("a*b")); + assertEquals("Invalid character '&' in the anchor: a&b", checkAnchor("a&b")); + } - // Split lines disabled - options.setSplitLines(false); - assertFalse(options.getSplitLines()); - yaml = new Yaml(options); - output = yaml.dump(splitMap); - assertEquals("{\"1111111111\": \"2222222222\", \"3333333333\": \"4444444444\"}\n", output); - output = yaml.dump(nonSplitMap); - assertEquals("{\"1\": \"2\", \"3\": \"4\"}\n", output); + private String checkAnchor(String anchor) { + try { + Emitter.prepareAnchor(anchor); + throw new IllegalStateException("Invalid must not be accepted"); + } catch (Exception e) { + return e.getMessage(); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/emitter/EmptyStringOutputTest.java b/src/test/java/org/yaml/snakeyaml/emitter/EmptyStringOutputTest.java new file mode 100644 index 00000000..97788741 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/emitter/EmptyStringOutputTest.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.emitter; + +import java.io.IOException; +import java.io.StringWriter; +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.events.DocumentStartEvent; +import org.yaml.snakeyaml.events.ImplicitTuple; +import org.yaml.snakeyaml.events.ScalarEvent; +import org.yaml.snakeyaml.events.StreamStartEvent; + +/** + * https://bitbucket.org/snakeyaml/snakeyaml-engine/issues/23/emitting-only-an-empty-string-adds-to + */ +public class EmptyStringOutputTest extends TestCase { + + public void testOutputEmptyStringWithEmitter() throws IOException { + assertEquals("The empty output must contain ---", "---", dump("")); + } + + public void testOutputStringWithEmitter() throws IOException { + assertEquals("The non-empty output must NOT contain ---", "v1234512345", dump("v1234512345")); + } + + private String dump(String value) throws IOException { + DumperOptions options = new DumperOptions(); + StringWriter output = new StringWriter(); + Emitter emitter = new Emitter(output, options); + emitter.emit(new StreamStartEvent(null, null)); + emitter.emit(new DocumentStartEvent(null, null, false, null, null)); + emitter.emit(new ScalarEvent(null, null, new ImplicitTuple(true, false), value, null, null, + DumperOptions.ScalarStyle.PLAIN)); + return output.toString(); + } +} + + diff --git a/src/test/java/org/yaml/snakeyaml/emitter/EventConstructor.java b/src/test/java/org/yaml/snakeyaml/emitter/EventConstructor.java index feb773d9..b59f3ded 100644 --- a/src/test/java/org/yaml/snakeyaml/emitter/EventConstructor.java +++ b/src/test/java/org/yaml/snakeyaml/emitter/EventConstructor.java @@ -1,24 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter; import java.util.HashMap; import java.util.List; import java.util.Map; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.Version; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; @@ -41,88 +39,86 @@ import org.yaml.snakeyaml.nodes.ScalarNode; public class EventConstructor extends Constructor { - public EventConstructor() { - this.yamlConstructors.put(null, new ConstructEvent()); - } + public EventConstructor() { + this.yamlConstructors.put(null, new ConstructEvent()); + } - private class ConstructEvent extends AbstractConstruct { + private class ConstructEvent extends AbstractConstruct { - @SuppressWarnings("unchecked") - public Object construct(Node node) { - Map<Object, Object> mapping; - if (node instanceof ScalarNode) { - mapping = new HashMap<Object, Object>(); - } else { - mapping = constructMapping((MappingNode) node); - } - String className = node.getTag().getValue().substring(1) + "Event"; - Event value; - if (className.equals("AliasEvent")) { - value = new AliasEvent((String) mapping.get("anchor"), null, null); - } else if (className.equals("ScalarEvent")) { - String tag = (String) mapping.get("tag"); - String v = (String) mapping.get("value"); - if (v == null) { - v = ""; - } - List<Boolean> implicitList = (List<Boolean>) mapping.get("implicit"); - ImplicitTuple implicit; - if (implicitList == null) { - implicit = new ImplicitTuple(false, true); - } else { - implicit = new ImplicitTuple((Boolean) implicitList.get(0), - (Boolean) implicitList.get(1)); - } - value = new ScalarEvent((String) mapping.get("anchor"), tag, implicit, v, null, - null, null); - } else if (className.equals("SequenceStartEvent")) { - String tag = (String) mapping.get("tag"); - Boolean implicit = (Boolean) mapping.get("implicit"); - if (implicit == null) { - implicit = true; - } - value = new SequenceStartEvent((String) mapping.get("anchor"), tag, implicit, null, - null, false); - } else if (className.equals("MappingStartEvent")) { - String tag = (String) mapping.get("tag"); - Boolean implicit = (Boolean) mapping.get("implicit"); - if (implicit == null) { - implicit = true; - } - value = new MappingStartEvent((String) mapping.get("anchor"), tag, implicit, null, - null, false); - } else if (className.equals("DocumentEndEvent")) { - value = new DocumentEndEvent(null, null, false); - } else if (className.equals("DocumentStartEvent")) { - Map<String, String> tags = (Map<String, String>) mapping.get("tags"); - List<Integer> versionList = (List<Integer>) mapping.get("version"); - Version version = null; - // TODO ??? - if (versionList != null) { - Integer major = versionList.get(0).intValue(); - if (major != 1) { - throw new YAMLException("Unsupported version."); - } - Integer minor = versionList.get(1).intValue(); - if (minor == 0) { - version = Version.V1_0; - } else { - version = Version.V1_1; - } - } - value = new DocumentStartEvent(null, null, false, version, tags); - } else if (className.equals("MappingEndEvent")) { - value = new MappingEndEvent(null, null); - } else if (className.equals("SequenceEndEvent")) { - value = new SequenceEndEvent(null, null); - } else if (className.equals("StreamEndEvent")) { - value = new StreamEndEvent(null, null); - } else if (className.equals("StreamStartEvent")) { - value = new StreamStartEvent(null, null); - } else { - throw new UnsupportedOperationException(); - } - return value; + @SuppressWarnings("unchecked") + public Object construct(Node node) { + Map<Object, Object> mapping; + if (node instanceof ScalarNode) { + mapping = new HashMap<Object, Object>(); + } else { + mapping = constructMapping((MappingNode) node); + } + String className = node.getTag().getValue().substring(1) + "Event"; + Event value; + if (className.equals("AliasEvent")) { + value = new AliasEvent((String) mapping.get("anchor"), null, null); + } else if (className.equals("ScalarEvent")) { + String tag = (String) mapping.get("tag"); + String v = (String) mapping.get("value"); + if (v == null) { + v = ""; + } + List<Boolean> implicitList = (List<Boolean>) mapping.get("implicit"); + ImplicitTuple implicit; + if (implicitList == null) { + implicit = new ImplicitTuple(false, true); + } else { + implicit = new ImplicitTuple(implicitList.get(0), implicitList.get(1)); + } + value = new ScalarEvent((String) mapping.get("anchor"), tag, implicit, v, null, null, + DumperOptions.ScalarStyle.PLAIN); + } else if (className.equals("SequenceStartEvent")) { + String tag = (String) mapping.get("tag"); + Boolean implicit = (Boolean) mapping.get("implicit"); + if (implicit == null) { + implicit = true; + } + value = new SequenceStartEvent((String) mapping.get("anchor"), tag, implicit, null, null, + DumperOptions.FlowStyle.BLOCK); + } else if (className.equals("MappingStartEvent")) { + String tag = (String) mapping.get("tag"); + Boolean implicit = (Boolean) mapping.get("implicit"); + if (implicit == null) { + implicit = true; + } + value = new MappingStartEvent((String) mapping.get("anchor"), tag, implicit, null, null, + DumperOptions.FlowStyle.BLOCK); + } else if (className.equals("DocumentEndEvent")) { + value = new DocumentEndEvent(null, null, false); + } else if (className.equals("DocumentStartEvent")) { + Map<String, String> tags = (Map<String, String>) mapping.get("tags"); + List<Integer> versionList = (List<Integer>) mapping.get("version"); + Version version = null; + if (versionList != null) { + Integer major = versionList.get(0).intValue(); + if (major != 1) { + throw new YAMLException("Unsupported version."); + } + Integer minor = versionList.get(1).intValue(); + if (minor == 0) { + version = Version.V1_0; + } else { + version = Version.V1_1; + } } + value = new DocumentStartEvent(null, null, false, version, tags); + } else if (className.equals("MappingEndEvent")) { + value = new MappingEndEvent(null, null); + } else if (className.equals("SequenceEndEvent")) { + value = new SequenceEndEvent(null, null); + } else if (className.equals("StreamEndEvent")) { + value = new StreamEndEvent(null, null); + } else if (className.equals("StreamStartEvent")) { + value = new StreamStartEvent(null, null); + } else { + throw new UnsupportedOperationException(); + } + return value; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/emitter/template/MyBean.java b/src/test/java/org/yaml/snakeyaml/emitter/template/MyBean.java index 188c3861..330ebba9 100644 --- a/src/test/java/org/yaml/snakeyaml/emitter/template/MyBean.java +++ b/src/test/java/org/yaml/snakeyaml/emitter/template/MyBean.java @@ -1,93 +1,88 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter.template; import java.util.ArrayList; import java.util.List; - import org.yaml.snakeyaml.immutable.Point; public class MyBean { - private Point point; - private List<String> list; - private List<Integer> empty = new ArrayList<Integer>(); - private String id; - public Point getPoint() { - return point; - } + private Point point; + private List<String> list; + private List<Integer> empty = new ArrayList<Integer>(); + private String id; - public void setPoint(Point point) { - this.point = point; - } + public Point getPoint() { + return point; + } - public List<String> getList() { - return list; - } + public void setPoint(Point point) { + this.point = point; + } - public void setList(List<String> list) { - this.list = list; - } + public List<String> getList() { + return list; + } - public List<Integer> getEmpty() { - return empty; - } + public void setList(List<String> list) { + this.list = list; + } - public void setEmpty(List<Integer> empty) { - this.empty = empty; - } + public List<Integer> getEmpty() { + return empty; + } - public String getId() { - return id; - } + public void setEmpty(List<Integer> empty) { + this.empty = empty; + } - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof MyBean) { - MyBean bean = (MyBean) obj; - if (!id.equals(bean.id)) { - return false; - } - if (!point.equals(bean.point)) { - return false; - } - if (!list.equals(bean.list)) { - return false; - } - if (!empty.equals(bean.empty)) { - return false; - } - return true; - } else { - return false; - } - } + public void setId(String id) { + this.id = id; + } - @Override - public int hashCode() { - return id.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof MyBean) { + MyBean bean = (MyBean) obj; + if (!id.equals(bean.id)) { + return false; + } + if (!point.equals(bean.point)) { + return false; + } + if (!list.equals(bean.list)) { + return false; + } + return empty.equals(bean.empty); + } else { + return false; } + } - @Override - public String toString() { - return id; - } + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public String toString() { + return id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/emitter/template/VelocityTest.java b/src/test/java/org/yaml/snakeyaml/emitter/template/VelocityTest.java index df8b310e..9ae01a97 100644 --- a/src/test/java/org/yaml/snakeyaml/emitter/template/VelocityTest.java +++ b/src/test/java/org/yaml/snakeyaml/emitter/template/VelocityTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.emitter.template; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; @@ -31,48 +27,49 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.immutable.Point; public class VelocityTest extends TestCase { - public void testNoTemplate() { - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - String output = yaml.dumpAsMap(createBean()); - // System.out.println(output); - assertEquals(Util.getLocalResource("template/etalon1.yaml"), output); - } - public void testTemplate1() throws Exception { - VelocityContext context = new VelocityContext(); - MyBean bean = createBean(); - context.put("bean", bean); - Yaml yaml = new Yaml(); - context.put("list", yaml.dump(bean.getList())); - VelocityEngine ve = new VelocityEngine(); - ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName()); - ve.init(); - Template t = ve.getTemplate("template/mybean1.vm"); - StringWriter writer = new StringWriter(); - t.merge(context, writer); - String output = writer.toString().trim().replaceAll("\\r\\n", "\n"); - // System.out.println(output); - String etalon = Util.getLocalResource("template/etalon2-template.yaml").trim(); - assertEquals(etalon.length(), output.length()); - assertEquals(etalon, output); - // parse the YAML document - Yaml loader = new Yaml(); - MyBean parsedBean = loader.loadAs(output, MyBean.class); - assertEquals(bean, parsedBean); - } + public void testNoTemplate() { + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + String output = yaml.dumpAsMap(createBean()); + // System.out.println(output); + assertEquals(Util.getLocalResource("template/etalon1.yaml"), output); + } + + public void testTemplate1() throws Exception { + VelocityContext context = new VelocityContext(); + MyBean bean = createBean(); + context.put("bean", bean); + Yaml yaml = new Yaml(); + context.put("list", yaml.dump(bean.getList())); + VelocityEngine ve = new VelocityEngine(); + ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName()); + ve.init(); + Template t = ve.getTemplate("template/mybean1.vm"); + StringWriter writer = new StringWriter(); + t.merge(context, writer); + String output = writer.toString().trim().replaceAll("\\r\\n", "\n"); + // System.out.println(output); + String etalon = Util.getLocalResource("template/etalon2-template.yaml").trim(); + assertEquals(etalon.length(), output.length()); + assertEquals(etalon, output); + // parse the YAML document + Yaml loader = new Yaml(); + MyBean parsedBean = loader.loadAs(output, MyBean.class); + assertEquals(bean, parsedBean); + } - private MyBean createBean() { - MyBean bean = new MyBean(); - bean.setId("id123"); - List<String> list = new ArrayList<String>(); - list.add("aaa"); - list.add("bbb"); - list.add("ccc"); - bean.setList(list); - Point p = new Point(1.0, 2.0); - bean.setPoint(p); - return bean; - } + private MyBean createBean() { + MyBean bean = new MyBean(); + bean.setId("id123"); + List<String> list = new ArrayList<String>(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + bean.setList(list); + Point p = new Point(1.0, 2.0); + bean.setPoint(p); + return bean; + } } diff --git a/src/test/java/org/yaml/snakeyaml/env/ApplicationProperties.java b/src/test/java/org/yaml/snakeyaml/env/ApplicationProperties.java new file mode 100644 index 00000000..39842781 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/env/ApplicationProperties.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.env; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Builder +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ApplicationProperties { + + private String kafkaBrokers; + private String kafkaTopicName; + private String kafkaGroupIdConfig; + private Integer workers; +} diff --git a/src/test/java/org/yaml/snakeyaml/env/EnvFormatTest.java b/src/test/java/org/yaml/snakeyaml/env/EnvFormatTest.java new file mode 100644 index 00000000..f6b1854e --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/env/EnvFormatTest.java @@ -0,0 +1,117 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.env; + +import static org.yaml.snakeyaml.env.EnvScalarConstructor.ENV_FORMAT; + +import java.util.regex.Matcher; +import junit.framework.TestCase; + +/* + * ${VARIABLE:-default} evaluates to default if VARIABLE is unset or empty in the environment. + * ${VARIABLE-default} evaluates to default only if VARIABLE is unset in the environment. + * + * Similarly, the following syntax allows you to specify mandatory variables: + * + * ${VARIABLE:?err} exits with an error message containing err if VARIABLE is unset or empty in the + * environment. ${VARIABLE?err} exits with an error message containing err if VARIABLE is unset in + * the environment. + */ +public class EnvFormatTest extends TestCase { + + public void testMatchBasic() { + assertTrue(ENV_FORMAT.matcher("${V}").matches()); + assertTrue(ENV_FORMAT.matcher("${PATH}").matches()); + assertTrue(ENV_FORMAT.matcher("${VARIABLE}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE }").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE}").matches()); + assertTrue(ENV_FORMAT.matcher("${\tVARIABLE }").matches()); + + Matcher matcher = ENV_FORMAT.matcher("${VARIABLE}"); + matcher.matches(); + assertEquals("VARIABLE", matcher.group("name")); + assertNull(matcher.group("value")); + assertNull(matcher.group("separator")); + + assertFalse(ENV_FORMAT.matcher("${VARI ABLE}").matches()); + } + + public void testMatchDefault() { + assertTrue(ENV_FORMAT.matcher("${VARIABLE-default}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE-default}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE-default }").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE-default}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE-}").matches()); + + Matcher matcher = ENV_FORMAT.matcher("${VARIABLE-default}"); + matcher.matches(); + assertEquals("VARIABLE", matcher.group("name")); + assertEquals("default", matcher.group("value")); + assertEquals("-", matcher.group("separator")); + + assertFalse(ENV_FORMAT.matcher("${VARIABLE -default}").matches()); + assertFalse(ENV_FORMAT.matcher("${VARIABLE - default}").matches()); + assertFalse(ENV_FORMAT.matcher("${VARIABLE -default}").matches()); + } + + public void testMatchDefaultOrEmpty() { + assertTrue(ENV_FORMAT.matcher("${VARIABLE:-default}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE:-default }").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE:-}").matches()); + + Matcher matcher = ENV_FORMAT.matcher("${VARIABLE:-default}"); + matcher.matches(); + assertEquals("VARIABLE", matcher.group("name")); + assertEquals("default", matcher.group("value")); + assertEquals(":-", matcher.group("separator")); + + assertFalse(ENV_FORMAT.matcher("${VARIABLE :-default}").matches()); + assertFalse(ENV_FORMAT.matcher("${VARIABLE : -default}").matches()); + assertFalse(ENV_FORMAT.matcher("${VARIABLE : - default}").matches()); + } + + public void testMatchErrorDefaultOrEmpty() { + assertTrue(ENV_FORMAT.matcher("${VARIABLE:?err}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE:?err }").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE:? }").matches()); + + Matcher matcher = ENV_FORMAT.matcher("${VARIABLE:?err}"); + matcher.matches(); + assertEquals("VARIABLE", matcher.group("name")); + assertEquals("err", matcher.group("value")); + assertEquals(":?", matcher.group("separator")); + + assertFalse(ENV_FORMAT.matcher("${ VARIABLE :?err }").matches()); + assertFalse(ENV_FORMAT.matcher("${ VARIABLE : ?err }").matches()); + assertFalse(ENV_FORMAT.matcher("${ VARIABLE : ? err }").matches()); + } + + public void testMatchErrorDefault() { + assertTrue(ENV_FORMAT.matcher("${VARIABLE?err}").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE:?err }").matches()); + assertTrue(ENV_FORMAT.matcher("${ VARIABLE:?}").matches()); + + Matcher matcher = ENV_FORMAT.matcher("${ VARIABLE?err }"); + matcher.matches(); + assertEquals("VARIABLE", matcher.group("name")); + assertEquals("err", matcher.group("value")); + assertEquals("?", matcher.group("separator")); + + assertFalse(ENV_FORMAT.matcher("${ VARIABLE ?err }").matches()); + assertFalse(ENV_FORMAT.matcher("${ VARIABLE ?err }").matches()); + assertFalse(ENV_FORMAT.matcher("${ VARIABLE ? err }").matches()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/env/EnvLombokTest.java b/src/test/java/org/yaml/snakeyaml/env/EnvLombokTest.java new file mode 100644 index 00000000..19e2b140 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/env/EnvLombokTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.env; + +import static org.yaml.snakeyaml.env.EnvScalarConstructor.ENV_FORMAT; +import static org.yaml.snakeyaml.env.EnvScalarConstructor.ENV_TAG; + +import java.util.ArrayList; +import junit.framework.TestCase; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; + +public class EnvLombokTest extends TestCase { + + public void testEnvConstructor() { + Yaml yaml = new Yaml(new EnvScalarConstructor(new TypeDescription(ApplicationProperties.class), + new ArrayList<TypeDescription>(), new LoaderOptions())); + yaml.addImplicitResolver(ENV_TAG, ENV_FORMAT, "$"); + String yamlData = + "kafkaBrokers: ${KAFKA_URL:-kafka:9092}\n" + "kafkaGroupIdConfig: keycloak_group_id\n" + + "workers: 17\n" + "kafkaTopicName: ${TOPIC_NAME:-keycloakTestTopic}\n"; + ApplicationProperties props = yaml.load(yamlData); + assertEquals("kafka:9092", props.getKafkaBrokers()); + assertEquals("keycloakTestTopic", props.getKafkaTopicName()); + assertEquals("keycloak_group_id", props.getKafkaGroupIdConfig()); + assertEquals(Integer.valueOf(17), props.getWorkers()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/env/EnvScalarConstructorTest.java b/src/test/java/org/yaml/snakeyaml/env/EnvScalarConstructorTest.java new file mode 100644 index 00000000..530e3f24 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/env/EnvScalarConstructorTest.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.env; + +import junit.framework.TestCase; + +public class EnvScalarConstructorTest extends TestCase { + + private static final EnvScalarConstructor env = new EnvScalarConstructor() { + @Override + public String getEnv(String key) { + if (key.endsWith("Empty")) { + return ""; + } + if (key.endsWith("Unset")) { + return null; + } + return key + "Value"; + } + }; + + public void testEnvConstructor() { + assertEquals("URL", env.apply("VAR", "-", "default", "URL")); + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/env/EnvTagTest.java b/src/test/java/org/yaml/snakeyaml/env/EnvTagTest.java new file mode 100644 index 00000000..30af22e5 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/env/EnvTagTest.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.env; + +import static org.yaml.snakeyaml.env.EnvScalarConstructor.ENV_FORMAT; + +import java.io.StringReader; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.Node; + +/** + * test that implicit resolver assigns the tag + */ +public class EnvTagTest extends TestCase { + + public void testImplicitResolverForEnvConstructor() { + Yaml yaml = new Yaml(); + yaml.addImplicitResolver(EnvScalarConstructor.ENV_TAG, ENV_FORMAT, "$"); + Node loaded = yaml.compose(new StringReader("${PATH}")); + assertEquals(EnvScalarConstructor.ENV_TAG, loaded.getTag()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/env/EnvVariableTest.java b/src/test/java/org/yaml/snakeyaml/env/EnvVariableTest.java new file mode 100644 index 00000000..3642e3df --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/env/EnvVariableTest.java @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.env; + +import static org.yaml.snakeyaml.env.EnvScalarConstructor.ENV_FORMAT; + +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.MissingEnvironmentVariableException; + +public class EnvVariableTest extends TestCase { + + // the variables EnvironmentKey1 and EnvironmentEmpty are set by Maven + private static final String KEY1 = "EnvironmentKey1"; + private static final String EMPTY = "EnvironmentEmpty"; + private static final String VALUE1 = "EnvironmentValue1"; + + private String load(String template) { + Yaml yaml = new Yaml(new EnvScalarConstructor()); + yaml.addImplicitResolver(EnvScalarConstructor.ENV_TAG, ENV_FORMAT, "$"); + String loaded = yaml.load(template); + return loaded; + } + + public void testEnvironmentSet() { + assertEquals("Surefire plugin must set the variable.", VALUE1, System.getenv(KEY1)); + assertEquals("Surefire plugin must set the variable.", "", System.getenv(EMPTY)); + } + + public void testEnvConstructor() { + assertEquals(VALUE1, load("${EnvironmentKey1}")); + assertEquals(VALUE1, load("${EnvironmentKey1-any}")); + assertEquals(VALUE1, load("${EnvironmentKey1:-any}")); + assertEquals(VALUE1, load("${EnvironmentKey1:?any}")); + assertEquals(VALUE1, load("${EnvironmentKey1?any}")); + } + + public void testEnvConstructorForEmpty() { + assertEquals("", load("${EnvironmentEmpty}")); + assertEquals("", load("${EnvironmentEmpty?}")); + assertEquals("detected", load("${EnvironmentEmpty:-detected}")); + assertEquals("", load("${EnvironmentEmpty-detected}")); + assertEquals("", load("${EnvironmentEmpty?detectedError}")); + try { + load("${EnvironmentEmpty:?detectedError}"); + } catch (MissingEnvironmentVariableException e) { + assertEquals("Empty mandatory variable EnvironmentEmpty: detectedError", e.getMessage()); + } + } + + public void testEnvConstructorForUnset() { + assertEquals("", load("${EnvironmentUnset}")); + assertEquals("", load("${EnvironmentUnset:- }")); + assertEquals("detected", load("${EnvironmentUnset:-detected}")); + assertEquals("detected", load("${EnvironmentUnset-detected}")); + try { + load("${EnvironmentUnset:?detectedError}"); + } catch (MissingEnvironmentVariableException e) { + assertEquals("Missing mandatory variable EnvironmentUnset: detectedError", e.getMessage()); + } + try { + load("${EnvironmentUnset?detectedError}"); + } catch (MissingEnvironmentVariableException e) { + assertEquals("Missing mandatory variable EnvironmentUnset: detectedError", e.getMessage()); + } + } + + public void testDockerCompose() { + Yaml yaml = new Yaml(new EnvScalarConstructor()); + yaml.addImplicitResolver(EnvScalarConstructor.ENV_TAG, ENV_FORMAT, "$"); + String resource = Util.getLocalResource("env/docker-compose.yaml"); + Map<String, Object> compose = yaml.load(resource); + String output = compose.toString(); + assertTrue(output, output.endsWith( + "environment={URL1=EnvironmentValue1, URL2=, URL3=server3, URL4=, URL5=server5, URL6=server6}}}}")); + } + + public void testIssue493() { + Yaml yaml = new Yaml(new EnvScalarConstructor()); + yaml.addImplicitResolver(EnvScalarConstructor.ENV_TAG, ENV_FORMAT, "$"); + String resource = Util.getLocalResource("env/env-493.yaml"); + Map<String, Object> compose = yaml.load(resource); + String output = compose.toString(); + assertEquals( + "{database={url=jdbc:postgresql://localhost:5432/server493, user=user493, password=password493}}", + output); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/error/MarkTest.java b/src/test/java/org/yaml/snakeyaml/error/MarkTest.java index b67d8fa4..fa7b58c5 100644 --- a/src/test/java/org/yaml/snakeyaml/error/MarkTest.java +++ b/src/test/java/org/yaml/snakeyaml/error/MarkTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.error; @@ -19,25 +17,45 @@ import junit.framework.TestCase; public class MarkTest extends TestCase { - public void testGet_snippet() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - assertEquals(" *The first line.\n ^", mark.get_snippet()); - mark = new Mark("test1", 9, 0, 0, "The first*line.\nThe last line.", 9); - assertEquals(" The first*line.\n ^", mark.get_snippet()); - } + public void testGet_snippet() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + assertEquals(" *The first line.\n ^", mark.get_snippet()); + mark = new Mark("test1", 0, 0, 0, "The first*line.\nThe last line.".toCharArray(), 9); + assertEquals(" The first*line.\n ^", mark.get_snippet()); + } - public void testToString() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - String[] lines = mark.toString().split("\n"); - assertEquals(" in test1, line 1, column 1:", lines[0]); - assertEquals("*The first line.", lines[1].trim()); - assertEquals("^", lines[2].trim()); - } + public void testToString() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + String[] lines = mark.toString().split("\n"); + assertEquals(" in test1, line 1, column 1:", lines[0]); + assertEquals("*The first line.", lines[1].trim()); + assertEquals("^", lines[2].trim()); + } - public void testPosition() { - Mark mark = new Mark("test1", 17, 29, 213, "*The first line.\nThe last line.", 0); - assertEquals(17, mark.getIndex()); - assertEquals(29, mark.getLine()); - assertEquals(213, mark.getColumn()); + public void testPosition() { + Mark mark = new Mark("test1", 17, 29, 213, "*The first line.\nThe last line.".toCharArray(), 0); + assertEquals("index is used in JRuby", 17, mark.getIndex()); + assertEquals(29, mark.getLine()); + assertEquals(213, mark.getColumn()); + } + + public void testGetBuffer() { + Mark mark = new Mark("test1", 0, 29, 213, "*The first line.\nThe last line.".toCharArray(), 0); + int[] buffer = new int[] {42, 84, 104, 101, 32, 102, 105, 114, 115, 116, 32, 108, 105, 110, 101, + 46, 10, 84, 104, 101, 32, 108, 97, 115, 116, 32, 108, 105, 110, 101, 46}; + assertEquals(buffer.length, mark.getBuffer().length); + boolean match = true; + for (int i = 0; i < buffer.length; i++) { + if (buffer[i] != mark.getBuffer()[i]) { + match = false; + break; + } } + assertTrue(match); + } + + public void testGetPointer() { + Mark mark = new Mark("test1", 0, 29, 213, "*The first line.\nThe last line.".toCharArray(), 5); + assertEquals(5, mark.getPointer()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/error/MarkedYAMLExceptionTest.java b/src/test/java/org/yaml/snakeyaml/error/MarkedYAMLExceptionTest.java index 0725db24..ce6128fd 100644 --- a/src/test/java/org/yaml/snakeyaml/error/MarkedYAMLExceptionTest.java +++ b/src/test/java/org/yaml/snakeyaml/error/MarkedYAMLExceptionTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.error; @@ -19,43 +17,43 @@ import junit.framework.TestCase; public class MarkedYAMLExceptionTest extends TestCase { - public void testToString1() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - MarkedYAMLException exception = new MarkedYAMLException(null, null, "Error happened", mark); - assertTrue(exception.toString().contains("Error happened")); - assertTrue(exception.toString().contains("The first line")); - assertTrue(exception.toString(), exception.toString().contains("test1")); - } + public void testToString1() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + MarkedYAMLException exception = new MarkedYAMLException(null, null, "Error happened", mark); + assertTrue(exception.toString().contains("Error happened")); + assertTrue(exception.toString().contains("The first line")); + assertTrue(exception.toString(), exception.toString().contains("test1")); + } - public void testToString2() { - Mark mark = new Mark("search", 0, 0, 0, "*The first line.\nThe last line.", 0); - MarkedYAMLException exception = new MarkedYAMLException("See http://www.google.com", mark, - "Error2 happened", mark); - assertTrue(exception.toString().contains("Error2 happened")); - assertTrue(exception.toString().contains("The first line")); - assertTrue(exception.toString().contains("search")); - } + public void testToString2() { + Mark mark = new Mark("search", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + MarkedYAMLException exception = + new MarkedYAMLException("See http://www.google.com", mark, "Error2 happened", mark); + assertTrue(exception.toString().contains("Error2 happened")); + assertTrue(exception.toString().contains("The first line")); + assertTrue(exception.toString().contains("search")); + } - public void testToString3() { - MarkedYAMLException exception = new MarkedYAMLException("See http://www.google.com", null, - null, null, "Note1"); - assertTrue(exception.toString().contains("Note1")); - } + public void testToString3() { + MarkedYAMLException exception = + new MarkedYAMLException("See http://www.google.com", null, null, null, "Note1"); + assertTrue(exception.toString().contains("Note1")); + } - public void testToString4() { - Mark mark = new Mark("search", 0, 0, 0, "*The first line.\nThe last line.", 0); - MarkedYAMLException exception = new MarkedYAMLException("See http://www.google.com", mark, - null, null, null, null); - assertTrue(exception.toString().contains("first line")); - } + public void testToString4() { + Mark mark = new Mark("search", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + MarkedYAMLException exception = + new MarkedYAMLException("See http://www.google.com", mark, null, null, null, null); + assertTrue(exception.toString().contains("first line")); + } - public void testGetters() { - Mark mark = new Mark("search", 0, 0, 0, "*The first line.\nThe last line.", 0); - MarkedYAMLException exception = new MarkedYAMLException("See http://www.google.com", mark, - "Error2 happened", mark); - assertEquals("See http://www.google.com", exception.getContext()); - assertEquals(mark, exception.getContextMark()); - assertEquals("Error2 happened", exception.getProblem()); - assertEquals(mark, exception.getProblemMark()); - } + public void testGetters() { + Mark mark = new Mark("search", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + MarkedYAMLException exception = + new MarkedYAMLException("See http://www.google.com", mark, "Error2 happened", mark); + assertEquals("See http://www.google.com", exception.getContext()); + assertEquals(mark, exception.getContextMark()); + assertEquals("Error2 happened", exception.getProblem()); + assertEquals(mark, exception.getProblemMark()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/error/WrappedExceptionsTest.java b/src/test/java/org/yaml/snakeyaml/error/WrappedExceptionsTest.java new file mode 100644 index 00000000..1dd852c6 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/error/WrappedExceptionsTest.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.error; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; + +public class WrappedExceptionsTest { + + private static final String INVALID_YAML = "!!seq abc"; + + @Test + public void testWrapped() { + try { + LoaderOptions options = new LoaderOptions(); + options.setWrappedToRootException(true); + Yaml yaml = new Yaml(options); + yaml.load(INVALID_YAML); + fail(); + } catch (YAMLException e) { + assertEquals(ClassCastException.class, e.getCause().getClass()); + } + } + + @Test(expected = ClassCastException.class) + public void testUnWrapped() { + LoaderOptions options = new LoaderOptions(); + options.setWrappedToRootException(false); + Yaml yaml = new Yaml(options); + yaml.load(INVALID_YAML); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/events/ScalarEventTest.java b/src/test/java/org/yaml/snakeyaml/events/ScalarEventTest.java index b167f900..9c1221ff 100644 --- a/src/test/java/org/yaml/snakeyaml/events/ScalarEventTest.java +++ b/src/test/java/org/yaml/snakeyaml/events/ScalarEventTest.java @@ -1,35 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.events; +import static org.junit.Assert.assertNotEquals; + import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; public class ScalarEventTest extends TestCase { - public void testToString() { - ScalarEvent event = new ScalarEvent("a2", "str", new ImplicitTuple(true, true), "text", - null, null, '"'); - assertEquals( - "<org.yaml.snakeyaml.events.ScalarEvent(anchor=a2, tag=str, implicit=[true, true], value=text)>", - event.toString()); - } + public void testToString() { + ScalarEvent event = new ScalarEvent("a2", "str", new ImplicitTuple(true, true), "text", null, + null, DumperOptions.ScalarStyle.DOUBLE_QUOTED); + assertEquals( + "<org.yaml.snakeyaml.events.ScalarEvent(anchor=a2, tag=str, implicit=[true, true], value=text)>", + event.toString()); + } - public void testNotEqual() { - ScalarEvent event = new ScalarEvent("a2", "str", new ImplicitTuple(true, true), "text", - null, null, '"'); - assertFalse(event.equals(event.toString())); - } + public void testNotEqual() { + ScalarEvent event = new ScalarEvent("a2", "str", new ImplicitTuple(true, true), "text", null, + null, DumperOptions.ScalarStyle.DOUBLE_QUOTED); + assertNotEquals(event, event.toString()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Box.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Box.java index 5bcc0367..718cb485 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Box.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Box.java @@ -1,53 +1,52 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; public class Box { - private String id; - private String name; - private Item top; - private Item bottom; - - public Box(String id, String name) { - super(); - this.id = id; - this.name = name; - } - - public Item getTop() { - return top; - } - - public void setTop(Item top) { - this.top = top; - } - - public Item getBottom() { - return bottom; - } - - public void setBottom(Item bottom) { - this.bottom = bottom; - } - - public String getId() { - return id; - } - - public String getName() { - return name; - } + + private final String id; + private final String name; + private Item top; + private Item bottom; + + public Box(String id, String name) { + super(); + this.id = id; + this.name = name; + } + + public Item getTop() { + return top; + } + + public void setTop(Item top) { + this.top = top; + } + + public Item getBottom() { + return bottom; + } + + public void setBottom(Item bottom) { + this.bottom = bottom; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorErrorsTest.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorErrorsTest.java index 161286ca..f6b05caf 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorErrorsTest.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorErrorsTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.BaseConstructor; @@ -27,120 +23,113 @@ import org.yaml.snakeyaml.error.YAMLException; public class CompactConstructorErrorsTest extends TestCase { - public void test1() { - BaseConstructor compact = new CompactConstructor(); - Yaml yaml = new Yaml(compact); - String doc = Util.getLocalResource("compactnotation/error1.yaml"); - try { - yaml.load(doc); - fail("Package is not specified."); - } catch (Exception e) { - assertEquals("java.lang.ClassNotFoundException: Table", e.getMessage()); - } - } - - private Object load(String fileName) { - CompactConstructor compact = new PackageCompactConstructor( - "org.yaml.snakeyaml.extensions.compactnotation"); - Yaml yaml = new Yaml(compact); - String doc = Util.getLocalResource("compactnotation/" + fileName); - Object obj = yaml.load(doc); - assertNotNull(obj); - return obj; + public void test1() { + BaseConstructor compact = new CompactConstructor(); + Yaml yaml = new Yaml(compact); + String doc = Util.getLocalResource("compactnotation/error1.yaml"); + try { + yaml.load(doc); + fail("Package is not specified."); + } catch (Exception e) { + assertEquals("java.lang.ClassNotFoundException: Table", e.getMessage()); } - - private void failLoad(String fileName, String failure) { - load(fileName); - fail(failure); - } - - private void check(String fileName, String failure, String message) { - check(fileName, failure, message, true); - } - - private void check(String fileName, String failure, String message, boolean exactMatch) { - try { - failLoad(fileName, failure); - } catch (YAMLException e) { - String eMessage = e.getMessage(); - if (exactMatch) { - assertEquals(message, eMessage); - } else { - assertNotNull("Exception message is NULL", eMessage); - assertTrue(String.format( - "\nException message\n%s\ndoes not contain expected value\n%s", - e.getMessage(), message), eMessage.contains(message)); - } - } catch (Exception e) { - fail("Exception must be YAMLException"); - } - } - - public void test2() { - check("error2.yaml", - "No single argument constructor provided.", - "java.lang.NoSuchMethodException: org.yaml.snakeyaml.extensions.compactnotation.Table.<init>(java.lang.String)"); - } - - public void test3() { - check("error3.yaml", - "In-line parameters can only be Strings.", - "org.yaml.snakeyaml.error.YAMLException: Cannot set property='size' with value='17' (class java.lang.String) in Row id=id111"); - } - - /** - * Created Map instead of Row - */ - @SuppressWarnings("unchecked") - public void test4() { - Table table = (Table) load("error4.yaml"); - List<Row> rows = table.getRows(); - assertEquals(1, rows.size()); - assertFalse("Row should not be created.", rows.get(0) instanceof Row); - Map<String, String> map = (Map<String, String>) rows.get(0); - assertEquals(1, map.size()); - assertEquals("15}", map.get("Row(id111, description = text) {size")); - } - - /** - * Wrong indent - */ - @SuppressWarnings("unchecked") - public void test5() { - Table table = (Table) load("error5.yaml"); - List<Row> rows = table.getRows(); - assertEquals(1, rows.size()); - assertFalse("Row should not be created.", rows.get(0) instanceof Row); - Map<String, String> map = (Map<String, String>) rows.get(0); - assertEquals(4, map.size()); - // System.out.println(map); - assertNull(map.get(new Row("id222"))); - assertTrue(map.containsKey(new Row("id222"))); - assertEquals(17, map.get("size")); - } - - public void test6() { - check("error6.yaml", - "Invalid property.", - "org.yaml.snakeyaml.error.YAMLException: Unable to find property 'foo' on class: org.yaml.snakeyaml.extensions.compactnotation.Table"); - } - - public void test7() { - check("error7.yaml", - "Invalid property.", - "Unable to find property 'foo' on class: org.yaml.snakeyaml.extensions.compactnotation.Table", - false); - } - - public void test8() { - check("error8.yaml", - "No list property", - "org.yaml.snakeyaml.error.YAMLException: No list property found in class org.yaml.snakeyaml.extensions.compactnotation.Row"); - } - - public void test9() { - check("error9.yaml", - "Many list properties found", - "org.yaml.snakeyaml.error.YAMLException: Many list properties found in class org.yaml.snakeyaml.extensions.compactnotation.ManyListsTable; Please override getSequencePropertyName() to specify which property to use."); + } + + private Object load(String fileName) { + CompactConstructor compact = + new PackageCompactConstructor("org.yaml.snakeyaml.extensions.compactnotation"); + Yaml yaml = new Yaml(compact); + String doc = Util.getLocalResource("compactnotation/" + fileName); + Object obj = yaml.load(doc); + assertNotNull(obj); + return obj; + } + + private void failLoad(String fileName, String failure) { + load(fileName); + fail(failure); + } + + private void check(String fileName, String failure, String message) { + check(fileName, failure, message, true); + } + + private void check(String fileName, String failure, String message, boolean exactMatch) { + try { + failLoad(fileName, failure); + } catch (YAMLException e) { + String eMessage = e.getMessage(); + if (exactMatch) { + assertEquals(message, eMessage); + } else { + assertNotNull("Exception message is NULL", eMessage); + assertTrue(String.format("\nException message\n%s\ndoes not contain expected value\n%s", + e.getMessage(), message), eMessage.contains(message)); + } + } catch (Exception e) { + fail("Exception must be YAMLException"); } + } + + public void test2() { + check("error2.yaml", "No single argument constructor provided.", + "java.lang.NoSuchMethodException: org.yaml.snakeyaml.extensions.compactnotation.Table.<init>(java.lang.String)"); + } + + public void test3() { + check("error3.yaml", "In-line parameters can only be Strings.", + "org.yaml.snakeyaml.error.YAMLException: Cannot set property='size' with value='17' (class java.lang.String) in Row id=id111"); + } + + /** + * Created Map instead of Row + */ + @SuppressWarnings("unchecked") + public void test4() { + Table table = (Table) load("error4.yaml"); + List<Row> rows = table.getRows(); + assertEquals(1, rows.size()); + assertFalse("Row should not be created.", rows.get(0) instanceof Row); + Map<String, String> map = (Map<String, String>) rows.get(0); + assertEquals(1, map.size()); + assertEquals("15}", map.get("Row(id111, description = text) {size")); + } + + /** + * Wrong indent + */ + @SuppressWarnings("unchecked") + public void test5() { + Table table = (Table) load("error5.yaml"); + List<Row> rows = table.getRows(); + assertEquals(1, rows.size()); + assertFalse("Row should not be created.", rows.get(0) instanceof Row); + Map<String, String> map = (Map<String, String>) rows.get(0); + assertEquals(4, map.size()); + // System.out.println(map); + assertNull(map.get(new Row("id222"))); + assertTrue(map.containsKey(new Row("id222"))); + assertEquals(17, map.get("size")); + } + + public void test6() { + check("error6.yaml", "Invalid property.", + "org.yaml.snakeyaml.error.YAMLException: Unable to find property 'foo' on class: org.yaml.snakeyaml.extensions.compactnotation.Table"); + } + + public void test7() { + check("error7.yaml", "Invalid property.", + "Unable to find property 'foo' on class: org.yaml.snakeyaml.extensions.compactnotation.Table", + false); + } + + public void test8() { + check("error8.yaml", "No list property", + "org.yaml.snakeyaml.error.YAMLException: No list property found in class org.yaml.snakeyaml.extensions.compactnotation.Row"); + } + + public void test9() { + check("error9.yaml", "Many list properties found", + "org.yaml.snakeyaml.error.YAMLException: Many list properties found in class org.yaml.snakeyaml.extensions.compactnotation.ManyListsTable; Please override getSequencePropertyName() to specify which property to use."); + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorExampleTest.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorExampleTest.java index d8e355c0..bac0cd14 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorExampleTest.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorExampleTest.java @@ -1,180 +1,176 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; import java.util.Iterator; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class CompactConstructorExampleTest extends TestCase { - private Object load(String fileName) { - CompactConstructor compact = new CompactConstructor(); - Yaml yaml = new Yaml(compact); - String doc = Util.getLocalResource("compactnotation/" + fileName); - Object obj = yaml.load(doc); - assertNotNull(obj); - return obj; - } - - public void test1() { - Object obj = load("example1.yaml"); - assertEquals(new Container(), obj); - } - - public void test2() { - Object obj = load("example2.yaml"); - assertEquals(new Container("title"), obj); - } - - public void test3() { - Container obj = (Container) load("example3.yaml"); - assertEquals(new Container("title3"), obj); - assertEquals("title3", obj.getTitle()); - assertEquals("parent", obj.getName()); - assertEquals("123", obj.getId()); - } - - public void test4() { - Object obj = load("example4.yaml"); - // System.out.println(obj); - Container container = (Container) obj; - assertNotNull(obj); - assertEquals(new Container("title4"), obj); - assertEquals("title4", container.getTitle()); - assertEquals("child4", container.getName()); - assertEquals("444", container.getId()); - } - - public void test5() { - Object obj = load("example5.yaml"); - // System.out.println(obj); - Container container = (Container) obj; - assertNotNull(obj); - assertEquals(new Container("title4"), obj); - assertEquals("title4", container.getTitle()); - assertEquals("child5", container.getName()); - assertEquals("ID555", container.getId()); + private Object load(String fileName) { + CompactConstructor compact = new CompactConstructor(); + Yaml yaml = new Yaml(compact); + String doc = Util.getLocalResource("compactnotation/" + fileName); + Object obj = yaml.load(doc); + assertNotNull(obj); + return obj; + } + + public void test1() { + Object obj = load("example1.yaml"); + assertEquals(new Container(), obj); + } + + public void test2() { + Object obj = load("example2.yaml"); + assertEquals(new Container("title"), obj); + } + + public void test3() { + Container obj = (Container) load("example3.yaml"); + assertEquals(new Container("title3"), obj); + assertEquals("title3", obj.getTitle()); + assertEquals("parent", obj.getName()); + assertEquals("123", obj.getId()); + } + + public void test4() { + Object obj = load("example4.yaml"); + // System.out.println(obj); + Container container = (Container) obj; + assertNotNull(obj); + assertEquals(new Container("title4"), obj); + assertEquals("title4", container.getTitle()); + assertEquals("child4", container.getName()); + assertEquals("444", container.getId()); + } + + public void test5() { + Object obj = load("example5.yaml"); + // System.out.println(obj); + Container container = (Container) obj; + assertNotNull(obj); + assertEquals(new Container("title4"), obj); + assertEquals("title4", container.getTitle()); + assertEquals("child5", container.getName()); + assertEquals("ID555", container.getId()); + } + + public void test6() { + Object obj = load("example6.yaml"); + // System.out.println(obj); + Container container = (Container) obj; + assertNotNull(obj); + assertEquals(new Container("title4"), obj); + assertEquals("title4", container.getTitle()); + assertEquals("child6", container.getName()); + assertEquals("ID6", container.getId()); + } + + public void test7() { + Object obj = load("example7.yaml"); + // System.out.println(obj); + Container container = (Container) obj; + assertNotNull(obj); + assertEquals(new Container("The title"), obj); + assertEquals("The title", container.getTitle()); + assertEquals("child7", container.getName()); + assertEquals("id7", container.getId()); + } + + @SuppressWarnings("unchecked") + // TODO it is unclear how the result should look like for CON + public void test9() { + Map<String, Object> map = (Map<String, Object>) load("example9.yaml"); + assertEquals(1, map.size()); + Map<Container, Map<String, String>> containers = + (Map<Container, Map<String, String>>) map.get("something"); + // System.out.println(obj); + assertEquals(2, containers.size()); + for (Container c : containers.keySet()) { + assertTrue(c.getId().matches("id\\d")); + assertEquals(1, containers.get(c).size()); } - - public void test6() { - Object obj = load("example6.yaml"); - // System.out.println(obj); - Container container = (Container) obj; - assertNotNull(obj); - assertEquals(new Container("title4"), obj); - assertEquals("title4", container.getTitle()); - assertEquals("child6", container.getName()); - assertEquals("ID6", container.getId()); - } - - public void test7() { - Object obj = load("example7.yaml"); - // System.out.println(obj); - Container container = (Container) obj; - assertNotNull(obj); - assertEquals(new Container("The title"), obj); - assertEquals("The title", container.getTitle()); - assertEquals("child7", container.getName()); - assertEquals("id7", container.getId()); - } - - @SuppressWarnings("unchecked") - // TODO it is unclear how the result should look like for CON - public void test9() { - Map<String, Object> map = (Map<String, Object>) load("example9.yaml"); - assertEquals(1, map.size()); - Map<Container, Map<String, String>> containers = (Map<Container, Map<String, String>>) map - .get("something"); - // System.out.println(obj); - assertEquals(2, containers.size()); - for (Container c : containers.keySet()) { - assertTrue(c.getId().matches("id\\d")); - assertEquals(1, containers.get(c).size()); - } - } - - @SuppressWarnings("unchecked") - public void test10() { - Map<String, Object> map = (Map<String, Object>) load("example10.yaml"); - assertEquals(1, map.size()); - List<Container> containers = (List<Container>) map.get("something"); - // System.out.println(obj); - assertEquals(3, containers.size()); - for (Container c : containers) { - assertTrue(c.toString(), c.getId().matches("id\\d+")); - assertTrue(c.toString(), c.getName().matches("child\\d+")); - // System.out.println(c); - } - } - - public void test11withoutPackageNames() { - Constructor compact = new PackageCompactConstructor( - "org.yaml.snakeyaml.extensions.compactnotation"); - Yaml yaml = new Yaml(compact); - String doc = Util.getLocalResource("compactnotation/example11.yaml"); - Box box = (Box) yaml.load(doc); - assertNotNull(box); - assertEquals("id11", box.getId()); - assertEquals("Main box", box.getName()); - Item top = box.getTop(); - assertEquals("id003", top.getId()); - assertEquals("25.0", top.getPrice()); - assertEquals("parrot", top.getName()); - Item bottom = box.getBottom(); - assertEquals("id004", bottom.getId()); - assertEquals("3.5", bottom.getPrice()); - assertEquals("sweet", bottom.getName()); - } - - public void test12withList() { - Constructor compact = new TableCompactConstructor( - "org.yaml.snakeyaml.extensions.compactnotation"); - Yaml yaml = new Yaml(compact); - String doc = Util.getLocalResource("compactnotation/example12.yaml"); - Table table = (Table) yaml.load(doc); - assertNotNull(table); - assertEquals("id12", table.getId()); - assertEquals("A table", table.getName()); - List<Row> rows = table.getRows(); - assertEquals(3, rows.size()); - Iterator<Row> iter = rows.iterator(); - Row first = iter.next(); - assertEquals("id111", first.getId()); - assertEquals("I think; therefore I am.", first.getDescription()); - assertEquals(0.125, first.getRatio(), 0.000000001); - assertEquals(15, first.getSize()); - Row second = iter.next(); - assertEquals("id222", second.getId()); - assertEquals("We do not need new lines here, just replace them all with spaces\n", - second.getDescription()); - assertEquals(0.333, second.getRatio(), 0.000000001); - assertEquals(17, second.getSize()); - Row third = iter.next(); - assertEquals("id333", third.getId()); - assertEquals( - "Please preserve all\nthe lines because they may be\nimportant, but do not include the last one !!!", - third.getDescription()); - assertEquals(0.88, third.getRatio(), 0.000000001); - assertEquals(52, third.getSize()); + } + + @SuppressWarnings("unchecked") + public void test10() { + Map<String, Object> map = (Map<String, Object>) load("example10.yaml"); + assertEquals(1, map.size()); + List<Container> containers = (List<Container>) map.get("something"); + // System.out.println(obj); + assertEquals(3, containers.size()); + for (Container c : containers) { + assertTrue(c.toString(), c.getId().matches("id\\d+")); + assertTrue(c.toString(), c.getName().matches("child\\d+")); + // System.out.println(c); } + } + + public void test11withoutPackageNames() { + Constructor compact = + new PackageCompactConstructor("org.yaml.snakeyaml.extensions.compactnotation"); + Yaml yaml = new Yaml(compact); + String doc = Util.getLocalResource("compactnotation/example11.yaml"); + Box box = yaml.load(doc); + assertNotNull(box); + assertEquals("id11", box.getId()); + assertEquals("Main box", box.getName()); + Item top = box.getTop(); + assertEquals("id003", top.getId()); + assertEquals("25.0", top.getPrice()); + assertEquals("parrot", top.getName()); + Item bottom = box.getBottom(); + assertEquals("id004", bottom.getId()); + assertEquals("3.5", bottom.getPrice()); + assertEquals("sweet", bottom.getName()); + } + + public void test12withList() { + Constructor compact = + new TableCompactConstructor("org.yaml.snakeyaml.extensions.compactnotation"); + Yaml yaml = new Yaml(compact); + String doc = Util.getLocalResource("compactnotation/example12.yaml"); + Table table = yaml.load(doc); + assertNotNull(table); + assertEquals("id12", table.getId()); + assertEquals("A table", table.getName()); + List<Row> rows = table.getRows(); + assertEquals(3, rows.size()); + Iterator<Row> iter = rows.iterator(); + Row first = iter.next(); + assertEquals("id111", first.getId()); + assertEquals("I think; therefore I am.", first.getDescription()); + assertEquals(0.125, first.getRatio(), 0.000000001); + assertEquals(15, first.getSize()); + Row second = iter.next(); + assertEquals("id222", second.getId()); + assertEquals("We do not need new lines here, just replace them all with spaces\n", + second.getDescription()); + assertEquals(0.333, second.getRatio(), 0.000000001); + assertEquals(17, second.getSize()); + Row third = iter.next(); + assertEquals("id333", third.getId()); + assertEquals( + "Please preserve all\nthe lines because they may be\nimportant, but do not include the last one !!!", + third.getDescription()); + assertEquals(0.88, third.getRatio(), 0.000000001); + assertEquals(52, third.getSize()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorTest.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorTest.java index 837d463c..b27219d7 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/CompactConstructorTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; @@ -19,94 +17,94 @@ import junit.framework.TestCase; public class CompactConstructorTest extends TestCase { - public void testNoCompactData() { - CompactConstructor flow = new CompactConstructor(); - assertNull(flow.getCompactData("scalar")); - assertNull(flow.getCompactData("123")); - assertNull(flow.getCompactData("(name=frame,title=My Frame)")); - assertNull(flow.getCompactData("JFrame name=frame,title=My Frame)")); - assertNull(flow.getCompactData("JFrame name=frame,title=My Frame")); - assertNull(flow.getCompactData("JFrame(name=frame,title=My Frame")); - assertNull(flow.getCompactData("JFrame(name=frame,title=My Frame)b")); - assertNull(flow.getCompactData("JFrame(name=frame,title=My Frame) ")); - assertNull(flow.getCompactData("JFrame(name=)")); - assertNull(flow.getCompactData("JFrame(=name)")); - } + public void testNoCompactData() { + CompactConstructor flow = new CompactConstructor(); + assertNull(flow.getCompactData("scalar")); + assertNull(flow.getCompactData("123")); + assertNull(flow.getCompactData("(name=frame,title=My Frame)")); + assertNull(flow.getCompactData("JFrame name=frame,title=My Frame)")); + assertNull(flow.getCompactData("JFrame name=frame,title=My Frame")); + assertNull(flow.getCompactData("JFrame(name=frame,title=My Frame")); + assertNull(flow.getCompactData("JFrame(name=frame,title=My Frame)b")); + assertNull(flow.getCompactData("JFrame(name=frame,title=My Frame) ")); + assertNull(flow.getCompactData("JFrame(name=)")); + assertNull(flow.getCompactData("JFrame(=name)")); + } - public void testGetCompactData1() { - CompactConstructor flow = new CompactConstructor(); - CompactData data = flow.getCompactData("JFrame(name=frame)"); - assertNotNull(data); - assertEquals("JFrame", data.getPrefix()); - assertEquals(1, data.getProperties().size()); - assertEquals("frame", data.getProperties().get("name")); - } + public void testGetCompactData1() { + CompactConstructor flow = new CompactConstructor(); + CompactData data = flow.getCompactData("JFrame(name=frame)"); + assertNotNull(data); + assertEquals("JFrame", data.getPrefix()); + assertEquals(1, data.getProperties().size()); + assertEquals("frame", data.getProperties().get("name")); + } - public void testGetCompactData2() { - CompactConstructor flow = new CompactConstructor(); - CompactData data = flow.getCompactData("Frame(name=frame,title=My Frame)"); - assertNotNull(data); - assertEquals("Frame", data.getPrefix()); - assertEquals(2, data.getProperties().size()); - assertEquals("frame", data.getProperties().get("name")); - assertEquals("My Frame", data.getProperties().get("title")); + public void testGetCompactData2() { + CompactConstructor flow = new CompactConstructor(); + CompactData data = flow.getCompactData("Frame(name=frame,title=My Frame)"); + assertNotNull(data); + assertEquals("Frame", data.getPrefix()); + assertEquals(2, data.getProperties().size()); + assertEquals("frame", data.getProperties().get("name")); + assertEquals("My Frame", data.getProperties().get("title")); - assertNotNull(flow.getCompactData("JFrame ( name = frame , title = My Frame )")); - } + assertNotNull(flow.getCompactData("JFrame ( name = frame , title = My Frame )")); + } - public void testGetCompactData3() { - CompactConstructor flow = new CompactConstructor(); - CompactData data = flow - .getCompactData("JFrame ( name = frame , title = My Frame, number= 123 )"); - assertNotNull(data); - assertEquals("JFrame", data.getPrefix()); - assertEquals(3, data.getProperties().size()); - assertEquals("frame", data.getProperties().get("name")); - assertEquals("My Frame", data.getProperties().get("title")); - assertEquals("123", data.getProperties().get("number")); - } + public void testGetCompactData3() { + CompactConstructor flow = new CompactConstructor(); + CompactData data = + flow.getCompactData("JFrame ( name = frame , title = My Frame, number= 123 )"); + assertNotNull(data); + assertEquals("JFrame", data.getPrefix()); + assertEquals(3, data.getProperties().size()); + assertEquals("frame", data.getProperties().get("name")); + assertEquals("My Frame", data.getProperties().get("title")); + assertEquals("123", data.getProperties().get("number")); + } - public void testGetCompactData4() { - CompactConstructor flow = new CompactConstructor(); - CompactData data = flow.getCompactData("JFrame(title)"); - assertNotNull(data); - assertEquals("JFrame", data.getPrefix()); - assertEquals(0, data.getProperties().size()); - assertEquals(1, data.getArguments().size()); - assertEquals("title", data.getArguments().get(0)); - } + public void testGetCompactData4() { + CompactConstructor flow = new CompactConstructor(); + CompactData data = flow.getCompactData("JFrame(title)"); + assertNotNull(data); + assertEquals("JFrame", data.getPrefix()); + assertEquals(0, data.getProperties().size()); + assertEquals(1, data.getArguments().size()); + assertEquals("title", data.getArguments().get(0)); + } - public void testGetCompactData5() { - CompactConstructor flow = new CompactConstructor(); - CompactData data = flow.getCompactData("JFrame(id123, title, name=foo, alignment=center)"); - assertNotNull(data); - assertEquals("JFrame", data.getPrefix()); - assertEquals(2, data.getProperties().size()); - assertEquals(2, data.getArguments().size()); - assertEquals("id123", data.getArguments().get(0)); - assertEquals("title", data.getArguments().get(1)); - } + public void testGetCompactData5() { + CompactConstructor flow = new CompactConstructor(); + CompactData data = flow.getCompactData("JFrame(id123, title, name=foo, alignment=center)"); + assertNotNull(data); + assertEquals("JFrame", data.getPrefix()); + assertEquals(2, data.getProperties().size()); + assertEquals(2, data.getArguments().size()); + assertEquals("id123", data.getArguments().get(0)); + assertEquals("title", data.getArguments().get(1)); + } - public void testGetCompactData6() { - CompactConstructor flow = new CompactConstructor(); - CompactData data = flow.getCompactData("JFrame()"); - assertNotNull(data); - assertEquals("JFrame", data.getPrefix()); - assertEquals(0, data.getProperties().size()); - assertEquals(0, data.getArguments().size()); - } + public void testGetCompactData6() { + CompactConstructor flow = new CompactConstructor(); + CompactData data = flow.getCompactData("JFrame()"); + assertNotNull(data); + assertEquals("JFrame", data.getPrefix()); + assertEquals(0, data.getProperties().size()); + assertEquals(0, data.getArguments().size()); + } - public void testGetCompactData7() { - CompactConstructor flow = new CompactConstructor(); - CompactData data = flow.getCompactData("package.Container(name=parent, id=123)"); - assertNotNull(data); - assertEquals("package.Container", data.getPrefix()); - assertEquals(2, data.getProperties().size()); - assertEquals(0, data.getArguments().size()); - } + public void testGetCompactData7() { + CompactConstructor flow = new CompactConstructor(); + CompactData data = flow.getCompactData("package.Container(name=parent, id=123)"); + assertNotNull(data); + assertEquals("package.Container", data.getPrefix()); + assertEquals(2, data.getProperties().size()); + assertEquals(0, data.getArguments().size()); + } - public void testCompactDataToString() { - CompactData data = new CompactData("foo"); - assertEquals("CompactData: foo {}", data.toString()); - } + public void testCompactDataToString() { + CompactData data = new CompactData("foo"); + assertEquals("CompactData: foo {}", data.toString()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Container.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Container.java index 56b3c199..de769d56 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Container.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Container.java @@ -1,76 +1,75 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; public class Container { - private String title; - private String name; - private String id; - public Container() { - this("no title"); - } + private final String title; + private String name; + private String id; - public Container(String title) { - this.title = title; - } + public Container() { + this("no title"); + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Container) { - Container c = (Container) obj; - if (name != null && !name.equals(c.name)) { - return false; - } - if (id != null && !id.equals(c.id)) { - return false; - } - return title.equals(c.title); - } else { - return false; - } - } + public Container(String title) { + this.title = title; + } - @Override - public int hashCode() { - return title.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Container) { + Container c = (Container) obj; + if (name != null && !name.equals(c.name)) { + return false; + } + if (id != null && !id.equals(c.id)) { + return false; + } + return title.equals(c.title); + } else { + return false; } + } - @Override - public String toString() { - return "Container=" + title; - } + @Override + public int hashCode() { + return title.hashCode(); + } - public String getName() { - return name; - } + @Override + public String toString() { + return "Container=" + title; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getId() { - return id; - } + public void setName(String name) { + this.name = name; + } - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public String getTitle() { - return title; - } + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Item.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Item.java index d6314c02..abfd3422 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Item.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Item.java @@ -1,46 +1,45 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; public class Item { - private String id; - private String price; - private String name; - public Item(String id) { - this.id = id; - } + private final String id; + private String price; + private String name; - public String getPrice() { - return price; - } + public Item(String id) { + this.id = id; + } - public void setPrice(String price) { - this.price = price; - } + public String getPrice() { + return price; + } - public String getName() { - return name; - } + public void setPrice(String price) { + this.price = price; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getId() { - return id; - } + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/ManyListsTable.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/ManyListsTable.java index 8b52b2ea..2aed8954 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/ManyListsTable.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/ManyListsTable.java @@ -1,48 +1,47 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; import java.util.List; public class ManyListsTable { - private String id; - private List<Row> rows; - private List<String> names; - public ManyListsTable(String id) { - this.id = id; - } + private final String id; + private List<Row> rows; + private List<String> names; - public List<Row> getRows() { - return rows; - } + public ManyListsTable(String id) { + this.id = id; + } - public void setRows(List<Row> rows) { - this.rows = rows; - } + public List<Row> getRows() { + return rows; + } - public String getId() { - return id; - } + public void setRows(List<Row> rows) { + this.rows = rows; + } - public List<String> getNames() { - return names; - } + public String getId() { + return id; + } - public void setNames(List<String> names) { - this.names = names; - } + public List<String> getNames() { + return names; + } + + public void setNames(List<String> names) { + this.names = names; + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructorTest.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructorTest.java index 551b721a..691880a0 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/PackageCompactConstructorTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; @@ -19,32 +17,32 @@ import junit.framework.TestCase; public class PackageCompactConstructorTest extends TestCase { - public void testGetClassForName() throws ClassNotFoundException { - assertEquals(Table.class, check("Table")); - assertEquals(Table.class, check("org.yaml.snakeyaml.extensions.compactnotation.Table")); - assertEquals(String.class, check("java.lang.String")); - } + public void testGetClassForName() throws ClassNotFoundException { + assertEquals(Table.class, check("Table")); + assertEquals(Table.class, check("org.yaml.snakeyaml.extensions.compactnotation.Table")); + assertEquals(String.class, check("java.lang.String")); + } - public void testException1() throws ClassNotFoundException { - try { - check("foo.Bar"); - fail(); - } catch (ClassNotFoundException e) { - assertEquals("foo.Bar", e.getMessage()); - } + public void testException1() throws ClassNotFoundException { + try { + check("foo.Bar"); + fail(); + } catch (ClassNotFoundException e) { + assertEquals("foo.Bar", e.getMessage()); } + } - public void testException2() throws ClassNotFoundException { - try { - check("FooBar"); - fail(); - } catch (ClassNotFoundException e) { - assertEquals("FooBar", e.getMessage()); - } + public void testException2() throws ClassNotFoundException { + try { + check("FooBar"); + fail(); + } catch (ClassNotFoundException e) { + assertEquals("FooBar", e.getMessage()); } + } - private Class<?> check(String name) throws ClassNotFoundException { - return new PackageCompactConstructor("org.yaml.snakeyaml.extensions.compactnotation") - .getClassForName(name); - } + private Class<?> check(String name) throws ClassNotFoundException { + return new PackageCompactConstructor("org.yaml.snakeyaml.extensions.compactnotation") + .getClassForName(name); + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Row.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Row.java index 8e21ad05..076a4a3d 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Row.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Row.java @@ -1,80 +1,79 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; public class Row { - private String id; - private int size; - private double ratio; - private float floatRatio; - private String description; - public Row(String id) { - super(); - this.id = id; - } + private final String id; + private int size; + private double ratio; + private float floatRatio; + private String description; - public int getSize() { - return size; - } + public Row(String id) { + super(); + this.id = id; + } - public void setSize(int size) { - this.size = size; - } + public int getSize() { + return size; + } - public double getRatio() { - return ratio; - } + public void setSize(int size) { + this.size = size; + } - public void setRatio(double ratio) { - this.ratio = ratio; - } + public double getRatio() { + return ratio; + } - public float getFloatRatio() { - return floatRatio; - } + public void setRatio(double ratio) { + this.ratio = ratio; + } - public void setFloatRatio(float floatRatio) { - this.floatRatio = floatRatio; - } + public float getFloatRatio() { + return floatRatio; + } - public String getDescription() { - return description; - } + public void setFloatRatio(float floatRatio) { + this.floatRatio = floatRatio; + } - public void setDescription(String description) { - this.description = description; - } + public String getDescription() { + return description; + } - public String getId() { - return id; - } + public void setDescription(String description) { + this.description = description; + } - @Override - public boolean equals(Object obj) { - return toString().equals(obj.toString()); - } + public String getId() { + return id; + } - @Override - public int hashCode() { - return id.hashCode(); - } + @Override + public boolean equals(Object obj) { + return toString().equals(obj.toString()); + } - @Override - public String toString() { - return "Row id=" + id; - } + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public String toString() { + return "Row id=" + id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Table.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Table.java index dce1eb0f..45b081a2 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Table.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/Table.java @@ -1,46 +1,45 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; import java.util.List; public class Table { - private String id; - private String name; - private List<Row> rows; - - public Table(String id, String name) { - super(); - this.id = id; - this.name = name; - } - - public List<Row> getRows() { - return rows; - } - - public void setRows(List<Row> rows) { - this.rows = rows; - } - - public String getId() { - return id; - } - - public String getName() { - return name; - } + + private final String id; + private final String name; + private List<Row> rows; + + public Table(String id, String name) { + super(); + this.id = id; + this.name = name; + } + + public List<Row> getRows() { + return rows; + } + + public void setRows(List<Row> rows) { + this.rows = rows; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } } diff --git a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/TableCompactConstructor.java b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/TableCompactConstructor.java index a6e074b6..efb79a89 100644 --- a/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/TableCompactConstructor.java +++ b/src/test/java/org/yaml/snakeyaml/extensions/compactnotation/TableCompactConstructor.java @@ -1,24 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.extensions.compactnotation; public class TableCompactConstructor extends PackageCompactConstructor { - public TableCompactConstructor(String packageName) { - super(packageName); - } + public TableCompactConstructor(String packageName) { + super(packageName); + } } diff --git a/src/test/java/org/yaml/snakeyaml/generics/AbstractAnimal.java b/src/test/java/org/yaml/snakeyaml/generics/AbstractAnimal.java index 68452efd..ef127174 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/AbstractAnimal.java +++ b/src/test/java/org/yaml/snakeyaml/generics/AbstractAnimal.java @@ -1,32 +1,31 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; public abstract class AbstractAnimal<T> { - private String name; - public String getName() { - return name; - } + private String name; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public abstract T getHome(); + public void setName(String name) { + this.name = name; + } - public abstract void setHome(T home); + public abstract T getHome(); + + public abstract void setHome(T home); } diff --git a/src/test/java/org/yaml/snakeyaml/generics/Bird.java b/src/test/java/org/yaml/snakeyaml/generics/Bird.java index 0b7bbe8b..7dd9b0ca 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/Bird.java +++ b/src/test/java/org/yaml/snakeyaml/generics/Bird.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; public class Bird extends AbstractAnimal<Nest> { - private Nest home; - public Nest getHome() { - return home; - } + private Nest home; - public void setHome(Nest home) { - this.home = home; - } + public Nest getHome() { + return home; + } + + public void setHome(Nest home) { + this.home = home; + } } diff --git a/src/test/java/org/yaml/snakeyaml/generics/BirdTest.java b/src/test/java/org/yaml/snakeyaml/generics/BirdTest.java index 499539ff..8d650746 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/BirdTest.java +++ b/src/test/java/org/yaml/snakeyaml/generics/BirdTest.java @@ -1,57 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; import java.beans.IntrospectionException; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class BirdTest extends TestCase { - public void testHome() throws IntrospectionException { - Bird bird = new Bird(); - bird.setName("Eagle"); - Nest home = new Nest(); - home = new Nest(); - home.setHeight(3); - bird.setHome(home); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bird); - Bird parsed; - String javaVendor = System.getProperty("java.vm.name"); - Yaml loader = new Yaml(); - if (GenericsBugDetector.isProperIntrospection()) { - // no global tags - System.out.println("java.vm.name: " + javaVendor); - assertEquals("no global tags must be emitted.", "home:\n height: 3\nname: Eagle\n", - output); - parsed = loader.loadAs(output, Bird.class); - - } else { - // with global tags - System.out - .println("JDK requires global tags for JavaBean properties with Java Generics. java.vm.name: " - + javaVendor); - assertEquals("global tags are inevitable here.", - "home: !!org.yaml.snakeyaml.generics.Nest\n height: 3\nname: Eagle\n", output); - parsed = loader.loadAs(output, Bird.class); - } - assertEquals(bird.getName(), parsed.getName()); - assertEquals(bird.getHome().getHeight(), parsed.getHome().getHeight()); - } + public void testHome() throws IntrospectionException { + Bird bird = new Bird(); + bird.setName("Eagle"); + Nest home = new Nest(); + home = new Nest(); + home.setHeight(3); + bird.setHome(home); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bird); + Bird parsed; + String javaVendor = System.getProperty("java.vm.name"); + Yaml loader = new Yaml(); + // no global tags + System.out.println("java.vm.name: " + javaVendor); + assertEquals("no global tags must be emitted.", "home:\n height: 3\nname: Eagle\n", output); + parsed = loader.loadAs(output, Bird.class); + assertEquals(bird.getName(), parsed.getName()); + assertEquals(bird.getHome().getHeight(), parsed.getHome().getHeight()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/generics/GenericArrayTypeTest.java b/src/test/java/org/yaml/snakeyaml/generics/GenericArrayTypeTest.java index e81c137e..5f6815c8 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/GenericArrayTypeTest.java +++ b/src/test/java/org/yaml/snakeyaml/generics/GenericArrayTypeTest.java @@ -1,119 +1,97 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; import java.beans.IntrospectionException; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class GenericArrayTypeTest extends TestCase { - public void testClasses() throws IntrospectionException { - GenericArray ga = new GenericArray(); - Yaml yaml = new Yaml(); - String doc = yaml.dump(ga); - // System.out.println(doc); - String etalon = "!!org.yaml.snakeyaml.generics.GenericArrayTypeTest$GenericArray\n" - + "home: [1, 2, 3]\n" + "name: Array3\n"; - assertEquals(etalon, doc); - if (GenericsBugDetector.isProperIntrospection()) { - GenericArray parsed = (GenericArray) yaml.load(doc); - assertEquals("Array3", parsed.getName()); - assertEquals(3, parsed.getHome().length); - } else { - try { - yaml.load(doc); - } catch (Exception e) { - // TODO Check GenericArrayType - String message = "Cannot create property=home for JavaBean=org.yaml.snakeyaml.generics.GenericArrayTypeTest$GenericArray"; - assertTrue(e.getMessage(), e.getMessage().contains(message)); - } - } - } + public void testClasses() throws IntrospectionException { + GenericArray ga = new GenericArray(); + Yaml yaml = new Yaml(); + String doc = yaml.dump(ga); + // System.out.println(doc); + String etalon = "!!org.yaml.snakeyaml.generics.GenericArrayTypeTest$GenericArray\n" + + "home: [1, 2, 3]\n" + "name: Array3\n"; + assertEquals(etalon, doc); + GenericArray parsed = yaml.load(doc); + assertEquals("Array3", parsed.getName()); + assertEquals(3, parsed.getHome().length); + } - public static class GenericArray extends AbstractAnimal<Integer[]> { - private Integer[] home; + public static class GenericArray extends AbstractAnimal<Integer[]> { - public GenericArray() { - home = new Integer[3]; - for (int i = 0; i < home.length; i++) { - home[i] = i + 1; - } - setName("Array" + String.valueOf(3)); - } + private Integer[] home; - @Override - public Integer[] getHome() { - return home; - } + public GenericArray() { + home = new Integer[3]; + for (int i = 0; i < home.length; i++) { + home[i] = i + 1; + } + setName("Array" + 3); + } - @Override - public void setHome(Integer[] home) { - this.home = home; - } + @Override + public Integer[] getHome() { + return home; } - public void testJavaBean() throws IntrospectionException { - GenericArray ga = new GenericArray(); - ArrayBean bean = new ArrayBean(); - bean.setId("ID556677"); - bean.setGa(ga); - Yaml dumper = new Yaml(); - String doc = dumper.dumpAsMap(bean); - // System.out.println(doc); - assertEquals(Util.getLocalResource("javabeans/genericArray-1.yaml"), doc); - // - Yaml beanLoader = new Yaml(); - if (GenericsBugDetector.isProperIntrospection()) { - ArrayBean loaded = beanLoader.loadAs(doc, ArrayBean.class); - assertEquals("ID556677", loaded.getId()); - assertEquals("Array3", loaded.getGa().getName()); - assertEquals(3, loaded.getGa().getHome().length); - } else { - try { - beanLoader.load(doc); - } catch (Exception e) { - // TODO Check GenericArrayType - String message = "Cannot create property=home for JavaBean=org.yaml.snakeyaml.generics.GenericArrayTypeTest$GenericArray"; - assertTrue(e.getMessage(), e.getMessage().contains(message)); - } - } + @Override + public void setHome(Integer[] home) { + this.home = home; } + } - public static class ArrayBean { - private String id; - private GenericArray ga; + public void testJavaBean() throws IntrospectionException { + GenericArray ga = new GenericArray(); + ArrayBean bean = new ArrayBean(); + bean.setId("ID556677"); + bean.setGa(ga); + Yaml dumper = new Yaml(); + String doc = dumper.dumpAsMap(bean); + // System.out.println(doc); + assertEquals(Util.getLocalResource("javabeans/genericArray-1.yaml"), doc); + // + Yaml beanLoader = new Yaml(); + ArrayBean loaded = beanLoader.loadAs(doc, ArrayBean.class); + assertEquals("ID556677", loaded.getId()); + assertEquals("Array3", loaded.getGa().getName()); + assertEquals(3, loaded.getGa().getHome().length); + } - public String getId() { - return id; - } + public static class ArrayBean { - public void setId(String id) { - this.id = id; - } + private String id; + private GenericArray ga; - public GenericArray getGa() { - return ga; - } + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public GenericArray getGa() { + return ga; + } - public void setGa(GenericArray ga) { - this.ga = ga; - } + public void setGa(GenericArray ga) { + this.ga = ga; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/generics/Nest.java b/src/test/java/org/yaml/snakeyaml/generics/Nest.java index fbf8dbf5..982df9c8 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/Nest.java +++ b/src/test/java/org/yaml/snakeyaml/generics/Nest.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; public class Nest { - private int height; - public int getHeight() { - return height; - } + private int height; - public void setHeight(int height) { - this.height = height; - } + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } } diff --git a/src/test/java/org/yaml/snakeyaml/generics/ObjectValues.java b/src/test/java/org/yaml/snakeyaml/generics/ObjectValues.java index a3219105..85770483 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/ObjectValues.java +++ b/src/test/java/org/yaml/snakeyaml/generics/ObjectValues.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; @@ -19,31 +17,31 @@ import java.util.Map; public class ObjectValues { - private Object object; - private Map<String, Map<Integer, Object>> values; - private String[] possible; + private Object object; + private Map<String, Map<Integer, Object>> values; + private String[] possible; - public Object getObject() { - return object; - } + public Object getObject() { + return object; + } - public void setObject(Object object) { - this.object = object; - } + public void setObject(Object object) { + this.object = object; + } - public void setValues(Map<String, Map<Integer, Object>> values) { - this.values = values; - } + public void setValues(Map<String, Map<Integer, Object>> values) { + this.values = values; + } - public Map<String, Map<Integer, Object>> getValues() { - return values; - } + public Map<String, Map<Integer, Object>> getValues() { + return values; + } - public void setPossible(String[] possible) { - this.possible = possible; - } + public void setPossible(String[] possible) { + this.possible = possible; + } - public String[] getPossible() { - return possible; - } + public String[] getPossible() { + return possible; + } } diff --git a/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesTest.java b/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesTest.java index 233a03d5..613a5bd3 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesTest.java +++ b/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; @@ -19,76 +17,80 @@ import static org.junit.Assert.assertArrayEquals; import java.util.HashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class ObjectValuesTest extends TestCase { - public void testObjectValues() { - ObjectValues ov = new ObjectValues(); - Integer obj = new Integer(131313); - ov.setObject(obj); - final Map<String, Map<Integer, Object>> prop2values = new HashMap<String, Map<Integer, Object>>(); + public void testObjectValues() { + ObjectValues ov = new ObjectValues(); + Integer obj = Integer.valueOf(131313); + ov.setObject(obj); + final Map<String, Map<Integer, Object>> prop2values = + new HashMap<String, Map<Integer, Object>>(); - final String[] props = { "prop1", "prop2", "prop3" }; - for (String name : props) { - Map<Integer, Object> values = new HashMap<Integer, Object>(); - prop2values.put(name, values); - for (int i = 0; i < 3; i++) { - values.put(i, name + i); - } - } + final String[] props = {"prop1", "prop2", "prop3"}; + for (String name : props) { + Map<Integer, Object> values = new HashMap<Integer, Object>(); + prop2values.put(name, values); + for (int i = 0; i < 3; i++) { + values.put(i, name + i); + } + } - ov.setValues(prop2values); - ov.setPossible(props); + ov.setValues(prop2values); + ov.setPossible(props); - Yaml dumper = new Yaml(); - String dumpedStr = dumper.dumpAsMap(ov); - Yaml loader = new Yaml(); - ObjectValues ov2 = loader.loadAs(dumpedStr, ObjectValues.class); + Yaml dumper = new Yaml(); + String dumpedStr = dumper.dumpAsMap(ov); + Yaml loader = new Yaml(); + ObjectValues ov2 = loader.loadAs(dumpedStr, ObjectValues.class); - assertEquals(ov.getObject(), ov2.getObject()); - assertEquals(ov.getValues(), ov2.getValues()); - assertArrayEquals(ov.getPossible(), ov2.getPossible()); - ov.getPossible()[0] = ov2.getPossible()[0]; - } + assertEquals(ov.getObject(), ov2.getObject()); + assertEquals(ov.getValues(), ov2.getValues()); + assertArrayEquals(ov.getPossible(), ov2.getPossible()); + ov.getPossible()[0] = ov2.getPossible()[0]; + } - @SuppressWarnings("unchecked") - public void testObjectValuesWithParam() { - ObjectValuesWithParam<String, Integer> ov = new ObjectValuesWithParam<String, Integer>(); - Integer obj = new Integer(131313); - ov.setObject(obj); - final Map<String, Map<Integer, Object>> prop2values = new HashMap<String, Map<Integer, Object>>(); + @SuppressWarnings("unchecked") + public void testObjectValuesWithParam() { + ObjectValuesWithParam<String, Integer> ov = new ObjectValuesWithParam<String, Integer>(); + Integer obj = Integer.valueOf(131313); + ov.setObject(obj); + final Map<String, Map<Integer, Object>> prop2values = + new HashMap<String, Map<Integer, Object>>(); - final String[] props = { "prop1", "prop2", "prop3" }; - for (String name : props) { - Map<Integer, Object> values = new HashMap<Integer, Object>(); - prop2values.put(name, values); - for (int i = 0; i < 3; i++) { - values.put(i, name + i); - } - } + final String[] props = {"prop1", "prop2", "prop3"}; + for (String name : props) { + Map<Integer, Object> values = new HashMap<Integer, Object>(); + prop2values.put(name, values); + for (int i = 0; i < 3; i++) { + values.put(i, name + i); + } + } - ov.setValues(prop2values); - ov.setPossible(props); + ov.setValues(prop2values); + ov.setPossible(props); - Yaml dumper = new Yaml(); - String dumpedStr = dumper.dumpAsMap(ov); - Yaml loader = new Yaml(); - ObjectValuesWithParam<String, Integer> ov2 = loader.loadAs(dumpedStr, - new ObjectValuesWithParam<String, Integer>().getClass()); + Yaml dumper = new Yaml(); + String dumpedStr = dumper.dumpAsMap(ov); + Yaml loader = new Yaml(); + ObjectValuesWithParam<String, Integer> ov2 = + loader.loadAs(dumpedStr, new ObjectValuesWithParam<String, Integer>().getClass()); - assertEquals(ov.getObject(), ov2.getObject()); - assertEquals(ov.getValues(), ov2.getValues()); - assertArrayEquals(ov.getPossible(), ov2.getPossible()); - // TODO: This actually FAILS. Use of GenericArrays is ..... no words. - // assertEquals(ov.getPossible()[0], ov2.getPossible()[0]); - try { - ov2.getPossible()[0].toString(); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().startsWith("[Ljava.lang.Object")); - } + assertEquals(ov.getObject(), ov2.getObject()); + assertEquals(ov.getValues(), ov2.getValues()); + assertArrayEquals(ov.getPossible(), ov2.getPossible()); + // This actually FAILS. Use of GenericArrays is ..... no words. + // assertEquals(ov.getPossible()[0], ov2.getPossible()[0]); + try { + ov2.getPossible(); + } catch (Exception e) { + boolean java8 = e.getMessage().startsWith("[Ljava.lang.Object"); + boolean java9 = e.getMessage().startsWith("java.base/[Ljava.lang.Object"); + boolean java11 = e.getMessage() + .startsWith("class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String;"); + assertTrue(e.getMessage(), java8 || java9 || java11); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesWithParam.java b/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesWithParam.java index 51c4485b..01b9fcd3 100644 --- a/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesWithParam.java +++ b/src/test/java/org/yaml/snakeyaml/generics/ObjectValuesWithParam.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.generics; @@ -19,31 +17,31 @@ import java.util.Map; public class ObjectValuesWithParam<T, S> { - private Object object; - private Map<T, Map<S, Object>> values; - private T[] possible; + private Object object; + private Map<T, Map<S, Object>> values; + private T[] possible; - public Object getObject() { - return object; - } + public Object getObject() { + return object; + } - public void setObject(Object object) { - this.object = object; - } + public void setObject(Object object) { + this.object = object; + } - public void setValues(Map<T, Map<S, Object>> values) { - this.values = values; - } + public void setValues(Map<T, Map<S, Object>> values) { + this.values = values; + } - public Map<T, Map<S, Object>> getValues() { - return values; - } + public Map<T, Map<S, Object>> getValues() { + return values; + } - public void setPossible(T[] possible) { - this.possible = possible; - } + public void setPossible(T[] possible) { + this.possible = possible; + } - public T[] getPossible() { - return possible; - } + public T[] getPossible() { + return possible; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Animal.java b/src/test/java/org/yaml/snakeyaml/immutable/Animal.java index f7dcb73a..0828bfee 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Animal.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Animal.java @@ -1,20 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public interface Animal { - public String getName(); + + String getName(); } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Code.java b/src/test/java/org/yaml/snakeyaml/immutable/Code.java index 3ef1de47..c29ed1ce 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Code.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Code.java @@ -1,48 +1,47 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class Code { - private final Integer code; - public Code(Integer name) { - this.code = name; - } + private final Integer code; - public Integer getCode() { - return code; - } + public Code(Integer name) { + this.code = name; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Code) { - Code code = (Code) obj; - return code.equals(code.code); - } else { - return false; - } - } + public Integer getCode() { + return code; + } - @Override - public int hashCode() { - return code.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Code) { + Code code = (Code) obj; + return code.equals(code.code); + } else { + return false; } + } - @Override - public String toString() { - return "<Code code=" + code + ">"; - } + @Override + public int hashCode() { + return code.hashCode(); + } + + @Override + public String toString() { + return "<Code code=" + code + ">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Code2.java b/src/test/java/org/yaml/snakeyaml/immutable/Code2.java index 02fc2e9b..4cae9674 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Code2.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Code2.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; @@ -19,37 +17,38 @@ package org.yaml.snakeyaml.immutable; * Two constructors with 1 argument. These immutable objects are not supported. */ public class Code2 { - private final Integer code; - public Code2(Integer name) { - this.code = name; - } + private final Integer code; - public Code2(String name) { - this.code = new Integer(name); - } + public Code2(Integer name) { + this.code = name; + } - public Integer getCode() { - return code; - } + public Code2(String name) { + this.code = Integer.valueOf(name); + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Code2) { - Code2 code = (Code2) obj; - return code.equals(code.code); - } else { - return false; - } - } + public Integer getCode() { + return code; + } - @Override - public int hashCode() { - return code.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Code2) { + Code2 code = (Code2) obj; + return code.equals(code.code); + } else { + return false; } + } - @Override - public String toString() { - return "<Code2 code=" + code + ">"; - } + @Override + public int hashCode() { + return code.hashCode(); + } + + @Override + public String toString() { + return "<Code2 code=" + code + ">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Code3.java b/src/test/java/org/yaml/snakeyaml/immutable/Code3.java index 26385322..88b12eca 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Code3.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Code3.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; @@ -19,35 +17,36 @@ package org.yaml.snakeyaml.immutable; * No constructors with 1 argument. These immutable objects are not supported. */ public class Code3 { - private final String name; - private final Integer code; - public Code3(String name, Integer code) { - this.code = code; - this.name = name; - } + private final String name; + private final Integer code; - public String getData() { - return name + code; - } + public Code3(String name, Integer code) { + this.code = code; + this.name = name; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Code3) { - Code3 code = (Code3) obj; - return code.equals(code.code); - } else { - return false; - } - } + public String getData() { + return name + code; + } - @Override - public int hashCode() { - return code.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Code3) { + Code3 code = (Code3) obj; + return code.equals(code.code); + } else { + return false; } + } - @Override - public String toString() { - return "<Code3 data=" + getData() + ">"; - } + @Override + public int hashCode() { + return code.hashCode(); + } + + @Override + public String toString() { + return "<Code3 data=" + getData() + ">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Code4.java b/src/test/java/org/yaml/snakeyaml/immutable/Code4.java index 71c6828e..c2ffa0a3 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Code4.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Code4.java @@ -1,56 +1,54 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; /** - * Two constructors with 1 argument. None of them has String as the argument - * class. + * Two constructors with 1 argument. None of them has String as the argument class. */ public class Code4 { - private final Integer code; - public Code4(Integer name) { - this.code = name; - } + private final Integer code; - public Code4(Double name) { - this.code = new Integer(name.intValue()); - } + public Code4(Integer name) { + this.code = name; + } - public Integer getCode() { - return code; - } + public Code4(Double name) { + this.code = Integer.valueOf(name.intValue()); + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Code4) { - Code4 code = (Code4) obj; - return code.equals(code.code); - } else { - return false; - } - } + public Integer getCode() { + return code; + } - @Override - public int hashCode() { - return code.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Code4) { + Code4 code = (Code4) obj; + return code.equals(code.code); + } else { + return false; } + } - @Override - public String toString() { - return "<Code4 code=" + code + ">"; - } + @Override + public int hashCode() { + return code.hashCode(); + } + + @Override + public String toString() { + return "<Code4 code=" + code + ">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Color.java b/src/test/java/org/yaml/snakeyaml/immutable/Color.java index 2ac105a8..ee77b0c9 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Color.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Color.java @@ -1,48 +1,47 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class Color { - private final String name; - public Color(String name) { - this.name = name; - } + private final String name; - public String getName() { - return name; - } + public Color(String name) { + this.name = name; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Color) { - Color color = (Color) obj; - return name.equals(color.name); - } else { - return false; - } - } + public String getName() { + return name; + } - @Override - public int hashCode() { - return name.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Color) { + Color color = (Color) obj; + return name.equals(color.name); + } else { + return false; } + } - @Override - public String toString() { - return "<Color id=" + name + ">"; - } + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public String toString() { + return "<Color id=" + name + ">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Dog.java b/src/test/java/org/yaml/snakeyaml/immutable/Dog.java index 710aab3d..624e83a0 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Dog.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Dog.java @@ -1,33 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class Dog implements Animal { - private String name; - public Dog(String name) { - super(); - this.name = name; - } + private final String name; - public String getName() { - return name; - } + public Dog(String name) { + super(); + this.name = name; + } - public void bark() { - System.out.println("I am a " + name); - } + public String getName() { + return name; + } + + public void bark() { + System.out.println("I am a " + name); + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/DogImmutableTest.java b/src/test/java/org/yaml/snakeyaml/immutable/DogImmutableTest.java index 90b1ff64..d5a19e89 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/DogImmutableTest.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/DogImmutableTest.java @@ -1,36 +1,33 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class DogImmutableTest extends TestCase { - public void testDog() { - Yaml yaml = new Yaml(); - Dog loaded = (Dog) yaml.load("!!org.yaml.snakeyaml.immutable.Dog Bulldog"); - assertEquals("Bulldog", loaded.getName()); - } + public void testDog() { + Yaml yaml = new Yaml(); + Dog loaded = yaml.load("!!org.yaml.snakeyaml.immutable.Dog Bulldog"); + assertEquals("Bulldog", loaded.getName()); + } - public void testHouse() { - Yaml yaml = new Yaml(); - HouseBean loaded = (HouseBean) yaml - .load("!!org.yaml.snakeyaml.immutable.HouseBean\nanimal: !!org.yaml.snakeyaml.immutable.Dog Bulldog"); - assertEquals("Bulldog", loaded.getAnimal().getName()); - } + public void testHouse() { + Yaml yaml = new Yaml(); + HouseBean loaded = yaml.load( + "!!org.yaml.snakeyaml.immutable.HouseBean\nanimal: !!org.yaml.snakeyaml.immutable.Dog Bulldog"); + assertEquals("Bulldog", loaded.getAnimal().getName()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/HouseBean.java b/src/test/java/org/yaml/snakeyaml/immutable/HouseBean.java index edee6b1b..e9fcd5e9 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/HouseBean.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/HouseBean.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class HouseBean { - private String name; - private Animal animal; - public String getName() { - return name; - } + private String name; + private Animal animal; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public Animal getAnimal() { - return animal; - } + public void setName(String name) { + this.name = name; + } - public void setAnimal(Animal animal) { - this.animal = animal; - } + public Animal getAnimal() { + return animal; + } + + public void setAnimal(Animal animal) { + this.animal = animal; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/ImmutablesRepresenter.java b/src/test/java/org/yaml/snakeyaml/immutable/ImmutablesRepresenter.java index 0595731b..0c7d2d12 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/ImmutablesRepresenter.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/ImmutablesRepresenter.java @@ -1,26 +1,23 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; import java.awt.Insets; import java.awt.Rectangle; import java.util.Arrays; - import javax.swing.border.MatteBorder; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; @@ -28,55 +25,53 @@ import org.yaml.snakeyaml.representer.Representer; public class ImmutablesRepresenter extends Representer { - public ImmutablesRepresenter() { - super(); - this.representers.put(java.awt.Color.class, new RepresentColor()); - this.representers.put(Insets.class, new RepresentInsets()); - this.representers.put(MatteBorder.class, new RepresentMatteBorder()); - this.representers.put(Rectangle.class, new RepresentRectangle()); + public ImmutablesRepresenter() { + super(); + this.representers.put(java.awt.Color.class, new RepresentColor()); + this.representers.put(Insets.class, new RepresentInsets()); + this.representers.put(MatteBorder.class, new RepresentMatteBorder()); + this.representers.put(Rectangle.class, new RepresentRectangle()); + } + + class RepresentInsets implements Represent { + + public Node representData(Object data) { + Insets insets = (Insets) data; + return representSequence(getTag(data.getClass(), new Tag(data.getClass())), + Arrays.asList(insets.top, insets.left, insets.bottom, insets.right), + DumperOptions.FlowStyle.FLOW); } - class RepresentInsets implements Represent { + } - public Node representData(Object data) { - Insets insets = (Insets) data; - return representSequence( - getTag(data.getClass(), new Tag(data.getClass())), - Arrays.asList(new Object[] { insets.top, insets.left, insets.bottom, - insets.right }), true); - } + class RepresentRectangle implements Represent { + public Node representData(Object data) { + Rectangle rect = (Rectangle) data; + return representSequence(getTag(data.getClass(), new Tag(data.getClass())), + Arrays.asList(rect.x, rect.y, rect.width, rect.height), DumperOptions.FlowStyle.FLOW); } - class RepresentRectangle implements Represent { + } - public Node representData(Object data) { - Rectangle rect = (Rectangle) data; - return representSequence(getTag(data.getClass(), new Tag(data.getClass())), - Arrays.asList(new Object[] { rect.x, rect.y, rect.width, rect.height }), true); - } + class RepresentMatteBorder implements Represent { + public Node representData(Object data) { + MatteBorder mb = (MatteBorder) data; + return representSequence(getTag(data.getClass(), new Tag(data.getClass())), + Arrays.asList(mb.getBorderInsets(), mb.getMatteColor()), DumperOptions.FlowStyle.FLOW); } - class RepresentMatteBorder implements Represent { + } - public Node representData(Object data) { - MatteBorder mb = (MatteBorder) data; - return representSequence(getTag(data.getClass(), new Tag(data.getClass())), - Arrays.asList(new Object[] { mb.getBorderInsets(), mb.getMatteColor() }), true); - } + class RepresentColor implements Represent { + public Node representData(Object data) { + java.awt.Color color = (java.awt.Color) data; + return representSequence(getTag(data.getClass(), new Tag(data.getClass())), + Arrays.asList(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()), + DumperOptions.FlowStyle.FLOW); } - class RepresentColor implements Represent { - - public Node representData(Object data) { - java.awt.Color color = (java.awt.Color) data; - return representSequence( - getTag(data.getClass(), new Tag(data.getClass())), - Arrays.asList(new Integer[] { color.getRed(), color.getGreen(), - color.getBlue(), color.getAlpha() }), true); - } - - } + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/MoreImmutablesTest.java b/src/test/java/org/yaml/snakeyaml/immutable/MoreImmutablesTest.java index b96b37a5..87a1bb1f 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/MoreImmutablesTest.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/MoreImmutablesTest.java @@ -1,78 +1,73 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; import java.awt.Color; import java.awt.Insets; import java.awt.Rectangle; - import javax.swing.BorderFactory; import javax.swing.border.MatteBorder; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class MoreImmutablesTest extends TestCase { - public void testInsets() { - Yaml yaml = new Yaml(new ImmutablesRepresenter()); - Insets insets = new Insets(10, 20, 30, 40); - String dump = yaml.dump(insets); - assertEquals("!!java.awt.Insets [10, 20, 30, 40]\n", dump); - Object loaded = yaml.load(dump); - assertEquals(insets, loaded); - } + public void testInsets() { + Yaml yaml = new Yaml(new ImmutablesRepresenter()); + Insets insets = new Insets(10, 20, 30, 40); + String dump = yaml.dump(insets); + assertEquals("!!java.awt.Insets [10, 20, 30, 40]\n", dump); + Object loaded = yaml.load(dump); + assertEquals(insets, loaded); + } - public void testAwtColor() { - Yaml yaml = new Yaml(new ImmutablesRepresenter()); - Color color = new Color(10, 20, 30, 40); - String dump = yaml.dump(color); - assertEquals("!!java.awt.Color [10, 20, 30, 40]\n", dump); - Object loaded = yaml.load(dump); - assertEquals(color, loaded); - } + public void testAwtColor() { + Yaml yaml = new Yaml(new ImmutablesRepresenter()); + Color color = new Color(10, 20, 30, 40); + String dump = yaml.dump(color); + assertEquals("!!java.awt.Color [10, 20, 30, 40]\n", dump); + Object loaded = yaml.load(dump); + assertEquals(color, loaded); + } - public void testRectangle() { - Yaml yaml = new Yaml(new ImmutablesRepresenter()); - Rectangle rect = new Rectangle(10, 20, 30, 40); - String dump = yaml.dump(rect); - assertEquals("!!java.awt.Rectangle [10, 20, 30, 40]\n", dump); - Object loaded = yaml.load(dump); - assertEquals(rect, loaded); - } + public void testRectangle() { + Yaml yaml = new Yaml(new ImmutablesRepresenter()); + Rectangle rect = new Rectangle(10, 20, 30, 40); + String dump = yaml.dump(rect); + assertEquals("!!java.awt.Rectangle [10, 20, 30, 40]\n", dump); + Object loaded = yaml.load(dump); + assertEquals(rect, loaded); + } - // matteborder - only with color - no icon - public void testMatteBorder() { - DumperOptions options = new DumperOptions(); - options.setWidth(400); - Yaml yaml = new Yaml(new ImmutablesRepresenter(), options); - Insets insets = new Insets(10, 20, 30, 40); - Color color = new Color(100, 150, 200); - MatteBorder border = BorderFactory.createMatteBorder(insets.top, insets.left, - insets.bottom, insets.right, color); - String dump = yaml.dump(border); - assertEquals( - "!!javax.swing.border.MatteBorder [!!java.awt.Insets [10, 20, 30, 40], !!java.awt.Color [100, 150, 200, 255]]\n", - dump); - Object loaded = yaml.load(dump); - assertTrue(loaded instanceof MatteBorder); - MatteBorder loadedBorder = (MatteBorder) loaded; - assertEquals(insets, loadedBorder.getBorderInsets()); - assertEquals(color, loadedBorder.getMatteColor()); - } + // matteborder - only with color - no icon + public void testMatteBorder() { + DumperOptions options = new DumperOptions(); + options.setWidth(400); + Yaml yaml = new Yaml(new ImmutablesRepresenter(), options); + Insets insets = new Insets(10, 20, 30, 40); + Color color = new Color(100, 150, 200); + MatteBorder border = BorderFactory.createMatteBorder(insets.top, insets.left, insets.bottom, + insets.right, color); + String dump = yaml.dump(border); + assertEquals( + "!!javax.swing.border.MatteBorder [!!java.awt.Insets [10, 20, 30, 40], !!java.awt.Color [100, 150, 200, 255]]\n", + dump); + Object loaded = yaml.load(dump); + assertTrue(loaded instanceof MatteBorder); + MatteBorder loadedBorder = (MatteBorder) loaded; + assertEquals(insets, loadedBorder.getBorderInsets()); + assertEquals(color, loadedBorder.getMatteColor()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Point.java b/src/test/java/org/yaml/snakeyaml/immutable/Point.java index 98312dac..d005529e 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Point.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Point.java @@ -1,53 +1,52 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class Point { - private final double x; - private final double y; - public double getX() { - return x; - } + private final double x; + private final double y; - public double getY() { - return y; - } + public double getX() { + return x; + } - public Point(Double x, Double y) { - this.x = x; - this.y = y; - } + public double getY() { + return y; + } - @Override - public String toString() { - return "<Point x=" + String.valueOf(x) + " y=" + String.valueOf(y) + ">"; - } + public Point(Double x, Double y) { + this.x = x; + this.y = y; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Point) { - return toString().equals(obj.toString()); - } else { - return false; - } - } + @Override + public String toString() { + return "<Point x=" + x + " y=" + y + ">"; + } - @Override - public int hashCode() { - return toString().hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Point) { + return toString().equals(obj.toString()); + } else { + return false; } + } + + @Override + public int hashCode() { + return toString().hashCode(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Point2.java b/src/test/java/org/yaml/snakeyaml/immutable/Point2.java index 89d1c854..a9a70075 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Point2.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Point2.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; @@ -19,29 +17,30 @@ package org.yaml.snakeyaml.immutable; * Two public constructor with 2 argument are present */ public class Point2 { - private final Integer x; - private final Integer y; - public Integer getX() { - return x; - } + private final Integer x; + private final Integer y; - public Integer getY() { - return y; - } + public Integer getX() { + return x; + } - public Point2(Double x, Double y) { - this.x = x.intValue(); - this.y = y.intValue(); - } + public Integer getY() { + return y; + } - public Point2(Integer x, Integer y) { - this.x = x; - this.y = y; - } + public Point2(Double x, Double y) { + this.x = x.intValue(); + this.y = y.intValue(); + } - @Override - public String toString() { - return "<Point2 x=" + String.valueOf(x) + " y=" + String.valueOf(y) + ">"; - } + public Point2(Integer x, Integer y) { + this.x = x; + this.y = y; + } + + @Override + public String toString() { + return "<Point2 x=" + x + " y=" + y + ">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Point3d.java b/src/test/java/org/yaml/snakeyaml/immutable/Point3d.java index 333de040..e9609f14 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Point3d.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Point3d.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class Point3d { - private final double z; - private final Point point; - public Point3d(Point point, Double z) { - this.point = point; - this.z = z; - } + private final double z; + private final Point point; - public double getZ() { - return z; - } + public Point3d(Point point, Double z) { + this.point = point; + this.z = z; + } - public Point getPoint() { - return point; - } + public double getZ() { + return z; + } - @Override - public String toString() { - return "<Point3d point=" + point.toString() + " z=" + String.valueOf(z) + ">"; - } + public Point getPoint() { + return point; + } + + @Override + public String toString() { + return "<Point3d point=" + point.toString() + " z=" + z + ">"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/Shape.java b/src/test/java/org/yaml/snakeyaml/immutable/Shape.java index b1f0b412..56f8cca7 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/Shape.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/Shape.java @@ -1,55 +1,54 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class Shape { - private Color color; - private Point point; - private Point3d point3d; - private Integer id; - - public Point3d getPoint3d() { - return point3d; - } - - public void setPoint3d(Point3d point3d) { - this.point3d = point3d; - } - - public void setColor(Color color) { - this.color = color; - } - - public void setPoint(Point point) { - this.point = point; - } - - public void setId(Integer id) { - this.id = id; - } - - public Color getColor() { - return color; - } - - public Point getPoint() { - return point; - } - - public Integer getId() { - return id; - } + + private Color color; + private Point point; + private Point3d point3d; + private Integer id; + + public Point3d getPoint3d() { + return point3d; + } + + public void setPoint3d(Point3d point3d) { + this.point3d = point3d; + } + + public void setColor(Color color) { + this.color = color; + } + + public void setPoint(Point point) { + this.point = point; + } + + public void setId(Integer id) { + this.id = id; + } + + public Color getColor() { + return color; + } + + public Point getPoint() { + return point; + } + + public Integer getId() { + return id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/ShapeImmutableTest.java b/src/test/java/org/yaml/snakeyaml/immutable/ShapeImmutableTest.java index 4d8f4549..971509eb 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/ShapeImmutableTest.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/ShapeImmutableTest.java @@ -1,151 +1,144 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class ShapeImmutableTest extends TestCase { - public void testColor() { - Yaml yaml = new Yaml(); - Color loaded = (Color) yaml.load("!!org.yaml.snakeyaml.immutable.Color BLACK"); - assertEquals("BLACK", loaded.getName()); - } - - public void testCode() { - Yaml yaml = new Yaml(); - Code loaded = (Code) yaml.load("!!org.yaml.snakeyaml.immutable.Code 123"); - assertEquals(new Integer(123), loaded.getCode()); - } - - public void testSuperColor() { - Yaml yaml = new Yaml(); - SuperColor superColor = (SuperColor) yaml - .load("!!org.yaml.snakeyaml.immutable.SuperColor [!!org.yaml.snakeyaml.immutable.Color BLACK]"); - assertEquals("BLACK", superColor.getColor().getName()); - } - - public void testSuperColorFail() { - Yaml yaml = new Yaml(); - try { - yaml.load("!!org.yaml.snakeyaml.immutable.SuperColor BLACK"); - fail("SuperColor requires Color and not a String."); - } catch (Exception e) { - assertTrue(e - .getMessage() - .startsWith( - "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.SuperColor; exception=Unsupported class: class org.yaml.snakeyaml.immutable.Color")); - } - } - - public void testCode2() { - Yaml yaml = new Yaml(); - Code2 code2 = (Code2) yaml.load("!!org.yaml.snakeyaml.immutable.Code2 555"); - assertEquals(new Integer(555), code2.getCode()); - } - - public void testCode3() { - Yaml yaml = new Yaml(); - try { - yaml.load("!!org.yaml.snakeyaml.immutable.Code3 777"); - fail("There must be 1 constructor with 1 argument for scalar."); - } catch (Exception e) { - assertTrue(e - .getMessage() - .startsWith( - "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Code3; exception=No single argument constructor found for class org.yaml.snakeyaml.immutable.Code3")); - } - } - - public void testCode4() { - Yaml yaml = new Yaml(); - try { - yaml.load("!!org.yaml.snakeyaml.immutable.Code4 777"); - fail("Constructor with String is required."); - } catch (Exception e) { - assertEquals( - "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Code4; exception=Can't construct a java object for scalar tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Code4; No String constructor found. Exception=org.yaml.snakeyaml.immutable.Code4.<init>(java.lang.String)\n" - + " in 'string', line 1, column 1:\n" - + " !!org.yaml.snakeyaml.immutable.C ... \n" + " ^\n", - e.getMessage()); - } - } - - public void testPoint() { - Yaml yaml = new Yaml(); - Point loaded = (Point) yaml.load("!!org.yaml.snakeyaml.immutable.Point [1.17, 3.14]"); - assertEquals(1.17, loaded.getX()); - assertEquals(3.14, loaded.getY()); - } - - public void testPointBlock() { - Yaml yaml = new Yaml(); - Point loaded = (Point) yaml.load("!!org.yaml.snakeyaml.immutable.Point\n- 1.17\n- 3.14"); - assertEquals(1.17, loaded.getX()); - assertEquals(3.14, loaded.getY()); - } - - public void testPointOnlyOneArgument() { - Yaml yaml = new Yaml(); - try { - yaml.load("!!org.yaml.snakeyaml.immutable.Point\n- 1.17"); - fail("Two arguments required."); - } catch (Exception e) { - assertEquals( - "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Point; exception=No suitable constructor with 1 arguments found for class org.yaml.snakeyaml.immutable.Point\n" - + " in 'string', line 1, column 1:\n" - + " !!org.yaml.snakeyaml.immutable.Point\n" + " ^\n", - e.getMessage()); - } - } - - public void testPoint2() { - Yaml yaml = new Yaml(); - Point2 loaded = (Point2) yaml.load("!!org.yaml.snakeyaml.immutable.Point2\n- 1\n- 3"); - assertEquals(new Integer(1), loaded.getX()); - assertEquals(new Integer(3), loaded.getY()); + public void testColor() { + Yaml yaml = new Yaml(); + Color loaded = yaml.load("!!org.yaml.snakeyaml.immutable.Color BLACK"); + assertEquals("BLACK", loaded.getName()); + } + + public void testCode() { + Yaml yaml = new Yaml(); + Code loaded = yaml.load("!!org.yaml.snakeyaml.immutable.Code 123"); + assertEquals(Integer.valueOf(123), loaded.getCode()); + } + + public void testSuperColor() { + Yaml yaml = new Yaml(); + SuperColor superColor = yaml.load( + "!!org.yaml.snakeyaml.immutable.SuperColor [!!org.yaml.snakeyaml.immutable.Color BLACK]"); + assertEquals("BLACK", superColor.getColor().getName()); + } + + public void testSuperColorFail() { + Yaml yaml = new Yaml(); + try { + yaml.load("!!org.yaml.snakeyaml.immutable.SuperColor BLACK"); + fail("SuperColor requires Color and not a String."); + } catch (Exception e) { + assertTrue(e.getMessage().startsWith( + "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.SuperColor; exception=Unsupported class: class org.yaml.snakeyaml.immutable.Color")); } - - public void testPoint3d() { - Yaml yaml = new Yaml(); - Point3d loaded = (Point3d) yaml - .load("!!org.yaml.snakeyaml.immutable.Point3d [!!org.yaml.snakeyaml.immutable.Point [1.17, 3.14], 345.1]"); - assertEquals(345.1, loaded.getZ()); + } + + public void testCode2() { + Yaml yaml = new Yaml(); + Code2 code2 = yaml.load("!!org.yaml.snakeyaml.immutable.Code2 555"); + assertEquals(Integer.valueOf(555), code2.getCode()); + } + + public void testCode3() { + Yaml yaml = new Yaml(); + try { + yaml.load("!!org.yaml.snakeyaml.immutable.Code3 777"); + fail("There must be 1 constructor with 1 argument for scalar."); + } catch (Exception e) { + assertTrue(e.getMessage().startsWith( + "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Code3; exception=No single argument constructor found for class org.yaml.snakeyaml.immutable.Code3")); } - - public void testShape() { - Yaml yaml = new Yaml(); - String source = Util.getLocalResource("immutable/shape1.yaml"); - Shape loaded = (Shape) yaml.load(source); - assertEquals(new Integer(123), loaded.getId()); + } + + public void testCode4() { + Yaml yaml = new Yaml(); + try { + yaml.load("!!org.yaml.snakeyaml.immutable.Code4 777"); + fail("Constructor with String is required."); + } catch (Exception e) { + assertEquals( + "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Code4; exception=Can't construct a java object for scalar tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Code4; No String constructor found. Exception=org.yaml.snakeyaml.immutable.Code4.<init>(java.lang.String)\n" + + " in 'string', line 1, column 1:\n" + " !!org.yaml.snakeyaml.immutable.C ... \n" + + " ^\n", + e.getMessage()); } - - public void testShapeNoTags() { - String source = Util.getLocalResource("immutable/shapeNoTags.yaml"); - Yaml beanLoader = new Yaml(); - Shape loaded = beanLoader.loadAs(source, Shape.class); - assertEquals(new Integer(123), loaded.getId()); - assertEquals("BLACK", loaded.getColor().getName()); - assertEquals(1.17, loaded.getPoint().getX()); - assertEquals(3.14, loaded.getPoint().getY()); - assertEquals(345.1, loaded.getPoint3d().getZ()); - assertEquals(1.96, loaded.getPoint3d().getPoint().getX()); - assertEquals(1.78, loaded.getPoint3d().getPoint().getY()); + } + + public void testPoint() { + Yaml yaml = new Yaml(); + Point loaded = yaml.load("!!org.yaml.snakeyaml.immutable.Point [1.17, 3.14]"); + assertEquals(1.17, loaded.getX()); + assertEquals(3.14, loaded.getY()); + } + + public void testPointBlock() { + Yaml yaml = new Yaml(); + Point loaded = yaml.load("!!org.yaml.snakeyaml.immutable.Point\n- 1.17\n- 3.14"); + assertEquals(1.17, loaded.getX()); + assertEquals(3.14, loaded.getY()); + } + + public void testPointOnlyOneArgument() { + Yaml yaml = new Yaml(); + try { + yaml.load("!!org.yaml.snakeyaml.immutable.Point\n- 1.17"); + fail("Two arguments required."); + } catch (Exception e) { + assertEquals( + "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.Point; exception=No suitable constructor with 1 arguments found for class org.yaml.snakeyaml.immutable.Point\n" + + " in 'string', line 1, column 1:\n" + " !!org.yaml.snakeyaml.immutable.Point\n" + + " ^\n", + e.getMessage()); } + } + + public void testPoint2() { + Yaml yaml = new Yaml(); + Point2 loaded = yaml.load("!!org.yaml.snakeyaml.immutable.Point2\n- 1\n- 3"); + assertEquals(Integer.valueOf(1), loaded.getX()); + assertEquals(Integer.valueOf(3), loaded.getY()); + } + + public void testPoint3d() { + Yaml yaml = new Yaml(); + Point3d loaded = yaml.load( + "!!org.yaml.snakeyaml.immutable.Point3d [!!org.yaml.snakeyaml.immutable.Point [1.17, 3.14], 345.1]"); + assertEquals(345.1, loaded.getZ()); + } + + public void testShape() { + Yaml yaml = new Yaml(); + String source = Util.getLocalResource("immutable/shape1.yaml"); + Shape loaded = yaml.load(source); + assertEquals(Integer.valueOf(123), loaded.getId()); + } + + public void testShapeNoTags() { + String source = Util.getLocalResource("immutable/shapeNoTags.yaml"); + Yaml beanLoader = new Yaml(); + Shape loaded = beanLoader.loadAs(source, Shape.class); + assertEquals(Integer.valueOf(123), loaded.getId()); + assertEquals("BLACK", loaded.getColor().getName()); + assertEquals(1.17, loaded.getPoint().getX()); + assertEquals(3.14, loaded.getPoint().getY()); + assertEquals(345.1, loaded.getPoint3d().getZ()); + assertEquals(1.96, loaded.getPoint3d().getPoint().getX()); + assertEquals(1.78, loaded.getPoint3d().getPoint().getY()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/SuperColor.java b/src/test/java/org/yaml/snakeyaml/immutable/SuperColor.java index 0a249628..43b01a3d 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/SuperColor.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/SuperColor.java @@ -1,52 +1,51 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable; public class SuperColor { - private final Color color; - public SuperColor(Color name) { - this.color = name; - } + private final Color color; - public Color getName() { - return color; - } + public SuperColor(Color name) { + this.color = name; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof SuperColor) { - SuperColor color = (SuperColor) obj; - return color.equals(color.color); - } else { - return false; - } - } + public Color getName() { + return color; + } - @Override - public int hashCode() { - return color.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof SuperColor) { + SuperColor color = (SuperColor) obj; + return color.equals(color.color); + } else { + return false; } + } - @Override - public String toString() { - return "SuperColor color=" + color; - } + @Override + public int hashCode() { + return color.hashCode(); + } - public Color getColor() { - return color; - } + @Override + public String toString() { + return "SuperColor color=" + color; + } + + public Color getColor() { + return color; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/primitives/BunchOfPrimitives.java b/src/test/java/org/yaml/snakeyaml/immutable/primitives/BunchOfPrimitives.java index 19008b47..2f826cd4 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/primitives/BunchOfPrimitives.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/primitives/BunchOfPrimitives.java @@ -1,67 +1,66 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable.primitives; public class BunchOfPrimitives { - private int primitiveInt; - private double primitiveDouble; - public boolean primitiveBoolean; - public BunchOfPrimitives(int primitiveInt, double primitiveDouble, boolean primitiveBoolean) { - this.primitiveInt = primitiveInt; - this.primitiveDouble = primitiveDouble; - this.primitiveBoolean = primitiveBoolean; - } + private final int primitiveInt; + private double primitiveDouble; + public boolean primitiveBoolean; - /** - * The number of parameters is the same but the type is different - */ - public BunchOfPrimitives(int i1, int i2, int i3) { - this.primitiveInt = i1; - } + public BunchOfPrimitives(int primitiveInt, double primitiveDouble, boolean primitiveBoolean) { + this.primitiveInt = primitiveInt; + this.primitiveDouble = primitiveDouble; + this.primitiveBoolean = primitiveBoolean; + } - public BunchOfPrimitives(long i1, double i2, boolean i3) { - this((int) i1, i2, i3); - } + /** + * The number of parameters is the same but the type is different + */ + public BunchOfPrimitives(int i1, int i2, int i3) { + this.primitiveInt = i1; + } - public int getPrimitiveInt() { - return primitiveInt; - } + public BunchOfPrimitives(long i1, double i2, boolean i3) { + this((int) i1, i2, i3); + } - public double getPrimitiveDouble() { - return primitiveDouble; - } + public int getPrimitiveInt() { + return primitiveInt; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof BunchOfPrimitives) { - BunchOfPrimitives bunch = (BunchOfPrimitives) obj; - return primitiveInt == bunch.primitiveInt; - } else { - return false; - } - } + public double getPrimitiveDouble() { + return primitiveDouble; + } - @Override - public int hashCode() { - return primitiveInt; + @Override + public boolean equals(Object obj) { + if (obj instanceof BunchOfPrimitives) { + BunchOfPrimitives bunch = (BunchOfPrimitives) obj; + return primitiveInt == bunch.primitiveInt; + } else { + return false; } + } - @Override - public String toString() { - return "BunchOfPrimitives " + primitiveInt; - } + @Override + public int hashCode() { + return primitiveInt; + } + + @Override + public String toString() { + return "BunchOfPrimitives " + primitiveInt; + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesRepresenter.java b/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesRepresenter.java index 36745dc0..6de67cd9 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesRepresenter.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesRepresenter.java @@ -1,40 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable.primitives; import java.util.Arrays; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; public class ImmutablePrimitivesRepresenter extends Representer { - public ImmutablePrimitivesRepresenter() { - super(); - this.representers.put(BunchOfPrimitives.class, new RepresentPrimitives()); - } - class RepresentPrimitives implements Represent { - public Node representData(Object data) { - BunchOfPrimitives bunch = (BunchOfPrimitives) data; - return representSequence( - getTag(data.getClass(), new Tag(data.getClass())), - Arrays.asList(new Object[] { bunch.getPrimitiveInt(), - bunch.getPrimitiveDouble(), bunch.primitiveBoolean }), true); - } + public ImmutablePrimitivesRepresenter() { + super(); + this.representers.put(BunchOfPrimitives.class, new RepresentPrimitives()); + } + + class RepresentPrimitives implements Represent { + + public Node representData(Object data) { + BunchOfPrimitives bunch = (BunchOfPrimitives) data; + return representSequence(getTag(data.getClass(), new Tag(data.getClass())), Arrays + .asList(bunch.getPrimitiveInt(), bunch.getPrimitiveDouble(), bunch.primitiveBoolean), + DumperOptions.FlowStyle.FLOW); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesTest.java b/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesTest.java index 801715b7..d50743f1 100644 --- a/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesTest.java +++ b/src/test/java/org/yaml/snakeyaml/immutable/primitives/ImmutablePrimitivesTest.java @@ -1,55 +1,51 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.immutable.primitives; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.YAMLException; public class ImmutablePrimitivesTest extends TestCase { - public void testPrimitives() { - Yaml yaml = new Yaml(new ImmutablePrimitivesRepresenter()); - BunchOfPrimitives bunch = new BunchOfPrimitives(10, 40.0, true); - String dump = yaml.dump(bunch); - assertEquals("!!" + bunch.getClass().getCanonicalName() + " [10, 40.0, true]\n", dump); - Object loaded = yaml.load(dump); - assertEquals(loaded.toString(), bunch, loaded); - } + public void testPrimitives() { + Yaml yaml = new Yaml(new ImmutablePrimitivesRepresenter()); + BunchOfPrimitives bunch = new BunchOfPrimitives(10, 40.0, true); + String dump = yaml.dump(bunch); + assertEquals("!!" + bunch.getClass().getCanonicalName() + " [10, 40.0, true]\n", dump); + Object loaded = yaml.load(dump); + assertEquals(loaded.toString(), bunch, loaded); + } - public void testPrimitivesLong() { - Yaml yaml = new Yaml(); - String dump = "!!org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives [10000000000, 40.0, true]"; - BunchOfPrimitives bunch = (BunchOfPrimitives) yaml.load(dump); - assertEquals("Must be truncated.", new Long(10000000000L).intValue(), - bunch.getPrimitiveInt()); - } + public void testPrimitivesLong() { + Yaml yaml = new Yaml(); + String dump = + "!!org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives [10000000000, 40.0, true]"; + BunchOfPrimitives bunch = yaml.load(dump); + assertEquals("Must be truncated.", Long.valueOf(10000000000L).intValue(), + bunch.getPrimitiveInt()); + } - public void testPrimitivesException() { - Yaml yaml = new Yaml(); - String dump = "!!org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives [10, 40, true]"; - try { - yaml.load(dump); - fail(); - } catch (YAMLException e) { - assertTrue(e - .getMessage() - .startsWith( - "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives; exception=No suitable constructor with 3 arguments found for class org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives")); - } + public void testPrimitivesException() { + Yaml yaml = new Yaml(); + String dump = "!!org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives [10, 40, true]"; + try { + yaml.load(dump); + fail(); + } catch (YAMLException e) { + assertTrue(e.getMessage().startsWith( + "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives; exception=No suitable constructor with 3 arguments found for class org.yaml.snakeyaml.immutable.primitives.BunchOfPrimitives")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/introspector/PropertyTest.java b/src/test/java/org/yaml/snakeyaml/introspector/PropertyTest.java new file mode 100644 index 00000000..f538357a --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/introspector/PropertyTest.java @@ -0,0 +1,156 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.introspector; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.Assert; +import org.junit.Test; +import org.yaml.snakeyaml.constructor.TestBean1; + +public class PropertyTest { + + @Test + public void testMethodPropertyToString() throws IntrospectionException { + for (PropertyDescriptor property : Introspector.getBeanInfo(TestBean1.class) + .getPropertyDescriptors()) { + if (property.getName().equals("text")) { + MethodProperty prop = new MethodProperty(property); + assertEquals("text of class java.lang.String", prop.toString()); + } + } + } + + @Test + public void testGetFieldPropertyAnnotation() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setBeanAccess(BeanAccess.FIELD); + + Property name = propertyUtils.getProperty(TestBean.class, "name"); + + TestAnnotation annotation = name.getAnnotation(TestAnnotation.class); + assertNotNull(annotation); + assertEquals("field", annotation.value()); + } + + @Test + public void testGetFieldPropertyAnnotations() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setBeanAccess(BeanAccess.FIELD); + + Property property = propertyUtils.getProperty(TestBean.class, "name"); + + List<Annotation> annotations = property.getAnnotations(); + assertEquals(1, annotations.size()); + + Annotation annotation = annotations.get(0); + assertEquals(annotation.annotationType(), TestAnnotation.class); + assertEquals("field", ((TestAnnotation) annotation).value()); + + } + + @Test + public void testGetMethodPropertyAnnotation() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setBeanAccess(BeanAccess.PROPERTY); + + Property property = propertyUtils.getProperty(TestBean.class, "age"); + + TestAnnotation annotation = property.getAnnotation(TestAnnotation.class); + assertNotNull(annotation); + assertEquals("getter", annotation.value()); // Annotation on getter takes precedence + } + + @Test + public void testGetMethodPropertyAnnotationSetterOnly() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setBeanAccess(BeanAccess.PROPERTY); + + Property property = propertyUtils.getProperty(TestBean.class, "lastName"); + TestAnnotation annotation = property.getAnnotation(TestAnnotation.class); + assertNotNull(annotation); + assertEquals("setter", annotation.value()); + } + + @Test + public void testGetMethodPropertyAnnotationsSetterOnly() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setBeanAccess(BeanAccess.PROPERTY); + + Property property = propertyUtils.getProperty(TestBean.class, "lastName"); + List<Annotation> annotations = property.getAnnotations(); + assertEquals(1, annotations.size()); + + Annotation annotation = annotations.get(0); + + Assert.assertEquals(TestAnnotation.class, annotation.annotationType()); + Assert.assertEquals("setter", ((TestAnnotation) annotation).value()); + } + + @Test + public void testGetMethodPropertyAnnotations() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setBeanAccess(BeanAccess.PROPERTY); + + Property age = propertyUtils.getProperty(TestBean.class, "age"); + + List<Annotation> annotations = age.getAnnotations(); + assertEquals(2, annotations.size()); + + Set<String> expectedValues = new HashSet<String>(Arrays.asList("getter", "setter")); + + for (Annotation annotation : annotations) { + assertEquals(annotation.annotationType(), TestAnnotation.class); + String value = ((TestAnnotation) annotation).value(); + Assert.assertTrue("The annotation has unexpected value: " + annotation, + expectedValues.remove(value)); + } + } + + @Test + public void testGetMissingPropertyAnnotation() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setSkipMissingProperties(true); + + Property property = propertyUtils.getProperty(TestBean.class, "missing"); + + assertNull(property.getAnnotation(TestAnnotation.class)); + } + + @Test + public void testGetMissingPropertyAnnotations() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setSkipMissingProperties(true); + + Property property = propertyUtils.getProperty(TestBean.class, "missing"); + + List<Annotation> annotations = property.getAnnotations(); + + assertNotNull(annotations); + assertTrue(annotations.isEmpty()); + } + + +} diff --git a/src/test/java/org/yaml/snakeyaml/introspector/TestAnnotation.java b/src/test/java/org/yaml/snakeyaml/introspector/TestAnnotation.java new file mode 100644 index 00000000..7e276fae --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/introspector/TestAnnotation.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.introspector; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.FIELD}) +public @interface TestAnnotation { + + String value() default ""; +} diff --git a/src/test/java/org/yaml/snakeyaml/introspector/TestBean.java b/src/test/java/org/yaml/snakeyaml/introspector/TestBean.java new file mode 100644 index 00000000..83a171da --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/introspector/TestBean.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.introspector; + +public class TestBean { + + @TestAnnotation("field") + private String name; + private String lastName; + private Integer age; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @TestAnnotation(value = "setter") + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @TestAnnotation(value = "getter") + public Integer getAge() { + return age; + } + + @TestAnnotation(value = "setter") + public void setAge(Integer age) { + this.age = age; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue10/BasicDumpTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue10/BasicDumpTest.java index a16c4e27..1b88b499 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue10/BasicDumpTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue10/BasicDumpTest.java @@ -1,99 +1,95 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue10; import java.util.ArrayList; import java.util.Iterator; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class BasicDumpTest extends TestCase { - public void testTag() { - DataSource base = new DataSource(); - JDBCDataSource baseJDBC = new JDBCDataSource(); - baseJDBC.setParent(base); - - ArrayList<DataSource> dataSources = new ArrayList<DataSource>(); - // trying expected order first - dataSources.add(base); - dataSources.add(baseJDBC); - - DataSources ds = new DataSources(); - ds.setDataSources(dataSources); - - Yaml yaml = new Yaml(); - String output = yaml.dump(ds); - - String etalon = Util.getLocalResource("javabeans/issue10-1.yaml"); - assertEquals(etalon.trim(), output.trim()); - Object obj = yaml.load(output); - DataSources dsOut = (DataSources) obj; - Iterator<DataSource> iter = dsOut.getDataSources().iterator(); - assertFalse("Must be DataSource.", iter.next() instanceof JDBCDataSource); - assertTrue(iter.next() instanceof JDBCDataSource); - } - - public void testTag2() { - DataSource base = new DataSource(); - JDBCDataSource baseJDBC = new JDBCDataSource(); - baseJDBC.setParent(base); - - ArrayList<DataSource> dataSources = new ArrayList<DataSource>(); - dataSources.add(base); - dataSources.add(baseJDBC); - - DataSources ds = new DataSources(); - ds.setDataSources(dataSources); - - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(ds); - - String etalon = Util.getLocalResource("javabeans/issue10-2.yaml"); - assertEquals(etalon.trim(), output.trim()); - } - - /** - * different order does not require the global tag - */ - public void testTag3() { - DataSource base = new DataSource(); - JDBCDataSource baseJDBC = new JDBCDataSource(); - baseJDBC.setParent(base); - - ArrayList<DataSource> dataSources = new ArrayList<DataSource>(); - dataSources.add(baseJDBC); - dataSources.add(base); - - DataSources ds = new DataSources(); - ds.setDataSources(dataSources); - - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(ds); - - String etalon = Util.getLocalResource("javabeans/issue10-3.yaml"); - assertEquals(etalon.trim(), output.trim()); - // load - Yaml beanLoader = new Yaml(); - DataSources bean = beanLoader.loadAs(output, DataSources.class); - Iterator<DataSource> iter = bean.getDataSources().iterator(); - assertTrue(iter.next() instanceof JDBCDataSource); - assertFalse("Must be DataSource.", iter.next() instanceof JDBCDataSource); - } + public void testTag() { + DataSource base = new DataSource(); + JDBCDataSource baseJDBC = new JDBCDataSource(); + baseJDBC.setParent(base); + + ArrayList<DataSource> dataSources = new ArrayList<DataSource>(); + // trying expected order first + dataSources.add(base); + dataSources.add(baseJDBC); + + DataSources ds = new DataSources(); + ds.setDataSources(dataSources); + + Yaml yaml = new Yaml(); + String output = yaml.dump(ds); + + String etalon = Util.getLocalResource("javabeans/issue10-1.yaml"); + assertEquals(etalon.trim(), output.trim()); + Object obj = yaml.load(output); + DataSources dsOut = (DataSources) obj; + Iterator<DataSource> iter = dsOut.getDataSources().iterator(); + assertFalse("Must be DataSource.", iter.next() instanceof JDBCDataSource); + assertTrue(iter.next() instanceof JDBCDataSource); + } + + public void testTag2() { + DataSource base = new DataSource(); + JDBCDataSource baseJDBC = new JDBCDataSource(); + baseJDBC.setParent(base); + + ArrayList<DataSource> dataSources = new ArrayList<DataSource>(); + dataSources.add(base); + dataSources.add(baseJDBC); + + DataSources ds = new DataSources(); + ds.setDataSources(dataSources); + + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(ds); + + String etalon = Util.getLocalResource("javabeans/issue10-2.yaml"); + assertEquals(etalon.trim(), output.trim()); + } + + /** + * different order does not require the global tag + */ + public void testTag3() { + DataSource base = new DataSource(); + JDBCDataSource baseJDBC = new JDBCDataSource(); + baseJDBC.setParent(base); + + ArrayList<DataSource> dataSources = new ArrayList<DataSource>(); + dataSources.add(baseJDBC); + dataSources.add(base); + + DataSources ds = new DataSources(); + ds.setDataSources(dataSources); + + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(ds); + + String etalon = Util.getLocalResource("javabeans/issue10-3.yaml"); + assertEquals(etalon.trim(), output.trim()); + // load + Yaml beanLoader = new Yaml(); + DataSources bean = beanLoader.loadAs(output, DataSources.class); + Iterator<DataSource> iter = bean.getDataSources().iterator(); + assertTrue(iter.next() instanceof JDBCDataSource); + assertFalse("Must be DataSource.", iter.next() instanceof JDBCDataSource); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSource.java b/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSource.java index 3063b9ea..0874ac12 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSource.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSource.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue10; public class DataSource { - String name; - public String getName() { - return name; - } + String name; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSources.java b/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSources.java index 995e2ca4..ecdbee37 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSources.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue10/DataSources.java @@ -1,30 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue10; import java.util.List; public class DataSources { - List<DataSource> dataSources; - public List<DataSource> getDataSources() { - return dataSources; - } + List<DataSource> dataSources; - public void setDataSources(List<DataSource> dataSources) { - this.dataSources = dataSources; - } + public List<DataSource> getDataSources() { + return dataSources; + } + + public void setDataSources(List<DataSource> dataSources) { + this.dataSources = dataSources; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue10/JDBCDataSource.java b/src/test/java/org/yaml/snakeyaml/issues/issue10/JDBCDataSource.java index e80193ea..6f2e2482 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue10/JDBCDataSource.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue10/JDBCDataSource.java @@ -1,56 +1,55 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue10; public class JDBCDataSource extends DataSource { - String username; - String password; - String url; - DataSource parent; + String username; + String password; + String url; - public DataSource getParent() { - return parent; - } + DataSource parent; - public void setParent(DataSource parent) { - this.parent = parent; - } + public DataSource getParent() { + return parent; + } - public String getUsername() { - return username; - } + public void setParent(DataSource parent) { + this.parent = parent; + } - public void setUsername(String username) { - this.username = username; - } + public String getUsername() { + return username; + } - public String getPassword() { - return password; - } + public void setUsername(String username) { + this.username = username; + } - public void setPassword(String password) { - this.password = password; - } + public String getPassword() { + return password; + } - public String getUrl() { - return url; - } + public void setPassword(String password) { + this.password = password; + } - public void setUrl(String url) { - this.url = url; - } + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue100/Data.java b/src/test/java/org/yaml/snakeyaml/issues/issue100/Data.java index 1596802a..08d794f7 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue100/Data.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue100/Data.java @@ -1,65 +1,64 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue100; public class Data { - private String id; - private int age; - public Data() { - this.id = null; - this.age = 999; - } + private String id; + private int age; - public Data(String id, int age) { - this.id = id; - this.age = age; - } + public Data() { + this.id = null; + this.age = 999; + } - public String getId() { - return id; - } + public Data(String id, int age) { + this.id = id; + this.age = age; + } - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public int getAge() { - return age; - } + public void setId(String id) { + this.id = id; + } - public void setAge(int age) { - this.age = age; - } + public int getAge() { + return age; + } - @Override - public String toString() { - return "Data [age=" + age + ", id=" + id + "]"; - } + public void setAge(int age) { + this.age = age; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Data) { - return toString().equals(obj.toString()); - } - return false; - } + @Override + public String toString() { + return "Data [age=" + age + ", id=" + id + "]"; + } - @Override - public int hashCode() { - return toString().hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Data) { + return toString().equals(obj.toString()); } + return false; + } + + @Override + public int hashCode() { + return toString().hashCode(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue100/DataBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue100/DataBean.java index cd311714..a60b25af 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue100/DataBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue100/DataBean.java @@ -1,47 +1,46 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue100; public class DataBean { - private String id; - private Data data; - private DataMore more; - public String getId() { - return id; - } + private String id; + private Data data; + private DataMore more; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public Data getData() { - return data; - } + public void setId(String id) { + this.id = id; + } - public void setData(Data data) { - this.data = data; - } + public Data getData() { + return data; + } - public DataMore getMore() { - return more; - } + public void setData(Data data) { + this.data = data; + } - public void setMore(DataMore more) { - this.more = more; - } + public DataMore getMore() { + return more; + } + + public void setMore(DataMore more) { + this.more = more; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue100/DataMore.java b/src/test/java/org/yaml/snakeyaml/issues/issue100/DataMore.java index 4d4dff31..5ff96502 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue100/DataMore.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue100/DataMore.java @@ -1,43 +1,42 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue100; public class DataMore extends Data { - private boolean complete; - public DataMore() { - setId("-1"); - setAge(-1); - } + private boolean complete; - public DataMore(String id, int age, boolean complete) { - super(id, age); - this.complete = complete; - } + public DataMore() { + setId("-1"); + setAge(-1); + } - public boolean isComplete() { - return complete; - } + public DataMore(String id, int age, boolean complete) { + super(id, age); + this.complete = complete; + } - public void setComplete(boolean complete) { - this.complete = complete; - } + public boolean isComplete() { + return complete; + } - @Override - public String toString() { - return "DataMore [complete=" + complete + ", toString()=" + super.toString() + "]"; - } + public void setComplete(boolean complete) { + this.complete = complete; + } + + @Override + public String toString() { + return "DataMore [complete=" + complete + ", toString()=" + super.toString() + "]"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeJavaBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeJavaBeanTest.java index 21545574..431bd82d 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeJavaBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeJavaBeanTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue100; @@ -19,180 +17,181 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class MergeJavaBeanTest extends TestCase { - @SuppressWarnings("unchecked") - public void testNoMerge() { - String input = "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- *id001"; - // System.out.println(input); - Yaml yaml = new Yaml(); - List<Data> list = (List<Data>) yaml.load(input); - for (Data data : list) { - // System.out.println(data); - assertEquals("id123", data.getId()); - assertEquals(11, data.getAge()); - } - } - - public void testMergeWithTags() { - String input = Util.getLocalResource("issues/issue100-1.yaml"); - // System.out.println(input); - Yaml yaml = new Yaml(); - - List<?> list = (List<?>) yaml.load(input); - // First object: Data ( 11, "id123" ) - assertEquals(list.get(0).getClass(), Data.class); - assertEquals(11, ((Data) list.get(0)).getAge()); - assertEquals("id123", ((Data) list.get(0)).getId()); - - // Second object: Data ( 13, "id456" ) - assertEquals(list.get(1).getClass(), Data.class); - assertEquals(13, ((Data) list.get(1)).getAge()); - assertEquals("id456", ((Data) list.get(1)).getId()); - - // Third object: Data ( 11, "id789" ) - assertEquals(list.get(2).getClass(), Data.class); - assertEquals(11, ((Data) list.get(2)).getAge()); - assertEquals("id789", ((Data) list.get(2)).getId()); - - // 4th object: DataMore ( 30, "id123" ) - assertEquals(list.get(3).getClass(), DataMore.class); - assertEquals(30, ((DataMore) list.get(3)).getAge()); - assertEquals("id123", ((DataMore) list.get(3)).getId()); - assertTrue(((DataMore) list.get(3)).isComplete()); - - // 5th object: Map ( age: 100 ) - assertTrue(list.get(4) instanceof Map); - assertEquals(1, ((Map<?, ?>) list.get(4)).size()); - assertTrue(((Map<?, ?>) list.get(4)).containsKey("age")); - assertEquals(100, ((Map<?, ?>) list.get(4)).get("age")); - - // 6th object: DataMore ( 100, "id789" ) - assertEquals(list.get(5).getClass(), DataMore.class); - assertEquals(100, ((DataMore) list.get(5)).getAge()); - assertEquals("id789", ((DataMore) list.get(5)).getId()); - assertFalse(((DataMore) list.get(5)).isComplete()); - // All instances except the last Map must be different Data instances - Set<Data> dataSet = new HashSet<Data>(); - for (Object data : list) { - if (data instanceof Data) { - dataSet.add((Data) data); - } - } - assertEquals("Must be all but one Data instances.", list.size() - 1, dataSet.size()); + @SuppressWarnings("unchecked") + public void testNoMerge() { + String input = + "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- *id001"; + // System.out.println(input); + Yaml yaml = new Yaml(); + List<Data> list = yaml.load(input); + for (Data data : list) { + // System.out.println(data); + assertEquals("id123", data.getId()); + assertEquals(11, data.getAge()); } - - /** - * Since to explicit tag is provided JavaBean properties are used to create - * a map - */ - @SuppressWarnings("unchecked") - public void testMergeBeanToMap() { - String input = "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- << : *id001"; - // System.out.println(input); - Yaml yaml = new Yaml(); - List<Object> list = (List<Object>) yaml.load(input); - // First object: Data ( 11, "id123" ) - Data first = (Data) list.get(0); - assertEquals(11, first.getAge()); - assertEquals("id123", first.getId()); - // Second object is map - Map<?, ?> second = (Map<?, ?>) list.get(1); - assertEquals(11, second.get("age")); - assertEquals("id123", second.get("id")); - } - - @SuppressWarnings("unchecked") - public void testMergeAndDeviate() { - String input = "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- <<: *id001\n id: id456"; - // System.out.println(input); - Yaml yaml = new Yaml(); - List<Object> list = (List<Object>) yaml.load(input); - // First object: Data ( 11, "id123" ) - Data first = (Data) list.get(0); - assertEquals(11, first.getAge()); - assertEquals("id123", first.getId()); - // Second object is map with a diffrent id - Map<?, ?> second = (Map<?, ?>) list.get(1); - assertEquals(11, second.get("age")); - assertEquals("id456", second.get("id")); - } - - /** - * <pre> - * Test that the merge-override works correctly in the case of custom classes / data types. - * Two base objects are specified: - * id001 refers to Data ( 11, "id123" ) - * id002 refers to Data ( 37, null ) with a literal null value - * The third object is specified as having the properties of id001, with the properties of - * id002 overriding where they conflict. - * Data ( 37, "id123" ) - * </pre> - */ - @SuppressWarnings("unchecked") - public void testMergeAndDeviateOverride() { - String input = "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- &id002 !!org.yaml.snakeyaml.issues.issue100.Data {age: 37}\n- <<: [ *id002, *id001 ]"; - // System.out.println(input); - Yaml yaml = new Yaml(); - List<Data> list = (List<Data>) yaml.load(input); - - // First object: Data ( 11, "id123" ) - assertEquals(11, list.get(0).getAge()); - assertEquals("id123", list.get(0).getId()); - - // Second object: Data ( 37, null ) - assertEquals(37, list.get(1).getAge()); - assertEquals(null, list.get(1).getId()); - - // Third object: map - Map<?, ?> third = (Map<?, ?>) list.get(2); - assertEquals(37, third.get("age")); - assertEquals("id123", third.get("id")); - } - - /** - * When the merged JavaBean is itself a JavaBean property then explicit tag - * is not required - */ - public void testMergeBeanProperty() { - String input = Util.getLocalResource("issues/issue100-3.yaml"); - // System.out.println(input); - Yaml yaml = new Yaml(new Constructor(DataBean.class)); - DataBean bean = (DataBean) yaml.load(input); - assertEquals("id001", bean.getId()); - assertEquals("id002", bean.getData().getId()); - assertEquals(17, bean.getData().getAge()); - assertEquals(17, bean.getMore().getAge()); - assertEquals("more003", bean.getMore().getId()); - assertTrue(bean.getMore().isComplete()); - } - - /** - * Merge map to JavaBean - */ - @SuppressWarnings("unchecked") - public void testMergeMapToJavaBean() { - String input = "- &id001 { age: 11, id: id123 }\n- !!org.yaml.snakeyaml.issues.issue100.Data\n <<: *id001\n id: id456"; - // System.out.println(input); - Yaml yaml = new Yaml(new Constructor()); - List<Object> objects = (List<Object>) yaml.load(input); - assertEquals(2, objects.size()); - // Check first type - Object first = objects.get(0); - Map<Object, Object> firstMap = (Map<Object, Object>) first; - // Check first contents - assertEquals(11, firstMap.get("age")); - assertEquals("id123", firstMap.get("id")); - // Check second contents - Data secondData = (Data) objects.get(1); - assertEquals(11, secondData.getAge()); - assertEquals("id456", secondData.getId()); + } + + public void testMergeWithTags() { + String input = Util.getLocalResource("issues/issue100-1.yaml"); + // System.out.println(input); + Yaml yaml = new Yaml(); + + List<?> list = yaml.load(input); + // First object: Data ( 11, "id123" ) + assertEquals(list.get(0).getClass(), Data.class); + assertEquals(11, ((Data) list.get(0)).getAge()); + assertEquals("id123", ((Data) list.get(0)).getId()); + + // Second object: Data ( 13, "id456" ) + assertEquals(list.get(1).getClass(), Data.class); + assertEquals(13, ((Data) list.get(1)).getAge()); + assertEquals("id456", ((Data) list.get(1)).getId()); + + // Third object: Data ( 11, "id789" ) + assertEquals(list.get(2).getClass(), Data.class); + assertEquals(11, ((Data) list.get(2)).getAge()); + assertEquals("id789", ((Data) list.get(2)).getId()); + + // 4th object: DataMore ( 30, "id123" ) + assertEquals(list.get(3).getClass(), DataMore.class); + assertEquals(30, ((DataMore) list.get(3)).getAge()); + assertEquals("id123", ((DataMore) list.get(3)).getId()); + assertTrue(((DataMore) list.get(3)).isComplete()); + + // 5th object: Map ( age: 100 ) + assertTrue(list.get(4) instanceof Map); + assertEquals(1, ((Map<?, ?>) list.get(4)).size()); + assertTrue(((Map<?, ?>) list.get(4)).containsKey("age")); + assertEquals(100, ((Map<?, ?>) list.get(4)).get("age")); + + // 6th object: DataMore ( 100, "id789" ) + assertEquals(list.get(5).getClass(), DataMore.class); + assertEquals(100, ((DataMore) list.get(5)).getAge()); + assertEquals("id789", ((DataMore) list.get(5)).getId()); + assertFalse(((DataMore) list.get(5)).isComplete()); + // All instances except the last Map must be different Data instances + Set<Data> dataSet = new HashSet<Data>(); + for (Object data : list) { + if (data instanceof Data) { + dataSet.add((Data) data); + } } + assertEquals("Must be all but one Data instances.", list.size() - 1, dataSet.size()); + } + + /** + * Since to explicit tag is provided JavaBean properties are used to create a map + */ + @SuppressWarnings("unchecked") + public void testMergeBeanToMap() { + String input = + "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- << : *id001"; + // System.out.println(input); + Yaml yaml = new Yaml(); + List<Object> list = yaml.load(input); + // First object: Data ( 11, "id123" ) + Data first = (Data) list.get(0); + assertEquals(11, first.getAge()); + assertEquals("id123", first.getId()); + // Second object is map + Map<?, ?> second = (Map<?, ?>) list.get(1); + assertEquals(11, second.get("age")); + assertEquals("id123", second.get("id")); + } + + @SuppressWarnings("unchecked") + public void testMergeAndDeviate() { + String input = + "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- <<: *id001\n id: id456"; + // System.out.println(input); + Yaml yaml = new Yaml(); + List<Object> list = yaml.load(input); + // First object: Data ( 11, "id123" ) + Data first = (Data) list.get(0); + assertEquals(11, first.getAge()); + assertEquals("id123", first.getId()); + // Second object is map with a diffrent id + Map<?, ?> second = (Map<?, ?>) list.get(1); + assertEquals(11, second.get("age")); + assertEquals("id456", second.get("id")); + } + + /** + * <pre> + * Test that the merge-override works correctly in the case of custom classes / data types. + * Two base objects are specified: + * id001 refers to Data ( 11, "id123" ) + * id002 refers to Data ( 37, null ) with a literal null value + * The third object is specified as having the properties of id001, with the properties of + * id002 overriding where they conflict. + * Data ( 37, "id123" ) + * </pre> + */ + @SuppressWarnings("unchecked") + public void testMergeAndDeviateOverride() { + String input = + "- &id001 !!org.yaml.snakeyaml.issues.issue100.Data {age: 11, id: id123}\n- &id002 !!org.yaml.snakeyaml.issues.issue100.Data {age: 37}\n- <<: [ *id002, *id001 ]"; + // System.out.println(input); + Yaml yaml = new Yaml(); + List<Data> list = yaml.load(input); + + // First object: Data ( 11, "id123" ) + assertEquals(11, list.get(0).getAge()); + assertEquals("id123", list.get(0).getId()); + + // Second object: Data ( 37, null ) + assertEquals(37, list.get(1).getAge()); + assertNull(list.get(1).getId()); + + // Third object: map + Map<?, ?> third = (Map<?, ?>) list.get(2); + assertEquals(37, third.get("age")); + assertEquals("id123", third.get("id")); + } + + /** + * When the merged JavaBean is itself a JavaBean property then explicit tag is not required + */ + public void testMergeBeanProperty() { + String input = Util.getLocalResource("issues/issue100-3.yaml"); + // System.out.println(input); + Yaml yaml = new Yaml(new Constructor(DataBean.class)); + DataBean bean = yaml.load(input); + assertEquals("id001", bean.getId()); + assertEquals("id002", bean.getData().getId()); + assertEquals(17, bean.getData().getAge()); + assertEquals(17, bean.getMore().getAge()); + assertEquals("more003", bean.getMore().getId()); + assertTrue(bean.getMore().isComplete()); + } + + /** + * Merge map to JavaBean + */ + @SuppressWarnings("unchecked") + public void testMergeMapToJavaBean() { + String input = + "- &id001 { age: 11, id: id123 }\n- !!org.yaml.snakeyaml.issues.issue100.Data\n <<: *id001\n id: id456"; + // System.out.println(input); + Yaml yaml = new Yaml(new Constructor()); + List<Object> objects = yaml.load(input); + assertEquals(2, objects.size()); + // Check first type + Object first = objects.get(0); + Map<Object, Object> firstMap = (Map<Object, Object>) first; + // Check first contents + assertEquals(11, firstMap.get("age")); + assertEquals("id123", firstMap.get("id")); + // Check second contents + Data secondData = (Data) objects.get(1); + assertEquals(11, secondData.getAge()); + assertEquals("id456", secondData.getId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeMapsTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeMapsTest.java index c89bc3be..02a1bb25 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeMapsTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue100/MergeMapsTest.java @@ -1,42 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue100; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class MergeMapsTest extends TestCase { - @SuppressWarnings("unchecked") - public void testExplicitMergeTag() { - String input = Util.getLocalResource("issues/issue100-2.yaml"); - // System.out.println(input); - Yaml yaml = new Yaml(); - Map<String, ?> list = (Map<String, ?>) yaml.load(input); - List<Map<?, ?>> result = (List<Map<?, ?>>) list.get("result"); - Map<?, ?> first = result.iterator().next(); - for (Map<?, ?> data : result) { - // System.out.println(data); - assertEquals("Size must coinside.", first.size(), data.size()); - assertEquals(first, data); - } + @SuppressWarnings("unchecked") + public void testExplicitMergeTag() { + String input = Util.getLocalResource("issues/issue100-2.yaml"); + // System.out.println(input); + Yaml yaml = new Yaml(); + Map<String, ?> list = yaml.load(input); + List<Map<?, ?>> result = (List<Map<?, ?>>) list.get("result"); + Map<?, ?> first = result.iterator().next(); + for (Map<?, ?> data : result) { + // System.out.println(data); + assertEquals("Size must coinside.", first.size(), data.size()); + assertEquals(first, data); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue102/BigDataLoadTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue102/BigDataLoadTest.java index 7e4beca0..63f8956c 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue102/BigDataLoadTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue102/BigDataLoadTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue102; @@ -20,56 +18,60 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; public class BigDataLoadTest extends TestCase { - private static final int SIZE = 5000; - public void testBigStringData() { - Yaml yaml = new Yaml(); - List<?> loaded = (List<?>) yaml.load(getLongYamlDocument(SIZE)); - assertEquals(SIZE, loaded.size()); - } + private static final int SIZE = 5000; - public void testBigStreamData() { - Yaml yaml = new Yaml(); - StringReader buffer = new StringReader(getLongYamlDocument(SIZE)); - List<?> loaded = (List<?>) yaml.load(buffer); - assertEquals(SIZE, loaded.size()); - } + public void testBigStringData() { + LoaderOptions options = new LoaderOptions(); + options.setCodePointLimit(10000000); + Yaml yaml = new Yaml(options); + List<?> loaded = yaml.load(getLongYamlDocument(SIZE)); + assertEquals(SIZE, loaded.size()); + } + + public void testBigStreamData() { + LoaderOptions options = new LoaderOptions(); + options.setCodePointLimit(10000000); + Yaml yaml = new Yaml(options); + StringReader buffer = new StringReader(getLongYamlDocument(SIZE)); + List<?> loaded = yaml.load(buffer); + assertEquals(SIZE, loaded.size()); + } - private String getLongYamlDocument(int size) { - List<DataBean> beans = new ArrayList<DataBean>(); - Yaml yaml = new Yaml(); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < size; i++) { - List<String> list = new ArrayList<String>(); - for (int j = 0; j < 10; j++) { - list.add(String.valueOf(i + j)); - } - Map<String, Integer> map = new HashMap<String, Integer>(); - for (int j = 0; j < 10; j++) { - map.put(String.valueOf(j), i + j); - } - DataBean bean = new DataBean(); - bean.setId("id" + i); - bean.setList(list); - bean.setMap(map); - beans.add(bean); - String ooo = yaml.dumpAsMap(bean); - String[] lines = ooo.split("\n"); - builder.append("-\n"); - for (int j = 0; j < lines.length; j++) { - builder.append(" "); - builder.append(lines[j]); - builder.append("\n"); - } - } - String data = builder.toString(); - System.out.println("Long data size: " + data.length() / 1024 + " kBytes."); - return data; + private String getLongYamlDocument(int size) { + List<DataBean> beans = new ArrayList<DataBean>(); + Yaml yaml = new Yaml(); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < size; i++) { + List<String> list = new ArrayList<String>(); + for (int j = 0; j < 10; j++) { + list.add(String.valueOf(i + j)); + } + Map<String, Integer> map = new HashMap<String, Integer>(); + for (int j = 0; j < 10; j++) { + map.put(String.valueOf(j), i + j); + } + DataBean bean = new DataBean(); + bean.setId("id" + i); + bean.setList(list); + bean.setMap(map); + beans.add(bean); + String ooo = yaml.dumpAsMap(bean); + String[] lines = ooo.split("\n"); + builder.append("-\n"); + for (int j = 0; j < lines.length; j++) { + builder.append(" "); + builder.append(lines[j]); + builder.append("\n"); + } } + String data = builder.toString(); + // System.out.println("Long data size: " + data.length() / 1024 + " kBytes."); + return data; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue102/DataBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue102/DataBean.java index 9b1eb387..f084d561 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue102/DataBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue102/DataBean.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue102; @@ -19,31 +17,32 @@ import java.util.List; import java.util.Map; public class DataBean { - private String id; - private List<String> list; - private Map<String, Integer> map; - public String getId() { - return id; - } + private String id; + private List<String> list; + private Map<String, Integer> map; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public List<String> getList() { - return list; - } + public void setId(String id) { + this.id = id; + } - public void setList(List<String> list) { - this.list = list; - } + public List<String> getList() { + return list; + } - public Map<String, Integer> getMap() { - return map; - } + public void setList(List<String> list) { + this.list = list; + } - public void setMap(Map<String, Integer> map) { - this.map = map; - } + public Map<String, Integer> getMap() { + return map; + } + + public void setMap(Map<String, Integer> map) { + this.map = map; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue103/FakeMap.java b/src/test/java/org/yaml/snakeyaml/issues/issue103/FakeMap.java index bdced750..78d35c48 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue103/FakeMap.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue103/FakeMap.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue103; @@ -22,107 +20,109 @@ import java.util.Map; import java.util.Set; /** - * Implements map interface, but behaves like collection. It just collects - * whatever you put(...) in here. Needed to track duplications in merge - * procedure. - * + * Implements map interface, but behaves like collection. It just collects whatever you put(...) in + * here. Needed to track duplications in merge procedure. + * * issue100 & issue103 */ public class FakeMap<K, V> implements Map<K, V> { - class FakeEntry implements java.util.Map.Entry<K, V> { - - private final K key; - private V val; - - public FakeEntry(K key, V val) { - this.key = key; - this.val = val; - } - - public K getKey() { - return key; - } + class FakeEntry implements java.util.Map.Entry<K, V> { - public V getValue() { - return val; - } - - public V setValue(V newV) { - V old = val; - val = newV; - return old; - } + private final K key; + private V val; + public FakeEntry(K key, V val) { + this.key = key; + this.val = val; } - ArrayList<java.util.Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(); - - public void clear() { - entries.clear(); + public K getKey() { + return key; } - public boolean containsKey(Object arg0) { - for (java.util.Map.Entry<K, V> entry : entries) { - if (entry.getKey().equals(arg0)) - return true; - } - return false; + public V getValue() { + return val; } - public boolean containsValue(Object arg0) { - for (java.util.Map.Entry<K, V> entry : entries) { - if (entry.getValue().equals(arg0)) - return true; - } - return false; + public V setValue(V newV) { + V old = val; + val = newV; + return old; } - public Set<java.util.Map.Entry<K, V>> entrySet() { - throw new UnsupportedOperationException(); - } + } - public V get(Object arg0) { - for (java.util.Map.Entry<K, V> entry : entries) { - if (entry.getKey().equals(arg0)) - return entry.getValue(); - } - return null; - } + ArrayList<java.util.Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(); - public boolean isEmpty() { - return values().isEmpty(); - } + public void clear() { + entries.clear(); + } - public Set<K> keySet() { - throw new UnsupportedOperationException(); + public boolean containsKey(Object arg0) { + for (java.util.Map.Entry<K, V> entry : entries) { + if (entry.getKey().equals(arg0)) { + return true; + } } - - public V put(K key, V val) { - entries.add(new FakeEntry(key, val)); - return null; + return false; + } + + public boolean containsValue(Object arg0) { + for (java.util.Map.Entry<K, V> entry : entries) { + if (entry.getValue().equals(arg0)) { + return true; + } } - - public void putAll(Map<? extends K, ? extends V> arg0) { - throw new UnsupportedOperationException(); + return false; + } + + public Set<java.util.Map.Entry<K, V>> entrySet() { + throw new UnsupportedOperationException(); + } + + public V get(Object arg0) { + for (java.util.Map.Entry<K, V> entry : entries) { + if (entry.getKey().equals(arg0)) { + return entry.getValue(); + } } - - public V remove(Object arg0) { - for (Iterator<java.util.Map.Entry<K, V>> iter = entries.iterator(); iter.hasNext();) { - java.util.Map.Entry<K, V> entry = iter.next(); - if (entry.getKey().equals(arg0)) { - iter.remove(); - return entry.getValue(); - } - } - return null; + return null; + } + + public boolean isEmpty() { + return values().isEmpty(); + } + + public Set<K> keySet() { + throw new UnsupportedOperationException(); + } + + public V put(K key, V val) { + entries.add(new FakeEntry(key, val)); + return null; + } + + public void putAll(Map<? extends K, ? extends V> arg0) { + throw new UnsupportedOperationException(); + } + + public V remove(Object arg0) { + for (Iterator<java.util.Map.Entry<K, V>> iter = entries.iterator(); iter.hasNext();) { + java.util.Map.Entry<K, V> entry = iter.next(); + if (entry.getKey().equals(arg0)) { + iter.remove(); + return entry.getValue(); + } } + return null; + } - public int size() { - return entries.size(); - } + public int size() { + return entries.size(); + } - public Collection<V> values() { - throw new UnsupportedOperationException(); - } + public Collection<V> values() { + throw new UnsupportedOperationException(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue103/MergingTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue103/MergingTest.java index b825e283..2d2a5a00 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue103/MergingTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue103/MergingTest.java @@ -1,120 +1,116 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue103; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class MergingTest extends TestCase { - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void testMergeWithDefaultMap() { - String input = Util.getLocalResource("issues/issue103.yaml"); - // System.out.println(input); - Yaml yaml = new Yaml(); - - check((Map) yaml.load(input)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testMergeWithFakeMap() { - String input = Util.getLocalResource("issues/issue103.yaml"); - // System.out.println(input); - Constructor c = new Constructor() { - protected java.util.Map<Object, Object> createDefaultMap() { - return new FakeMap<Object, Object>(); - } - }; - - Yaml yaml = new Yaml(c); - - check((FakeMap) yaml.load(input)); - } - - private void check(Map<String, List<Map<Object, Object>>> map) { - - assertEquals(2, map.size()); - assertTrue(map.containsKey("input")); - assertTrue(map.containsKey("result")); - - // input: ... - List<Map<Object, Object>> inputList = map.get("input"); - assertEquals(4, inputList.size()); - - Map<Object, Object> center = inputList.get(0); - assertEquals(2, center.size()); - assertEquals(Integer.valueOf(1), center.get("x")); - assertEquals(Integer.valueOf(2), center.get("y")); - - Map<Object, Object> left = inputList.get(1); - assertEquals(2, left.size()); - assertEquals(Integer.valueOf(0), left.get("x")); - assertEquals(Integer.valueOf(2), left.get("y")); - - Map<Object, Object> big = inputList.get(2); - assertEquals(1, big.size()); - assertEquals(Integer.valueOf(10), big.get("r")); - - Map<Object, Object> small = inputList.get(3); - assertEquals(1, small.size()); - assertEquals(Integer.valueOf(1), small.get("r")); - - // result : ... - List<Map<Object, Object>> resultList = map.get("result"); - assertEquals(5, resultList.size()); - - Map<Object, Object> explicitKeys = resultList.get(0); - assertEquals(4, explicitKeys.size()); - assertEquals(Integer.valueOf(1), explicitKeys.get("x")); - assertEquals(Integer.valueOf(2), explicitKeys.get("y")); - assertEquals(Integer.valueOf(10), explicitKeys.get("r")); - assertEquals("center/big", explicitKeys.get("label")); - - Map<?, ?> merge_center = resultList.get(1); - assertEquals(4, merge_center.size()); - assertEquals(Integer.valueOf(1), merge_center.get("x")); - assertEquals(Integer.valueOf(2), merge_center.get("y")); - assertEquals(Integer.valueOf(10), merge_center.get("r")); - assertEquals("center/big", merge_center.get("label")); - - Map<?, ?> merge_left_override = resultList.get(2); - assertEquals(4, merge_left_override.size()); - assertEquals(Integer.valueOf(0), merge_left_override.get("x")); - assertEquals(Integer.valueOf(5), merge_left_override.get("y")); - assertEquals(Integer.valueOf(10), merge_left_override.get("r")); - assertEquals("center/big", merge_left_override.get("label")); - - Map<?, ?> merge_center_big = resultList.get(3); - assertEquals(4, merge_center_big.size()); - assertEquals(Integer.valueOf(1), merge_center_big.get("x")); - assertEquals(Integer.valueOf(2), merge_center_big.get("y")); - assertEquals(Integer.valueOf(10), merge_center_big.get("r")); - assertEquals("center/big", merge_center_big.get("label")); - - Map<?, ?> merge_big_left_small_override = resultList.get(4); - assertEquals(4, merge_big_left_small_override.size()); - assertEquals(Integer.valueOf(1), merge_big_left_small_override.get("x")); - assertEquals(Integer.valueOf(2), merge_big_left_small_override.get("y")); - assertEquals(Integer.valueOf(10), merge_big_left_small_override.get("r")); - assertEquals("center/big", merge_big_left_small_override.get("label")); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + public void testMergeWithDefaultMap() { + String input = Util.getLocalResource("issues/issue103.yaml"); + // System.out.println(input); + Yaml yaml = new Yaml(); + + check((Map) yaml.load(input)); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testMergeWithFakeMap() { + String input = Util.getLocalResource("issues/issue103.yaml"); + // System.out.println(input); + Constructor c = new Constructor() { + protected java.util.Map<Object, Object> createDefaultMap(int size) { + return new FakeMap<Object, Object>(); + } + }; + + Yaml yaml = new Yaml(c); + + check((FakeMap) yaml.load(input)); + } + + private void check(Map<String, List<Map<Object, Object>>> map) { + + assertEquals(2, map.size()); + assertTrue(map.containsKey("input")); + assertTrue(map.containsKey("result")); + + // input: ... + List<Map<Object, Object>> inputList = map.get("input"); + assertEquals(4, inputList.size()); + + Map<Object, Object> center = inputList.get(0); + assertEquals(2, center.size()); + assertEquals(Integer.valueOf(1), center.get("x")); + assertEquals(Integer.valueOf(2), center.get("y")); + + Map<Object, Object> left = inputList.get(1); + assertEquals(2, left.size()); + assertEquals(Integer.valueOf(0), left.get("x")); + assertEquals(Integer.valueOf(2), left.get("y")); + + Map<Object, Object> big = inputList.get(2); + assertEquals(1, big.size()); + assertEquals(Integer.valueOf(10), big.get("r")); + + Map<Object, Object> small = inputList.get(3); + assertEquals(1, small.size()); + assertEquals(Integer.valueOf(1), small.get("r")); + + // result : ... + List<Map<Object, Object>> resultList = map.get("result"); + assertEquals(5, resultList.size()); + + Map<Object, Object> explicitKeys = resultList.get(0); + assertEquals(4, explicitKeys.size()); + assertEquals(Integer.valueOf(1), explicitKeys.get("x")); + assertEquals(Integer.valueOf(2), explicitKeys.get("y")); + assertEquals(Integer.valueOf(10), explicitKeys.get("r")); + assertEquals("center/big", explicitKeys.get("label")); + + Map<?, ?> merge_center = resultList.get(1); + assertEquals(4, merge_center.size()); + assertEquals(Integer.valueOf(1), merge_center.get("x")); + assertEquals(Integer.valueOf(2), merge_center.get("y")); + assertEquals(Integer.valueOf(10), merge_center.get("r")); + assertEquals("center/big", merge_center.get("label")); + + Map<?, ?> merge_left_override = resultList.get(2); + assertEquals(4, merge_left_override.size()); + assertEquals(Integer.valueOf(0), merge_left_override.get("x")); + assertEquals(Integer.valueOf(5), merge_left_override.get("y")); + assertEquals(Integer.valueOf(10), merge_left_override.get("r")); + assertEquals("center/big", merge_left_override.get("label")); + + Map<?, ?> merge_center_big = resultList.get(3); + assertEquals(4, merge_center_big.size()); + assertEquals(Integer.valueOf(1), merge_center_big.get("x")); + assertEquals(Integer.valueOf(2), merge_center_big.get("y")); + assertEquals(Integer.valueOf(10), merge_center_big.get("r")); + assertEquals("center/big", merge_center_big.get("label")); + + Map<?, ?> merge_big_left_small_override = resultList.get(4); + assertEquals(4, merge_big_left_small_override.size()); + assertEquals(Integer.valueOf(1), merge_big_left_small_override.get("x")); + assertEquals(Integer.valueOf(2), merge_big_left_small_override.get("y")); + assertEquals(Integer.valueOf(10), merge_big_left_small_override.get("r")); + assertEquals("center/big", merge_big_left_small_override.get("label")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue11/YamlMapTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue11/YamlMapTest.java index 65508757..8b6468aa 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue11/YamlMapTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue11/YamlMapTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue11; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; @@ -30,116 +26,122 @@ import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; public class YamlMapTest extends TestCase { - public void testYaml() { - Yaml yaml = new Yaml(new ExtendedConstructor(), new ExtendedRepresenter()); - String output = yaml.dump(new Custom(123)); - // System.out.println(output); - Custom o = (Custom) yaml.load(output); - assertEquals("123", o.getStr()); - } - @SuppressWarnings("unchecked") - public void testYamlMap() { - Map<String, Object> data = new TreeMap<String, Object>(); - data.put("customTag", new Custom(123)); - - Yaml yaml = new Yaml(new ExtendedConstructor(), new ExtendedRepresenter()); - String output = yaml.dump(data); - // System.out.println(output); - Object o = yaml.load(output); - - assertTrue(o instanceof Map); - Map<String, Object> m = (Map<String, Object>) o; - assertTrue(m.get("customTag") instanceof Custom); + public void testYaml() { + Yaml yaml = new Yaml(new ExtendedConstructor(), new ExtendedRepresenter()); + String output = yaml.dump(new Custom(123)); + // System.out.println(output); + Custom o = yaml.load(output); + assertEquals("123", o.getStr()); + } + + @SuppressWarnings("unchecked") + public void testYamlMap() { + Map<String, Object> data = new TreeMap<String, Object>(); + data.put("customTag", new Custom(123)); + + Yaml yaml = new Yaml(new ExtendedConstructor(), new ExtendedRepresenter()); + String output = yaml.dump(data); + // System.out.println(output); + Object o = yaml.load(output); + + assertTrue(o instanceof Map); + Map<String, Object> m = (Map<String, Object>) o; + assertTrue(m.get("customTag") instanceof Custom); + } + + @SuppressWarnings("unchecked") + public void testYamlMapBean() { + Map<String, Object> data = new TreeMap<String, Object>(); + data.put("knownClass", new Wrapper("test", new Custom(456))); + + Yaml yaml = new Yaml(new ExtendedConstructor(), new ExtendedRepresenter()); + String output = yaml.dump(data); + // System.out.println(output); + Object o = yaml.load(output); + + assertTrue(o instanceof Map); + Map<String, Object> m = (Map<String, Object>) o; + assertEquals(Wrapper.class, m.get("knownClass").getClass()); + } + + public static class Wrapper { + + private String a; + private Custom b; + + public Wrapper(String s, Custom bb) { + a = s; + b = bb; } - @SuppressWarnings("unchecked") - public void testYamlMapBean() { - Map<String, Object> data = new TreeMap<String, Object>(); - data.put("knownClass", new Wrapper("test", new Custom(456))); + public Wrapper() {} - Yaml yaml = new Yaml(new ExtendedConstructor(), new ExtendedRepresenter()); - String output = yaml.dump(data); - // System.out.println(output); - Object o = yaml.load(output); + public String getA() { + return a; + } - assertTrue(o instanceof Map); - Map<String, Object> m = (Map<String, Object>) o; - assertEquals(Wrapper.class, m.get("knownClass").getClass()); + public void setA(String s) { + a = s; } - public static class Wrapper { - private String a; - private Custom b; + public Custom getB() { + return b; + } - public Wrapper(String s, Custom bb) { - a = s; - b = bb; - } + public void setB(Custom bb) { + b = bb; + } + } - public Wrapper() { - } + public static class Custom { - public String getA() { - return a; - } + final private String str; - public void setA(String s) { - a = s; - } + public Custom(Integer i) { + str = i.toString(); + } - public Custom getB() { - return b; - } + public Custom(Custom c) { + str = c.str; + } - public void setB(Custom bb) { - b = bb; - } + public String toString() { + return str; } - public static class Custom { - final private String str; + public String getStr() { + return str; + } + } - public Custom(Integer i) { - str = i.toString(); - } + public static class ExtendedRepresenter extends Representer { - public Custom(Custom c) { - str = c.str; - } + public ExtendedRepresenter() { + this.representers.put(Custom.class, new RepresentCustom()); + } - public String toString() { - return str; - } + private class RepresentCustom implements Represent { - public String getStr() { - return str; - } + public Node representData(Object data) { + return representScalar(new Tag("!Custom"), data.toString()); + } } + } - public static class ExtendedRepresenter extends Representer { - public ExtendedRepresenter() { - this.representers.put(Custom.class, new RepresentCustom()); - } + public static class ExtendedConstructor extends Constructor { - private class RepresentCustom implements Represent { - public Node representData(Object data) { - return representScalar(new Tag("!Custom"), ((Custom) data).toString()); - } - } + public ExtendedConstructor() { + this.yamlConstructors.put(new Tag("!Custom"), new ConstructCustom()); } - public static class ExtendedConstructor extends Constructor { - public ExtendedConstructor() { - this.yamlConstructors.put(new Tag("!Custom"), new ConstructCustom()); - } + private class ConstructCustom extends AbstractConstruct { - private class ConstructCustom extends AbstractConstruct { - public Object construct(Node node) { - String str = (String) constructScalar((ScalarNode) node); - return new Custom(new Integer(str)); - } + public Object construct(Node node) { + String str = constructScalar((ScalarNode) node); + return new Custom(Integer.valueOf(str)); + } - } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue111/LongUriTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue111/LongUriTest.java index acf00914..1c69a3d5 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue111/LongUriTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue111/LongUriTest.java @@ -1,50 +1,46 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue111; import java.io.StringReader; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; public class LongUriTest extends TestCase { - /** - * Try loading a tag with a very long escaped URI section (over 256 bytes' - * worth). - */ - public void testLongURIEscape() { - Yaml loader = new Yaml(); - // Create a long escaped string by exponential growth... - String longEscURI = "%41"; // capital A... - for (int i = 0; i < 10; ++i) { - longEscURI = longEscURI + longEscURI; - } - assertEquals(1024 * 3, longEscURI.length()); - String yaml = "!" + longEscURI + " www"; - Node node = loader.compose(new StringReader(yaml)); - ScalarNode scalar = (ScalarNode) node; - String etalon = "!"; - for (int i = 0; i < 1024; i++) { - etalon += "A"; - } - assertEquals(1025, etalon.length()); - assertEquals(etalon, scalar.getTag().toString()); + /** + * Try loading a tag with a very long escaped URI section (over 256 bytes' worth). + */ + public void testLongURIEscape() { + Yaml loader = new Yaml(); + // Create a long escaped string by exponential growth... + String longEscURI = "%41"; // capital A... + for (int i = 0; i < 10; ++i) { + longEscURI = longEscURI + longEscURI; + } + assertEquals(1024 * 3, longEscURI.length()); + String yaml = "!" + longEscURI + " www"; + + Node node = loader.compose(new StringReader(yaml)); + ScalarNode scalar = (ScalarNode) node; + String etalon = "!"; + for (int i = 0; i < 1024; i++) { + etalon += "A"; } + assertEquals(1025, etalon.length()); + assertEquals(etalon, scalar.getTag().toString()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue112/MyClass.java b/src/test/java/org/yaml/snakeyaml/issues/issue112/MyClass.java index 2f7c1b6f..8aca29dc 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue112/MyClass.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue112/MyClass.java @@ -1,33 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue112; public class MyClass<T extends Object> { - T name; - public void setName(T name) { - this.name = name; - } + T name; - public T getName() { - return this.name; - } + public void setName(T name) { + this.name = name; + } - @Override - public String toString() { - return name.toString(); - } + public T getName() { + return this.name; + } + + @Override + public String toString() { + return name.toString(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue112/MyCompositeObject.java b/src/test/java/org/yaml/snakeyaml/issues/issue112/MyCompositeObject.java index 471e678e..48a48ab8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue112/MyCompositeObject.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue112/MyCompositeObject.java @@ -1,30 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue112; import java.util.Collection; public class MyCompositeObject { - Collection<MyClass<? extends Object>> things; - public Collection<MyClass<? extends Object>> getThings() { - return this.things; - } + Collection<MyClass<? extends Object>> things; - public void setThings(Collection<MyClass<? extends Object>> things) { - this.things = things; - } + public Collection<MyClass<? extends Object>> getThings() { + return this.things; + } + + public void setThings(Collection<MyClass<? extends Object>> things) { + this.things = things; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue112/ParameterisedTypeLoadingTestCase.java b/src/test/java/org/yaml/snakeyaml/issues/issue112/ParameterisedTypeLoadingTestCase.java index 6b7f94a8..c1e4e8d9 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue112/ParameterisedTypeLoadingTestCase.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue112/ParameterisedTypeLoadingTestCase.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue112; @@ -20,7 +18,6 @@ import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.InputStream; - import org.junit.Test; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -28,38 +25,38 @@ import org.yaml.snakeyaml.constructor.Constructor; public class ParameterisedTypeLoadingTestCase { - @Test - public void testParameterisedTypeLoading() throws IOException { - Yaml yamlParser = new Yaml(new Constructor(MyCompositeObject.class)); - MyCompositeObject obj = (MyCompositeObject) yamlParser.load(getInput()); - check(obj); - - // dump the object - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(obj); - assertEquals(Util.getLocalResource("issues/issue112-2.yaml"), output); - } - - @Test - public void testJavaBeanLoader() throws IOException { - Yaml yamlParser = new Yaml(); - MyCompositeObject obj = yamlParser.loadAs(getInput(), MyCompositeObject.class); - check(obj); + @Test + public void testParameterisedTypeLoading() throws IOException { + Yaml yamlParser = new Yaml(new Constructor(MyCompositeObject.class)); + MyCompositeObject obj = yamlParser.load(getInput()); + check(obj); + + // dump the object + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(obj); + assertEquals(Util.getLocalResource("issues/issue112-2.yaml"), output); + } + + @Test + public void testJavaBeanLoader() throws IOException { + Yaml yamlParser = new Yaml(); + MyCompositeObject obj = yamlParser.loadAs(getInput(), MyCompositeObject.class); + check(obj); + } + + private void check(MyCompositeObject obj) { + Object[] values = {1, "two", 3, "four", "!!!"}; + assertNotNull(obj); + assertEquals(5, obj.getThings().size()); + int i = 0; + for (MyClass<? extends Object> thing : obj.getThings()) { + assertEquals(MyClass.class, thing.getClass()); + assertNotNull("The 'name' property must be set.", thing.getName()); + assertEquals(values[i++], thing.getName()); } + } - private void check(MyCompositeObject obj) { - Object[] values = { 1, "two", 3, "four", "!!!" }; - assertNotNull(obj); - assertEquals(5, obj.getThings().size()); - int i = 0; - for (MyClass<? extends Object> thing : obj.getThings()) { - assertEquals(MyClass.class, thing.getClass()); - assertNotNull("The 'name' property must be set.", thing.getName()); - assertEquals(values[i++], thing.getName()); - } - } - - private InputStream getInput() throws IOException { - return this.getClass().getClassLoader().getResource("issues/issue112-1.yaml").openStream(); - } + private InputStream getInput() throws IOException { + return this.getClass().getClassLoader().getResource("issues/issue112-1.yaml").openStream(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue114/PreserveTypeTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue114/PreserveTypeTest.java index fd69f9a4..87cd08b2 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue114/PreserveTypeTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue114/PreserveTypeTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue114; @@ -19,72 +17,70 @@ import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class PreserveTypeTest extends TestCase { - public static class MyBean { + public static class MyBean { - private int dummy; + private int dummy; - public int getDummy() { - return dummy; - } - - public void setDummy(int dummy) { - this.dummy = dummy; - } + public int getDummy() { + return dummy; } - public static class ReferencingBean { - - private List<MyBean> myBeans = new LinkedList<PreserveTypeTest.MyBean>(); - - public List<MyBean> getMyBeans() { - return myBeans; - } - - public void setMyBeans(List<MyBean> myBeans) { - this.myBeans = myBeans; - } + public void setDummy(int dummy) { + this.dummy = dummy; } + } - private Map<String, Object> createData(boolean collectionFirst) { - MyBean myBean = new MyBean(); - ReferencingBean referencingBean = new ReferencingBean(); - referencingBean.getMyBeans().add(myBean); + public static class ReferencingBean { - LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); - if (collectionFirst) { - map.put("referencingBean", referencingBean); - map.put("myBean", myBean); - } else { - map.put("myBean", myBean); - map.put("referencingBean", referencingBean); - } - return map; - } + private List<MyBean> myBeans = new LinkedList<PreserveTypeTest.MyBean>(); - private void check(String doc) { - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map<String, Object> loaded = (Map<String, Object>) yaml.load(doc); - Object myBean2 = loaded.get("myBean"); - assertTrue(myBean2.getClass().toString(), myBean2 instanceof MyBean); + public List<MyBean> getMyBeans() { + return myBeans; } - public void testPreserveType1() { - Yaml yaml = new Yaml(); - String s = yaml.dump(createData(true)); - check(s); + public void setMyBeans(List<MyBean> myBeans) { + this.myBeans = myBeans; } - - public void testPreserveType2() { - Yaml yaml = new Yaml(); - String s = yaml.dump(createData(false)); - check(s); + } + + private Map<String, Object> createData(boolean collectionFirst) { + MyBean myBean = new MyBean(); + ReferencingBean referencingBean = new ReferencingBean(); + referencingBean.getMyBeans().add(myBean); + + LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); + if (collectionFirst) { + map.put("referencingBean", referencingBean); + map.put("myBean", myBean); + } else { + map.put("myBean", myBean); + map.put("referencingBean", referencingBean); } + return map; + } + + private void check(String doc) { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<String, Object> loaded = yaml.load(doc); + Object myBean2 = loaded.get("myBean"); + assertTrue(myBean2.getClass().toString(), myBean2 instanceof MyBean); + } + + public void testPreserveType1() { + Yaml yaml = new Yaml(); + String s = yaml.dump(createData(true)); + check(s); + } + + public void testPreserveType2() { + Yaml yaml = new Yaml(); + String s = yaml.dump(createData(false)); + check(s); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue115/IssueBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue115/IssueBean.java index 572b94c7..0b2aa8ba 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue115/IssueBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue115/IssueBean.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue115; public class IssueBean { - private ParameterizedBean<Integer, String> bean = new ParameterizedBean<Integer, String>(); - public ParameterizedBean<Integer, String> getBean() { - return bean; - } + private ParameterizedBean<Integer, String> bean = new ParameterizedBean<Integer, String>(); - public void setBean(ParameterizedBean<Integer, String> bean) { - this.bean = bean; - } -}
\ No newline at end of file + public ParameterizedBean<Integer, String> getBean() { + return bean; + } + + public void setBean(ParameterizedBean<Integer, String> bean) { + this.bean = bean; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedBean.java index ad3376ad..e3bfec70 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedBean.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue115; public class ParameterizedBean<K, V> { - private K k; - private V v; - public K getK() { - return k; - } + private K k; + private V v; - public void setK(K k) { - this.k = k; - } + public K getK() { + return k; + } - public V getV() { - return v; - } + public void setK(K k) { + this.k = k; + } - public void setV(V v) { - this.v = v; - } -}
\ No newline at end of file + public V getV() { + return v; + } + + public void setV(V v) { + this.v = v; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedJavaBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedJavaBeanTest.java index ca3ccb44..dcf1e4e7 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedJavaBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedJavaBeanTest.java @@ -1,55 +1,51 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue115; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class ParameterizedJavaBeanTest extends TestCase { - public void testAsStandalone() { - ParameterizedBean<Integer, String> bean = new ParameterizedBean<Integer, String>(); - bean.setK(13); - bean.setV("ID47"); - Yaml yaml = new Yaml(); - String result = yaml.dump(bean); - assertEquals("!!org.yaml.snakeyaml.issues.issue115.ParameterizedBean {k: 13, v: ID47}\n", - result); - // load - @SuppressWarnings("unchecked") - ParameterizedBean<Integer, String> beanParsed = (ParameterizedBean<Integer, String>) yaml - .load(result); - assertEquals(new Integer(13), beanParsed.getK()); - assertEquals("ID47", beanParsed.getV()); - } + public void testAsStandalone() { + ParameterizedBean<Integer, String> bean = new ParameterizedBean<Integer, String>(); + bean.setK(13); + bean.setV("ID47"); + Yaml yaml = new Yaml(); + String result = yaml.dump(bean); + assertEquals("!!org.yaml.snakeyaml.issues.issue115.ParameterizedBean {k: 13, v: ID47}\n", + result); + // load + @SuppressWarnings("unchecked") + ParameterizedBean<Integer, String> beanParsed = yaml.load(result); + assertEquals(Integer.valueOf(13), beanParsed.getK()); + assertEquals("ID47", beanParsed.getV()); + } - public void testAsJavaBeanProperty() { - Yaml yaml = new Yaml(); - IssueBean issue = new IssueBean(); - ParameterizedBean<Integer, String> bean = new ParameterizedBean<Integer, String>(); - bean.setK(432); - bean.setV("Val432"); - issue.setBean(bean); - String result = yaml.dump(issue); - assertEquals("!!org.yaml.snakeyaml.issues.issue115.IssueBean\nbean: {k: 432, v: Val432}\n", - result); - // load - IssueBean issueParsed = (IssueBean) yaml.load(result); - assertEquals(new Integer(432), issueParsed.getBean().getK()); - assertEquals("Val432", issueParsed.getBean().getV()); - } -}
\ No newline at end of file + public void testAsJavaBeanProperty() { + Yaml yaml = new Yaml(); + IssueBean issue = new IssueBean(); + ParameterizedBean<Integer, String> bean = new ParameterizedBean<Integer, String>(); + bean.setK(432); + bean.setV("Val432"); + issue.setBean(bean); + String result = yaml.dump(issue); + assertEquals("!!org.yaml.snakeyaml.issues.issue115.IssueBean\nbean: {k: 432, v: Val432}\n", + result); + // load + IssueBean issueParsed = yaml.load(result); + assertEquals(Integer.valueOf(432), issueParsed.getBean().getK()); + assertEquals("Val432", issueParsed.getBean().getV()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedTest.java index c6c69d30..710c9e65 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue115/ParameterizedTest.java @@ -1,56 +1,57 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue115; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class ParameterizedTest extends TestCase { - public void testAsStandalone() { - Parameterized<Integer> parm = new Parameterized<Integer>(); - parm.t = 3; - Yaml yaml = new Yaml(); - String result = yaml.dump(parm); - assertEquals("!!org.yaml.snakeyaml.issues.issue115.Parameterized {t: 3}\n", result); - @SuppressWarnings("unchecked") - // load - Parameterized<Integer> parmParsed = (Parameterized<Integer>) yaml.load(result); - assertEquals(new Integer(3), parmParsed.t); - } - - public void testAsJavaBeanProperty() { - Yaml yaml = new Yaml(); - Issue issue = new Issue(); - Parameterized<Integer> parm = new Parameterized<Integer>(); - parm.t = 555; - issue.parm = parm; - String result = yaml.dump(issue); - assertEquals("!!org.yaml.snakeyaml.issues.issue115.Issue\nparm: {t: 555}\n", result); - // load - Issue issueParsed = (Issue) yaml.load(result); - assertEquals(new Integer(555), issueParsed.parm.t); - } + public void testAsStandalone() { + Parameterized<Integer> parm = new Parameterized<Integer>(); + parm.t = 3; + Yaml yaml = new Yaml(); + String result = yaml.dump(parm); + assertEquals("!!org.yaml.snakeyaml.issues.issue115.Parameterized {t: 3}\n", result); + @SuppressWarnings("unchecked") + // load + Parameterized<Integer> parmParsed = yaml.load(result); + assertEquals(Integer.valueOf(3), parmParsed.t); + } + + public void testAsJavaBeanProperty() { + Yaml yaml = new Yaml(); + Issue issue = new Issue(); + Parameterized<Integer> parm = new Parameterized<Integer>(); + parm.t = 555; + issue.parm = parm; + String result = yaml.dump(issue); + assertEquals("!!org.yaml.snakeyaml.issues.issue115.Issue\nparm: {t: 555}\n", result); + // load + Issue issueParsed = yaml.load(result); + assertEquals(Integer.valueOf(555), issueParsed.parm.t); + } } + class Issue { - public Parameterized<Integer> parm = new Parameterized<Integer>(); + + public Parameterized<Integer> parm = new Parameterized<Integer>(); } + class Parameterized<T> { - public T t; -}
\ No newline at end of file + + public T t; +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue116/HiddenSpecial.java b/src/test/java/org/yaml/snakeyaml/issues/issue116/HiddenSpecial.java index 8fea9ff6..dad74d63 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue116/HiddenSpecial.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue116/HiddenSpecial.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue116; public class HiddenSpecial { - private int inaccessableField; - public HiddenSpecial(String something) { - this.inaccessableField = something.hashCode(); - } + private final int inaccessableField; - public int retrieveMyVerySpecialField() { - return inaccessableField; - } -}
\ No newline at end of file + public HiddenSpecial(String something) { + this.inaccessableField = something.hashCode(); + } + + public int retrieveMyVerySpecialField() { + return inaccessableField; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue116/NoFieldsTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue116/NoFieldsTest.java index 044cdb8d..adcc0d23 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue116/NoFieldsTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue116/NoFieldsTest.java @@ -1,70 +1,70 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue116; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.YAMLException; public class NoFieldsTest extends TestCase { - public void testEmptyClass() { - Empty empty = new Empty(); - Yaml yaml = new Yaml(); - String result = yaml.dump(empty); - assertEquals("!!org.yaml.snakeyaml.issues.issue116.Empty {}\n", result); - Object emptyParsed = yaml.load(result); - assertTrue(emptyParsed instanceof Empty); - } + public void testEmptyClass() { + Empty empty = new Empty(); + Yaml yaml = new Yaml(); + String result = yaml.dump(empty); + assertEquals("!!org.yaml.snakeyaml.issues.issue116.Empty {}\n", result); + Object emptyParsed = yaml.load(result); + assertTrue(emptyParsed instanceof Empty); + } - public void testHiddenParameter() { - Hidden hidden = new Hidden(); - Yaml yaml = new Yaml(); - try { - yaml.dump(hidden); - fail("an exception should have been thrown"); - } catch (YAMLException e) { - assertEquals(e.getMessage(), - "No JavaBean properties found in org.yaml.snakeyaml.issues.issue116.Hidden"); - } - Object hiddenParsed = yaml.load("!!org.yaml.snakeyaml.issues.issue116.Hidden {}\n"); - assertTrue(hiddenParsed instanceof Hidden); + public void testHiddenParameter() { + Hidden hidden = new Hidden(); + Yaml yaml = new Yaml(); + try { + yaml.dump(hidden); + fail("an exception should have been thrown"); + } catch (YAMLException e) { + assertEquals(e.getMessage(), + "No JavaBean properties found in org.yaml.snakeyaml.issues.issue116.Hidden"); } + Object hiddenParsed = yaml.load("!!org.yaml.snakeyaml.issues.issue116.Hidden {}\n"); + assertTrue(hiddenParsed instanceof Hidden); + } - public void testSpecialHiddenParameter() { - HiddenSpecial hidden = new HiddenSpecial("qwerty"); - Yaml yaml = new Yaml(); - try { - yaml.dump(hidden); - fail("an exception should have been thrown"); - } catch (YAMLException e) { - assertEquals(e.getMessage(), - "No JavaBean properties found in org.yaml.snakeyaml.issues.issue116.HiddenSpecial"); - } - HiddenSpecial hs = (HiddenSpecial) yaml - .load("!!org.yaml.snakeyaml.issues.issue116.HiddenSpecial foo\n"); - assertEquals("foo".hashCode(), hs.retrieveMyVerySpecialField()); + public void testSpecialHiddenParameter() { + HiddenSpecial hidden = new HiddenSpecial("qwerty"); + Yaml yaml = new Yaml(); + try { + yaml.dump(hidden); + fail("an exception should have been thrown"); + } catch (YAMLException e) { + assertEquals(e.getMessage(), + "No JavaBean properties found in org.yaml.snakeyaml.issues.issue116.HiddenSpecial"); } + HiddenSpecial hs = yaml.load("!!org.yaml.snakeyaml.issues.issue116.HiddenSpecial foo\n"); + assertEquals("foo".hashCode(), hs.retrieveMyVerySpecialField()); + } } + class Empty { + } + class Hidden { - @SuppressWarnings("unused") - private int inaccessableField; + + @SuppressWarnings("unused") + private int inaccessableField; } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue124/Bean124.java b/src/test/java/org/yaml/snakeyaml/issues/issue124/Bean124.java index 202e84ed..e686b665 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue124/Bean124.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue124/Bean124.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue124; @@ -19,36 +17,37 @@ import java.util.ArrayList; import java.util.List; public class Bean124 { - private String a; - private List<Integer> numbers; - - public Bean124() { - this.a = "aaa"; - this.numbers = new ArrayList<Integer>(3); - numbers.add(1); - numbers.add(2); - numbers.add(3); - } - - public Bean124(String a, List<Integer> numbers) { - super(); - this.a = a; - this.numbers = numbers; - } - - public String getA() { - return a; - } - - public void setA(String a) { - this.a = a; - } - - public List<Integer> getNumbers() { - return numbers; - } - - public void setNumbers(List<Integer> numbers) { - this.numbers = numbers; - } -}
\ No newline at end of file + + private String a; + private List<Integer> numbers; + + public Bean124() { + this.a = "aaa"; + this.numbers = new ArrayList<Integer>(3); + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + public Bean124(String a, List<Integer> numbers) { + super(); + this.a = a; + this.numbers = numbers; + } + + public String getA() { + return a; + } + + public void setA(String a) { + this.a = a; + } + + public List<Integer> getNumbers() { + return numbers; + } + + public void setNumbers(List<Integer> numbers) { + this.numbers = numbers; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue124/DumpTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue124/DumpTest.java index 7da50388..8f237e3e 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue124/DumpTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue124/DumpTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue124; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; @@ -24,64 +21,63 @@ import org.yaml.snakeyaml.nodes.Tag; public class DumpTest extends TestCase { - public void testDumperOptionsSideEffect() { - Yaml yaml = new Yaml(); - Bean124 bean = new Bean124(); - String output0 = yaml.dump(bean); - // System.out.println(output0); - assertEquals("!!org.yaml.snakeyaml.issues.issue124.Bean124\na: aaa\nnumbers: [1, 2, 3]\n", - output0); - String output1 = yaml.dumpAsMap(bean); - // System.out.println(output1); - assertEquals("a: aaa\nnumbers:\n- 1\n- 2\n- 3\n", output1); - String output2 = yaml.dump(bean); - // System.out.println(output2); - assertEquals("Yaml.dumpAs() should not have any side effects.", output0, output2); - } + public void testDumperOptionsSideEffect() { + Yaml yaml = new Yaml(); + Bean124 bean = new Bean124(); + String output0 = yaml.dump(bean); + // System.out.println(output0); + assertEquals("!!org.yaml.snakeyaml.issues.issue124.Bean124\na: aaa\nnumbers: [1, 2, 3]\n", + output0); + String output1 = yaml.dumpAsMap(bean); + // System.out.println(output1); + assertEquals("a: aaa\nnumbers:\n- 1\n- 2\n- 3\n", output1); + String output2 = yaml.dump(bean); + // System.out.println(output2); + assertEquals("Yaml.dumpAs() should not have any side effects.", output0, output2); + } - public void testDumperDifferentTag() { - Yaml yaml = new Yaml(); - Bean124 bean = new Bean124(); - String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), FlowStyle.BLOCK); - assertEquals("!!foo.bar\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n", output1); - } + public void testDumperDifferentTag() { + Yaml yaml = new Yaml(); + Bean124 bean = new Bean124(); + String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), FlowStyle.BLOCK); + assertEquals("!!foo.bar\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n", output1); + } - public void testDumperFlowStyle() { - Yaml yaml = new Yaml(); - Bean124 bean = new Bean124(); - String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), FlowStyle.FLOW); - assertEquals("!!foo.bar {a: aaa, numbers: [1, 2, 3]}\n", output1); - } + public void testDumperFlowStyle() { + Yaml yaml = new Yaml(); + Bean124 bean = new Bean124(); + String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), FlowStyle.FLOW); + assertEquals("!!foo.bar {a: aaa, numbers: [1, 2, 3]}\n", output1); + } - public void testDumperAutoStyle() { - Yaml yaml = new Yaml(); - Bean124 bean = new Bean124(); - String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), FlowStyle.AUTO); - assertEquals("!!foo.bar\na: aaa\nnumbers: [1, 2, 3]\n", output1); - } + public void testDumperAutoStyle() { + Yaml yaml = new Yaml(); + Bean124 bean = new Bean124(); + String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), FlowStyle.AUTO); + assertEquals("!!foo.bar\na: aaa\nnumbers: [1, 2, 3]\n", output1); + } - public void testDumperNullStyle() { - Yaml yaml = new Yaml(); - Bean124 bean = new Bean124(); - String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), null); - assertEquals("!!foo.bar\na: aaa\nnumbers: [1, 2, 3]\n", output1); - } + public void testDumperNullStyle() { + Yaml yaml = new Yaml(); + Bean124 bean = new Bean124(); + String output1 = yaml.dumpAs(bean, new Tag("!!foo.bar"), null); + assertEquals("!!foo.bar\na: aaa\nnumbers: [1, 2, 3]\n", output1); + } - public void testDumperNullStyle2() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - Bean124 bean = new Bean124(); - String output1 = yaml.dumpAs(bean, new Tag("!!foo2.bar2"), null); - assertEquals("!!foo2.bar2\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n", output1); - } + public void testDumperNullStyle2() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + Bean124 bean = new Bean124(); + String output1 = yaml.dumpAs(bean, new Tag("!!foo2.bar2"), null); + assertEquals("!!foo2.bar2\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n", output1); + } - public void testDumperNullTag() { - Yaml yaml = new Yaml(); - Bean124 bean = new Bean124(); - String output1 = yaml.dumpAs(bean, null, FlowStyle.BLOCK); - assertEquals( - "!!org.yaml.snakeyaml.issues.issue124.Bean124\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n", - output1); - } -}
\ No newline at end of file + public void testDumperNullTag() { + Yaml yaml = new Yaml(); + Bean124 bean = new Bean124(); + String output1 = yaml.dumpAs(bean, null, FlowStyle.BLOCK); + assertEquals("!!org.yaml.snakeyaml.issues.issue124.Bean124\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n", + output1); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue127/Bean.java b/src/test/java/org/yaml/snakeyaml/issues/issue127/Bean.java index d347249c..d8bfb5e1 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue127/Bean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue127/Bean.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue127; public class Bean { - private String a; - private String b; - public String getA() { - return a; - } + private String a; + private String b; - public void setA(String a) { - this.a = a; - } + public String getA() { + return a; + } - public String getB() { - return b; - } + public void setA(String a) { + this.a = a; + } - public void setB(String b) { - this.b = b; - } -}
\ No newline at end of file + public String getB() { + return b; + } + + public void setB(String b) { + this.b = b; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue127/NullAliasTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue127/NullAliasTest.java index bd3da2fa..73b37aef 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue127/NullAliasTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue127/NullAliasTest.java @@ -1,25 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue127; import java.util.LinkedHashMap; import java.util.Map; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; @@ -27,30 +24,33 @@ import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; public class NullAliasTest extends TestCase { - private static final Tag MY_TAG = new Tag("tag:example.com,2011:bean"); - public void testRespresenter() { - Bean bean = new Bean(); + private static final Tag MY_TAG = new Tag("tag:example.com,2011:bean"); + + public void testRespresenter() { + Bean bean = new Bean(); - bean.setA("a"); // leave b null - Yaml yaml = new Yaml(new BeanRepresenter()); - String output = yaml.dump(bean); - assertEquals("!<tag:example.com,2011:bean>\na: a\nb: null\n", output); + bean.setA("a"); // leave b null + Yaml yaml = new Yaml(new BeanRepresenter()); + String output = yaml.dump(bean); + assertEquals("!<tag:example.com,2011:bean>\na: a\nb: null\n", output); + } + + class BeanRepresenter extends Representer { + + public BeanRepresenter() { + this.representers.put(Bean.class, new RepresentBean()); } - class BeanRepresenter extends Representer { - public BeanRepresenter() { - this.representers.put(Bean.class, new RepresentBean()); - } - - private class RepresentBean implements Represent { - public Node representData(Object data) { - Bean bean = (Bean) data; - Map<String, Object> fields = new LinkedHashMap<String, Object>(2); - fields.put("a", bean.getA()); - fields.put("b", bean.getB()); - return representMapping(MY_TAG, fields, false); - } - } + private class RepresentBean implements Represent { + + public Node representData(Object data) { + Bean bean = (Bean) data; + Map<String, Object> fields = new LinkedHashMap<String, Object>(2); + fields.put("a", bean.getA()); + fields.put("b", bean.getB()); + return representMapping(MY_TAG, fields, DumperOptions.FlowStyle.BLOCK); + } } -}
\ No newline at end of file + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue132/ScalarEventTagTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue132/ScalarEventTagTest.java index 52eb0bd7..75db4ccf 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue132/ScalarEventTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue132/ScalarEventTagTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue132; import java.io.StringReader; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.events.ScalarEvent; @@ -30,30 +26,31 @@ import org.yaml.snakeyaml.nodes.Node; * to test http://code.google.com/p/snakeyaml/issues/detail?id=132 */ public class ScalarEventTagTest extends TestCase { - public void testLoad() { - Yaml yaml = new Yaml(); - Iterable<Event> parsed = yaml.parse(new StringReader("5")); - List<Event> events = new ArrayList<Event>(5); - for (Event event : parsed) { - events.add(event); - // System.out.println(event); - } - String tag = ((ScalarEvent) events.get(2)).getTag(); - assertNull("The tag should not be specified: " + tag, tag); - } - public void testDump() { - Yaml yaml = new Yaml(); - Node intNode = yaml.represent(7); - assertEquals("tag:yaml.org,2002:int", intNode.getTag().toString()); - // System.out.println(intNode); - List<Event> intEvents = yaml.serialize(intNode); - String tag = ((ScalarEvent) intEvents.get(2)).getTag(); - assertEquals("Without the tag emitter would not know how to emit '7'", - "tag:yaml.org,2002:int", tag); - // - Node strNode = yaml.represent("7"); - assertEquals("tag:yaml.org,2002:str", strNode.getTag().toString()); - // System.out.println(strNode); + public void testLoad() { + Yaml yaml = new Yaml(); + Iterable<Event> parsed = yaml.parse(new StringReader("5")); + List<Event> events = new ArrayList<Event>(5); + for (Event event : parsed) { + events.add(event); + // System.out.println(event); } + String tag = ((ScalarEvent) events.get(2)).getTag(); + assertNull("The tag should not be specified: " + tag, tag); + } + + public void testDump() { + Yaml yaml = new Yaml(); + Node intNode = yaml.represent(7); + assertEquals("tag:yaml.org,2002:int", intNode.getTag().toString()); + // System.out.println(intNode); + List<Event> intEvents = yaml.serialize(intNode); + String tag = ((ScalarEvent) intEvents.get(2)).getTag(); + assertEquals("Without the tag emitter would not know how to emit '7'", "tag:yaml.org,2002:int", + tag); + // + Node strNode = yaml.represent("7"); + assertEquals("tag:yaml.org,2002:str", strNode.getTag().toString()); + // System.out.println(strNode); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue133/StackOverflowTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue133/StackOverflowTest.java index 080081d7..85744adf 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue133/StackOverflowTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue133/StackOverflowTest.java @@ -1,24 +1,24 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue133; -import java.awt.Point; - -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import java.awt.Point; +import org.junit.Test; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.NodeTuple; @@ -28,45 +28,49 @@ import org.yaml.snakeyaml.representer.Representer; /** * to test http://code.google.com/p/snakeyaml/issues/detail?id=133 */ -public class StackOverflowTest extends TestCase { - public void testDumpRecursiveObject() { - try { - Yaml yaml = new Yaml(); - // by default it must fail with StackOverflow - yaml.dump(new Point()); - fail("getLocation() is recursive."); - } catch (Throwable e) { - String message = e.getMessage(); - assertTrue("StackOverflow has no message: " + e.getMessage(), message == null - || message.contains("Unable to find getter for property 'location'")); - } - } +public class StackOverflowTest { - /** - * Since Point.getLocation() creates a new instance of Point class, - * SnakeYAML will fail to dump an instance of Point if 'getLocation()' is - * also included. - * - * Since Point is not really a JavaBean, we can safely skip the recursive - * property when we dump the instance of Point. - */ - private class PointRepresenter extends Representer { + @Test + public void testDumpRecursiveObjectOnJava6() { - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, - Object propertyValue, Tag customTag) { - if (javaBean instanceof Point && "location".equals(property.getName())) { - return null; - } else { - return super - .representJavaBeanProperty(javaBean, property, propertyValue, customTag); - } - } + org.junit.Assume.assumeTrue(System.getProperty("java.version").startsWith("1.6")); + + try { + Yaml yaml = new Yaml(); + // by default it must fail with StackOverflow + yaml.dump(new Point()); + fail("getLocation() is recursive."); + } catch (Throwable e) { + String message = e.getMessage(); + assertTrue("StackOverflow has no message: " + e.getMessage(), + message == null || message.contains("Unable to find getter for property 'location'")); } + } + + /** + * Since Point.getLocation() creates a new instance of Point class, SnakeYAML will fail to dump an + * instance of Point if 'getLocation()' is also included. + * + * Since Point is not really a JavaBean, we can safely skip the recursive property when we dump + * the instance of Point. + */ + private class PointRepresenter extends Representer { - public void testDump() { - Yaml yaml = new Yaml(new PointRepresenter()); - String output = yaml.dump(new Point()); - assertEquals("!!java.awt.Point {x: 0, y: 0}\n", output); + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, + Object propertyValue, Tag customTag) { + if (javaBean instanceof Point && "location".equals(property.getName())) { + return null; + } else { + return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + } } + } + + @Test + public void testDump() { + Yaml yaml = new Yaml(new PointRepresenter()); + String output = yaml.dump(new Point()); + assertEquals("!!java.awt.Point {x: 0, y: 0}\n", output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue136/TabInScalarTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue136/TabInScalarTest.java index 09c3b081..c7fa5442 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue136/TabInScalarTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue136/TabInScalarTest.java @@ -1,51 +1,48 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue136; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class TabInScalarTest extends TestCase { - public void testTab() { - String data = (String) new Yaml().load("L\tD"); - assertEquals("L\tD", data); - } - - public void testNoTab() { - String data = (String) new Yaml().load("L D"); - assertEquals("L D", data); - } - - public void testTabDoubleQuotes() { - String data = (String) new Yaml().load("\"L\tD\""); - // System.out.println(data); - assertEquals("L\tD", data); - } - - public void testTabSingleQuotes() { - String data = (String) new Yaml().load("'L\tD'"); - // System.out.println(data); - assertEquals("L\tD", data); - } - - public void testDumpTab() { - String data = (String) new Yaml().dump("L\tD"); - // System.out.println(data); - assertEquals("\"L\\tD\"\n", data); - } + public void testTab() { + String data = new Yaml().load("L\tD"); + assertEquals("L\tD", data); + } + + public void testNoTab() { + String data = new Yaml().load("L D"); + assertEquals("L D", data); + } + + public void testTabDoubleQuotes() { + String data = new Yaml().load("\"L\tD\""); + // System.out.println(data); + assertEquals("L\tD", data); + } + + public void testTabSingleQuotes() { + String data = new Yaml().load("'L\tD'"); + // System.out.println(data); + assertEquals("L\tD", data); + } + + public void testDumpTab() { + String data = new Yaml().dump("L\tD"); + // System.out.println(data); + assertEquals("\"L\\tD\"\n", data); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue137/SupplementaryCharactersTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue137/SupplementaryCharactersTest.java index 389735d3..a52c6362 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue137/SupplementaryCharactersTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue137/SupplementaryCharactersTest.java @@ -1,24 +1,24 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue137; +import java.io.InputStream; import java.io.UnsupportedEncodingException; - +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; /** @@ -26,38 +26,99 @@ import org.yaml.snakeyaml.Yaml; */ public class SupplementaryCharactersTest extends TestCase { - public void testSupplementaryCharacter() { - Yaml yaml = new Yaml(); - String parsed = (String) yaml.load("\"\\U0001f648\""); - assertEquals("\ud83d\ude48", parsed); - // System.out.println(data); - } + public static class EmojiContainer { + + public Map<String, Map<String, Integer>> sizes; + public Map<String, Map<String, List<String>>> values; + } + + public void testSupplementaryCharacter() { + Yaml yaml = new Yaml(); + String parsed = yaml.load("\"\\U0001f648\""); + assertEquals("\ud83d\ude48", parsed); + // System.out.println(data); + } + + public void testBasicMultilingualPlane() { + Yaml yaml = new Yaml(); + String parsed = yaml.load("\"\\U00000041\""); + assertEquals("A", parsed); + } + + /** + * Supplementary code points are dumped normally + */ + public void testDumpSupplementaryCodePoint() throws UnsupportedEncodingException { + String supplementary = "\ud83d\ude48"; + Yaml yaml = new Yaml(); + String output = yaml.dump(supplementary); + assertEquals("\ud83d\ude48\n", output); + String binString = yaml.load(output); + assertEquals(supplementary, binString); + } + + /** + * Non-printable characters are escaped + */ + public void testDumpNonPrintableCharacter() throws UnsupportedEncodingException { + String supplementary = "\u0001"; + Yaml yaml = new Yaml(); + String output = yaml.dump(supplementary); + assertEquals("!!binary |-\n AQ==\n", output); + byte[] binary = yaml.load(output); + String binString = new String(binary, StandardCharsets.UTF_8); + assertEquals(supplementary, binString); + } - public void testBasicMultilingualPlane() { - Yaml yaml = new Yaml(); - String parsed = (String) yaml.load("\"\\U00000041\""); - assertEquals("A", parsed); + public void testDumpSurrogateCharacter() throws UnsupportedEncodingException { + String supplementary = "\ud83d"; + Yaml yaml = new Yaml(); + try { + yaml.dump(supplementary); + fail("dumping half code point without other half should fail"); + } catch (Exception e) { + assertEquals("invalid string value has occurred", e.getMessage()); } - /** - * Supplementary Characters are dumped as binary - */ - public void testDumpSupplementaryCharacter() throws UnsupportedEncodingException { - String supplementary = "\ud83d\ude48"; - Yaml yaml = new Yaml(); - String output = yaml.dump(supplementary); - assertEquals("!!binary |-\n 8J+ZiA==\n", output); - byte[] binary = (byte[]) yaml.load(output); - String binString = new String(binary, "UTF-8"); - assertEquals(supplementary, binString); + } + + public void testLoadSupplementaryCodePoint() { + new Yaml().load("\"\ud83d\ude48\"\n"); + } + + public void testLoadSurrogateCharacter() { + try { + new Yaml().load("\"\ud83d\"\n"); + fail("separate surrogate characters are not printable"); + } catch (Exception e) { + assertEquals("special characters are not allowed", e.getMessage()); } + } + + /* + * This method tests loading of the document with a lot of SupplementaryCharacters. Main purpose + * is to check that StreamReader actually reads document fully, but not in one read (since file is + * bigger than StreamReader buffer). + */ + public void testLoadingEmoji() { + InputStream input = this.getClass().getClassLoader().getResourceAsStream("issues/emoji.yaml"); + EmojiContainer emoji = new Yaml().loadAs(input, EmojiContainer.class); + + assertEquals(emoji.sizes.keySet(), emoji.values.keySet()); - public void testLoadSupplementaryCharacter() { - try { - new Yaml().load("\"\ud83d\ude48\"\n"); - fail("Are Supplementary Characters printable ?"); - } catch (Exception e) { - assertEquals("special characters are not allowed", e.getMessage()); - } + for (Map.Entry<String, Map<String, Integer>> mainTopic : emoji.sizes.entrySet()) { + String mainName = mainTopic.getKey(); + Map<String, Integer> subtopic2size = mainTopic.getValue(); + + Map<String, List<String>> subtopic2values = emoji.values.get(mainName); + assertEquals(subtopic2size.keySet(), subtopic2values.keySet()); + + for (Map.Entry<String, Integer> subTopic : subtopic2size.entrySet()) { + String subName = subTopic.getKey(); + + assertEquals(subTopic.getValue().intValue(), subtopic2values.get(subName).size()); + } } + + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue138/ReaderExceptionTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue138/ReaderExceptionTest.java index 851ab171..4084fda7 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue138/ReaderExceptionTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue138/ReaderExceptionTest.java @@ -1,35 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue138; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.reader.ReaderException; public class ReaderExceptionTest extends TestCase { - public void testGetters() { - try { - new Yaml().load("012\u0019"); - fail(); - } catch (ReaderException e) { - assertEquals(3, e.getPosition()); - assertEquals("'string'", e.getName()); - assertEquals('\u0019', e.getCharacter()); - } + public void testGetters() { + try { + new Yaml().load("012\u0019"); + fail(); + } catch (ReaderException e) { + assertEquals(3, e.getPosition()); + assertEquals("'string'", e.getName()); + assertEquals(0x19, e.getCodePoint()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue139/MergeValueTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue139/MergeValueTest.java index debf99f6..7dc347cd 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue139/MergeValueTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue139/MergeValueTest.java @@ -1,70 +1,66 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue139; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class MergeValueTest extends TestCase { - public void testNotUniqueSimple() { - String simple = "{key: 1, key: 2}"; - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map<String, Integer> map = (Map<String, Integer>) yaml.load(simple); - assertEquals(1, map.size()); - assertEquals(new Integer(2), map.get("key")); - } - - public void testMerge() { - check("issues/issue139-1.yaml");// merge with unique keys - check("issues/issue139-2.yaml");// merge with same key - } + public void testNotUniqueSimple() { + String simple = "{key: 1, key: 2}"; + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<String, Integer> map = yaml.load(simple); + assertEquals(1, map.size()); + assertEquals(Integer.valueOf(2), map.get("key")); + } - private void check(String name) { - String input = Util.getLocalResource(name); - // System.out.println(input); - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map<String, Object> map = (Map<String, Object>) yaml.load(input); - assertEquals(2, map.size()); - assertTrue(map.containsKey("common")); - assertTrue(map.containsKey("production")); - assertEquals(map.get("common"), map.get("production")); - } + public void testMerge() { + check("issues/issue139-1.yaml");// merge with unique keys + check("issues/issue139-2.yaml");// merge with same key + } - /** - * http://yaml.org/type/merge.html: If the value associated with the key is - * a single mapping node, each of its key/value pairs is inserted into the - * current mapping, <b>unless the key already exists in it</b>. - */ + private void check(String name) { + String input = Util.getLocalResource(name); + // System.out.println(input); + Yaml yaml = new Yaml(); @SuppressWarnings("unchecked") - public void testMergeUnlessAlreadyExists() { - String input = Util.getLocalResource("issues/issue139-3.yaml"); - // System.out.println(input); - Yaml yaml = new Yaml(); - Map<String, Object> map = (Map<String, Object>) yaml.load(input); - assertEquals(2, map.size()); - Map<String, Integer> common = (Map<String, Integer>) map.get("common"); - Map<String, Integer> production = (Map<String, Integer>) map.get("production"); - assertEquals(new Integer(2), common.get("key")); - assertEquals(new Integer(3), production.get("key")); - } + Map<String, Object> map = yaml.load(input); + assertEquals(2, map.size()); + assertTrue(map.containsKey("common")); + assertTrue(map.containsKey("production")); + assertEquals(map.get("common"), map.get("production")); + } + + /** + * http://yaml.org/type/merge.html: If the value associated with the key is a single mapping node, + * each of its key/value pairs is inserted into the current mapping, <b>unless the key already + * exists in it</b>. + */ + @SuppressWarnings("unchecked") + public void testMergeUnlessAlreadyExists() { + String input = Util.getLocalResource("issues/issue139-3.yaml"); + // System.out.println(input); + Yaml yaml = new Yaml(); + Map<String, Object> map = yaml.load(input); + assertEquals(2, map.size()); + Map<String, Integer> common = (Map<String, Integer>) map.get("common"); + Map<String, Integer> production = (Map<String, Integer>) map.get("production"); + assertEquals(Integer.valueOf(2), common.get("key")); + assertEquals(Integer.valueOf(3), production.get("key")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue139/UniqueKeyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue139/UniqueKeyTest.java index 4117b979..28488b02 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue139/UniqueKeyTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue139/UniqueKeyTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue139; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.error.YAMLException; @@ -29,36 +25,36 @@ import org.yaml.snakeyaml.nodes.NodeTuple; public class UniqueKeyTest extends TestCase { - public void testNotUnique() { - String data = "{key: 1, key: 2}"; - Yaml yaml = new Yaml(new UniqueKeyConstructor()); - try { - yaml.load(data); - fail("The same key must be rejected"); - } catch (Exception e) { - assertEquals("The key is not unique key", e.getMessage()); - } + public void testNotUnique() { + String data = "{key: 1, key: 2}"; + Yaml yaml = new Yaml(new UniqueKeyConstructor()); + try { + yaml.load(data); + fail("The same key must be rejected"); + } catch (Exception e) { + assertEquals("The key is not unique key", e.getMessage()); } - - private class UniqueKeyConstructor extends Constructor { - - @Override - protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) { - List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue(); - for (NodeTuple tuple : nodeValue) { - Node keyNode = tuple.getKeyNode(); - Node valueNode = tuple.getValueNode(); - Object key = constructObject(keyNode); - if (key != null) { - key.hashCode();// check circular dependencies - } - Object value = constructObject(valueNode); - Object old = mapping.put(key, value); - if (old != null) { - throw new YAMLException("The key is not unique " + key); - } - } + } + + private class UniqueKeyConstructor extends Constructor { + + @Override + protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) { + List<NodeTuple> nodeValue = node.getValue(); + for (NodeTuple tuple : nodeValue) { + Node keyNode = tuple.getKeyNode(); + Node valueNode = tuple.getValueNode(); + Object key = constructObject(keyNode); + if (key != null) { + key.hashCode();// check circular dependencies + } + Object value = constructObject(valueNode); + Object old = mapping.put(key, value); + if (old != null) { + throw new YAMLException("The key is not unique " + key); } + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue141/ConfigurableTimezoneTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue141/ConfigurableTimezoneTest.java index 872af854..145e5784 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue141/ConfigurableTimezoneTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue141/ConfigurableTimezoneTest.java @@ -1,45 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue141; import java.util.Date; import java.util.TimeZone; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class ConfigurableTimezoneTest extends TestCase { - public void testNoTimezone() { - Yaml yaml = new Yaml(); - String output = yaml.dump(new Date()); - assertTrue(output, output.endsWith("Z\n")); - } + public void testNoTimezone() { + Yaml yaml = new Yaml(); + String output = yaml.dump(new Date()); + assertTrue(output, output.endsWith("Z\n")); + } - public void testTimezone() { - DumperOptions options = new DumperOptions(); - options.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); - Yaml yaml = new Yaml(options); - Date date = new Date(); - String output = yaml.dump(date); - // System.out.println(output); - assertTrue(output, output.trim().endsWith("+1:00")); - Date parsed = (Date) yaml.load(output); - assertEquals(date, parsed); - } + public void testTimezone() { + DumperOptions options = new DumperOptions(); + options.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); + Yaml yaml = new Yaml(options); + Date date = new Date(); + String output = yaml.dump(date); + // System.out.println(output); + assertTrue(output, output.trim().endsWith("+01:00")); + Date parsed = yaml.load(output); + assertEquals(date, parsed); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue142/DerivedMapTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue142/DerivedMapTest.java new file mode 100644 index 00000000..c78b94a1 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue142/DerivedMapTest.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue142; + +import java.util.LinkedHashMap; +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class DerivedMapTest extends TestCase { + + public static class Features extends LinkedHashMap<String, Object> { + + } + + public static class MyObject { + + private String name; + private Map<String, Object> features = new LinkedHashMap<String, Object>(); + private Features moreFeatures = new Features(); + + public Map<String, Object> getFeatures() { + return features; + } + + public void setFeatures(Map<String, Object> features) { + this.features = features; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Features getMoreFeatures() { + return moreFeatures; + } + + public void setMoreFeatures(Features moreFeatures) { + this.moreFeatures = moreFeatures; + } + + } + + public void testDerivedMap() { + MyObject o = new MyObject(); + o.setName("Mickey"); + o.getFeatures().put("Address", "Disney"); + o.getMoreFeatures().put("Address", "Disney"); + Yaml yaml = new Yaml(); + String asYaml = yaml.dump(o); + // System.out.println(asYaml); + MyObject o2 = yaml.load(asYaml); + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue143/GenericMapTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue143/GenericMapTest.java index c98449ec..8c7ec921 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue143/GenericMapTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue143/GenericMapTest.java @@ -1,45 +1,44 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue143; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class GenericMapTest extends TestCase { - public void testMap() throws Exception { - BeanWithMap fact = new BeanWithMap(); - GenericMap<Integer> shash = fact.getMap(); - shash.put("toto", new Integer(10)); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - // String txt = yaml.dump(fact); - // assertTrue(txt.contains("org.yaml.snakeyaml.issues.issue143.GenericMapTest")); - } + public void testMap() throws Exception { + BeanWithMap fact = new BeanWithMap(); + GenericMap<Integer> shash = fact.getMap(); + shash.put("toto", Integer.valueOf(10)); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + // String txt = yaml.dump(fact); + // assertTrue(txt.contains("org.yaml.snakeyaml.issues.issue143.GenericMapTest")); + } - public static class GenericMap<T> extends java.util.HashMap<String, T> { - private static final long serialVersionUID = -6833859369398863926L; - } + public static class GenericMap<T> extends java.util.HashMap<String, T> { + + private static final long serialVersionUID = -6833859369398863926L; + } + + public class BeanWithMap { - public class BeanWithMap { - public GenericMap<Integer> getMap() { - return new GenericMap<Integer>(); - } + public GenericMap<Integer> getMap() { + return new GenericMap<Integer>(); } -}
\ No newline at end of file + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue144/BeanData.java b/src/test/java/org/yaml/snakeyaml/issues/issue144/BeanData.java index 79880002..71b35192 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue144/BeanData.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue144/BeanData.java @@ -1,46 +1,45 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue144; public class BeanData { - private String id; - private float number; - public BeanData() { - this.id = "noid"; - } + private String id; + private float number; - public BeanData(String id) { - this.id = id; - } + public BeanData() { + this.id = "noid"; + } - public String getId() { - return id; - } + public BeanData(String id) { + this.id = id; + } - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public float getNumber() { - return number; - } + public void setId(String id) { + this.id = id; + } - public void setNumber(float number) { - this.number = number; - } + public float getNumber() { + return number; + } -}
\ No newline at end of file + public void setNumber(float number) { + this.number = number; + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue144/FloatPropertyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue144/FloatPropertyTest.java index b9492aad..527aa2c4 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue144/FloatPropertyTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue144/FloatPropertyTest.java @@ -1,42 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue144; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.extensions.compactnotation.CompactConstructor; public class FloatPropertyTest extends TestCase { - public void testFloatAsJavaBeanProperty() throws Exception { - BeanData bean = new BeanData(); - bean.setId("id1"); - bean.setNumber(3.5f); - Yaml yaml = new Yaml(); - String txt = yaml.dump(bean); - BeanData parsed = yaml.loadAs(txt, BeanData.class); - assertEquals(3.5f, parsed.getNumber()); - } + public void testFloatAsJavaBeanProperty() throws Exception { + BeanData bean = new BeanData(); + bean.setId("id1"); + bean.setNumber(3.5f); + Yaml yaml = new Yaml(); + String txt = yaml.dump(bean); + BeanData parsed = yaml.loadAs(txt, BeanData.class); + assertEquals(3.5f, parsed.getNumber()); + } - public void testCompact() { - Yaml yaml = new Yaml(new CompactConstructor()); - BeanData obj = (BeanData) yaml - .load("org.yaml.snakeyaml.issues.issue144.BeanData(id): { number: 123.4 }"); - assertEquals(123.4f, obj.getNumber()); - } + public void testCompact() { + Yaml yaml = new Yaml(new CompactConstructor()); + BeanData obj = yaml.load("org.yaml.snakeyaml.issues.issue144.BeanData(id): { number: 123.4 }"); + assertEquals(123.4f, obj.getNumber()); + } -}
\ No newline at end of file +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue145/AbstractThing.java b/src/test/java/org/yaml/snakeyaml/issues/issue145/AbstractThing.java index c169e387..516faac3 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue145/AbstractThing.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue145/AbstractThing.java @@ -1,28 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue145; public abstract class AbstractThing { - protected String id; - public String getId() { - return id; - } + protected String id; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue145/CompleteThing.java b/src/test/java/org/yaml/snakeyaml/issues/issue145/CompleteThing.java index eca4a066..498b7f46 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue145/CompleteThing.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue145/CompleteThing.java @@ -1,24 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue145; public class CompleteThing extends AbstractThing { - @Override - public String toString() { - return "CompleteThing-" + id; - } + @Override + public String toString() { + return "CompleteThing-" + id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue145/LineNumberInExceptionTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue145/LineNumberInExceptionTest.java index 39c8c740..5218fea0 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue145/LineNumberInExceptionTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue145/LineNumberInExceptionTest.java @@ -1,55 +1,54 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue145; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class LineNumberInExceptionTest extends TestCase { - public void testLineReport() { - Yaml yaml = new Yaml(); - try { - yaml.load("---\n!!org.yaml.snakeyaml.issues.issue145.AbstractThing { id: QQQ }"); - fail("Instances for abstract classes cannot be created"); - } catch (Exception e) { - assertTrue(e.toString().contains("line 2, column 1")); - assertEquals( - "Can't construct a java object for tag:yaml.org,2002:org.yaml.snakeyaml.issues.issue145.AbstractThing; exception=java.lang.InstantiationException\n" - + " in 'string', line 2, column 1:\n" - + " !!org.yaml.snakeyaml.issues.issu ... \n" + " ^\n", - e.getMessage()); - } - } + public void testLineReport() { + Yaml yaml = new Yaml(); + try { + yaml.load("---\n!!org.yaml.snakeyaml.issues.issue145.AbstractThing { id: QQQ }"); + fail("Instances for abstract classes cannot be created"); + } catch (Exception e) { + assertTrue(e.toString().contains("line 2, column 1")); - public void testCompleteThing() { - Yaml yaml = new Yaml(); - CompleteThing thing = (CompleteThing) yaml - .load("---\n!!org.yaml.snakeyaml.issues.issue145.CompleteThing { id: QQQ }"); - assertEquals("QQQ", thing.getId()); + String tag = "tag:yaml.org,2002:org.yaml.snakeyaml.issues.issue145.AbstractThing"; + String expectedError = + String.format("Can't create an instance for %s\n" + " in 'string', line 2, column 1:\n" + + " !!org.yaml.snakeyaml.issues.issu ... \n" + " ^\n", tag); + + assertEquals(expectedError, e.getMessage()); } + } + + public void testCompleteThing() { + Yaml yaml = new Yaml(); + CompleteThing thing = + yaml.load("---\n!!org.yaml.snakeyaml.issues.issue145.CompleteThing { id: QQQ }"); + assertEquals("QQQ", thing.getId()); + } - public void testWrongParameter() { - Yaml yaml = new Yaml(); - try { - yaml.load("---\n!!org.yaml.snakeyaml.issues.issue145.CompleteThing { id2: QQQ }"); - fail("Invalid parameter"); - } catch (Exception e) { - assertTrue("The error should ponit to QQQ.", e.toString().contains("line 2, column 59")); - } + public void testWrongParameter() { + Yaml yaml = new Yaml(); + try { + yaml.load("---\n!!org.yaml.snakeyaml.issues.issue145.CompleteThing { id2: QQQ }"); + fail("Invalid parameter"); + } catch (Exception e) { + assertTrue("The error should ponit to QQQ.", e.toString().contains("line 2, column 59")); } -}
\ No newline at end of file + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue147/PrintableTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue147/PrintableTest.java index a534b495..b96d8efa 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue147/PrintableTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue147/PrintableTest.java @@ -1,29 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue147; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class PrintableTest extends TestCase { - // http://code.google.com/p/snakeyaml/issues/detail?id=147 - public void testFFFD() { - Yaml yaml = new Yaml(); - String fffd = (String) yaml.load(yaml.dump("\uFFFD")); - assertEquals("\uFFFD", fffd); - } -}
\ No newline at end of file + + // http://code.google.com/p/snakeyaml/issues/detail?id=147 + public void testFFFD() { + Yaml yaml = new Yaml(); + String fffd = yaml.load(yaml.dump("\uFFFD")); + assertEquals("\uFFFD", fffd); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue148/PrintableUnicodeTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue148/PrintableUnicodeTest.java index 0fa9322b..9a0b7afd 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue148/PrintableUnicodeTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue148/PrintableUnicodeTest.java @@ -1,177 +1,180 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue148; import java.util.Formatter; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.ScalarStyle; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.reader.ReaderException; public class PrintableUnicodeTest extends TestCase { - public void testFFFD() { - Yaml yaml = createYaml(); - String fffd = yaml.dump("\uFFFD"); - assertEquals("\"\\ufffd\"\n", fffd); - } - public void testSerialization() { - // test serialization of all Unicode codepoints - Yaml yaml = createYaml(); - for (int c = Character.MIN_VALUE; c <= Character.MAX_VALUE; c++) { - String original = Character.toString((char) c); - String serialized = yaml.dump(original); + public void testFFFD() { + Yaml yaml = createYaml(); + String fffd = yaml.dump("\uFFFD"); + assertEquals("\"\\ufffd\"\n", fffd); + } - // "On output, a YAML processor must only produce these acceptable - // characters, - // and should also escape all non-printable Unicode characters." - for (int i = 0; i < serialized.length(); i++) { - int cp = (int) serialized.charAt(i); - if (!isAcceptable(cp)) - fail(String.format( - "U+%04x: Serialization produced result with unacceptable U+%04x\n", c, - cp)); - if (!isPrintable(cp)) - fail(String.format( - "U+%04x: Serialization produced result with nonprintable U+%04x\n", c, - cp)); - } - } - } + public void testSerialization() { + // test serialization of valid Unicode BMP codepoints + Yaml yaml = createYaml(); + for (int c = Character.MIN_VALUE; c <= Character.MAX_VALUE; c++) { + if (Character.isHighSurrogate((char) c) || Character.isLowSurrogate((char) c)) { + continue; + } - public void testDeserialization() { - // test deserialization of non-escaped codepoints - for (int c = Character.MIN_VALUE; c <= Character.MAX_VALUE; c++) { - // ignore breaks, which have special meaning - if (c == 0x0A || c == 0x0D || c == 0x85 || c == 0x2028 || c == 0x2029) - continue; - if (!isAcceptable(c) || c == 0x27) - continue; - String expected = Character.toString((char) c); - String serialized = "'" + expected + "'"; + String original = Character.toString((char) c); + String serialized = yaml.dump(original); - String result; - try { - result = new Yaml().load(serialized).toString(); - } catch (ReaderException e) { - fail(String - .format("U+%04x: Deserialization threw ReaderException for an acceptable character\n", - c)); - continue; - } - if (!result.equals(expected)) - fail(String.format("U+%04x: Deserialization incorrect: %s\n", c, hexdump(result))); + // "On output, a YAML processor must only produce these acceptable + // characters, + // and should also escape all non-printable Unicode characters." + for (int i = 0; i < serialized.length(); i++) { + int cp = serialized.charAt(i); + if (!isAcceptable(cp)) { + fail(String.format("U+%04x: Serialization produced result with unacceptable U+%04x\n", c, + cp)); + } + if (!isPrintable(cp)) { + fail(String.format("U+%04x: Serialization produced result with nonprintable U+%04x\n", c, + cp)); } + } } + } - public void testDeserialization2() { - // test deserialization of escaped codepoints - // "Any such characters must be presented using escape sequences." - for (int c = Character.MIN_VALUE; c <= Character.MAX_VALUE; c++) { - String expected = Character.toString((char) c); - String serialized = String.format("\"\\u%04x\"", c); + public void testDeserialization() { + // test deserialization of non-escaped codepoints + for (int c = Character.MIN_VALUE; c <= Character.MAX_VALUE; c++) { + // ignore breaks, which have special meaning + if (c == 0x0A || c == 0x0D || c == 0x85 || c == 0x2028 || c == 0x2029) { + continue; + } + if (!isAcceptable(c) || c == 0x27) { + continue; + } + String expected = Character.toString((char) c); + String serialized = "'" + expected + "'"; - String result; - try { - result = new Yaml().load(serialized).toString(); - } catch (ReaderException e) { - fail(String - .format("U+%04x: Deserialization threw ReaderException for an acceptable escaped character\n", - c)); - continue; - } - if (!result.equals(expected)) - fail(String.format("U+%04x: Deserialization of escaped character incorrect: %s\n", - c, hexdump(result))); - } + String result; + try { + result = new Yaml().load(serialized).toString(); + } catch (ReaderException e) { + fail(String.format( + "U+%04x: Deserialization threw ReaderException for an acceptable character\n", c)); + continue; + } + if (!result.equals(expected)) { + fail(String.format("U+%04x: Deserialization incorrect: %s\n", c, hexdump(result))); + } } + } - private Yaml createYaml() { - DumperOptions options = new DumperOptions(); - options.setAllowUnicode(false); - options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); - return new Yaml(options); - } + public void testDeserialization2() { + // test deserialization of escaped codepoints + // "Any such characters must be presented using escape sequences." + for (int c = Character.MIN_VALUE; c <= Character.MAX_VALUE; c++) { + String expected = Character.toString((char) c); + String serialized = String.format("\"\\u%04x\"", c); - /** - * Test whether a character is printable, according to the YAML spec. - * ('c-printable') - */ - public static boolean isPrintable(int c) { - return c == 0x9 || c == 0xA || c == 0xD || (c >= 0x20 && c <= 0x7E) // 8 - // bit - || c == 0x85 || (c >= 0xA0 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) // 16 - // bit - || (c >= 0x10000 && c <= 0x10FFFF); // 32 bit + String result; + try { + result = new Yaml().load(serialized).toString(); + } catch (ReaderException e) { + fail(String.format( + "U+%04x: Deserialization threw ReaderException for an acceptable escaped character\n", + c)); + continue; + } + if (!result.equals(expected)) { + fail(String.format("U+%04x: Deserialization of escaped character incorrect: %s\n", c, + hexdump(result))); + } } + } + + private Yaml createYaml() { + DumperOptions options = new DumperOptions(); + options.setAllowUnicode(false); + options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); + return new Yaml(options); + } - /** - * "On input, a YAML processor must accept all printable ASCII characters, - * the space, tab, line break, and all Unicode characters beyond #x9F. On - * output, a YAML processor must only produce these acceptable characters, - * and should also escape all non-printable Unicode characters. The allowed - * character range explicitly excludes the surrogate block #xD800-#xDFFF, - * DEL #x7F, the C0 control block #x0-#x1F (except for #x9, #xA, and #xD), - * the C1 control block #x80-#x9F, #xFFFE, and #xFFFF." - */ - public static boolean isAcceptable(int c) { - return (c >= 0x20 && c <= 0x7e // accept all printable ASCII characters, - // the space, - || c == 0x09 // tab, - || c == 0x0A || c == 0x0D || c == 0x85 || c == 0x2028 || c == 0x2029 // line - // break, + /** + * Test whether a character is printable, according to the YAML spec. ('c-printable') + */ + public static boolean isPrintable(int c) { + return c == 0x9 || c == 0xA || c == 0xD || (c >= 0x20 && c <= 0x7E) // 8 + // bit + || c == 0x85 || (c >= 0xA0 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) // 16 + // bit + || (c >= 0x10000 && c <= 0x10FFFF); // 32 bit + } + + /** + * "On input, a YAML processor must accept all printable ASCII characters, the space, tab, line + * break, and all Unicode characters beyond #x9F. On output, a YAML processor must only produce + * these acceptable characters, and should also escape all non-printable Unicode characters. The + * allowed character range explicitly excludes the surrogate block #xD800-#xDFFF, DEL #x7F, the C0 + * control block #x0-#x1F (except for #x9, #xA, and #xD), the C1 control block #x80-#x9F, #xFFFE, + * and #xFFFF." + */ + public static boolean isAcceptable(int c) { + return (c >= 0x20 && c <= 0x7e // accept all printable ASCII characters, + // the space, + || c == 0x09 // tab, + || c == 0x0A || c == 0x0D || c == 0x85 || c == 0x2028 || c == 0x2029 // line + // break, || isUnicodeCharacter(c) && c >= 0x9F // and all Unicode characters - // beyond #x9F - ) && !( // The allowed character range explicitly excludes - c >= 0xD800 && c <= 0xDFFF // the surrogate block #xD800-#xDFFF - || c == 0x7f // DEL #x7F, - || c <= 0x1F && !(c == 0x09 || c == 0x0A || c == 0x0D) // the - // C0 - // control - // block - // #x0-#x1F - // (except - // for - // #x9, - // #xA, - // and - // #xD), - || c >= 0x80 && c <= 0x9F // the C1 control block - // #x80-#x9F, - || c == 0xFFFE // #xFFFE, - || c == 0xFFFF // and #xFFFF. - ); - } + // beyond #x9F + ) && !( // The allowed character range explicitly excludes + c >= 0xD800 && c <= 0xDFFF // the surrogate block #xD800-#xDFFF + || c == 0x7f // DEL #x7F, + || c <= 0x1F && !(c == 0x09 || c == 0x0A || c == 0x0D) // the + // C0 + // control + // block + // #x0-#x1F + // (except + // for + // #x9, + // #xA, + // and + // #xD), + || c >= 0x80 && c <= 0x9F // the C1 control block + // #x80-#x9F, + || c == 0xFFFE // #xFFFE, + || c == 0xFFFF // and #xFFFF. + ); + } - /** - * Tests whether a codepoint is a designated Unicode noncharacter or not. - */ - public static boolean isUnicodeCharacter(int c) { - int plane = c / 0x10000; - return !(c >= 0xFDD0 && c <= 0xFDEF) && (plane <= 16 && (c & 0xFFFE) != 0xFFFE); - } + /** + * Tests whether a codepoint is a designated Unicode noncharacter or not. + */ + public static boolean isUnicodeCharacter(int c) { + int plane = c / 0x10000; + return !(c >= 0xFDD0 && c <= 0xFDEF) && (plane <= 16 && (c & 0xFFFE) != 0xFFFE); + } - public static String hexdump(String input) { - StringBuilder result = new StringBuilder(); - Formatter formatter = new Formatter(result); - for (int i = 0; i < input.length(); i++) - formatter.format("%02x ", (int) input.charAt(i)); - return result.toString(); + public static String hexdump(String input) { + StringBuilder result = new StringBuilder(); + Formatter formatter = new Formatter(result); + for (int i = 0; i < input.length(); i++) { + formatter.format("%02x ", (int) input.charAt(i)); } -}
\ No newline at end of file + return result.toString(); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue149/ComponentBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue149/ComponentBean.java index 97f7d1ed..54fa6f28 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue149/ComponentBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue149/ComponentBean.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue149; public class ComponentBean { - private int property1; - private String property2; - public int getProperty1() { - return property1; - } + private int property1; + private String property2; - public void setProperty1(int property1) { - this.property1 = property1; - } + public int getProperty1() { + return property1; + } - public String getProperty2() { - return property2; - } + public void setProperty1(int property1) { + this.property1 = property1; + } - public void setProperty2(String property2) { - this.property2 = property2; - } + public String getProperty2() { + return property2; + } + + public void setProperty2(String property2) { + this.property2 = property2; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue149/GlobalDirectivesTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue149/GlobalDirectivesTest.java index 6c2b5f41..67ee4de3 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue149/GlobalDirectivesTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue149/GlobalDirectivesTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue149; import java.util.Iterator; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -26,54 +22,55 @@ import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.Tag; public class GlobalDirectivesTest extends TestCase { - public void testOneDocument() { - String input = Util.getLocalResource("issues/issue149-one-document.yaml"); - // System.out.println(input); - Constructor constr = new Constructor(); - TypeDescription description = new TypeDescription(ComponentBean.class, new Tag( - "tag:ualberta.ca,2012:29")); - constr.addTypeDescription(description); - Yaml yaml = new Yaml(constr); - Iterator<Object> parsed = yaml.loadAll(input).iterator(); - ComponentBean bean = (ComponentBean) parsed.next(); - assertEquals(0, bean.getProperty1()); - assertEquals("aaa", bean.getProperty2()); - assertFalse(parsed.hasNext()); - } - public void testDirectives() { - String input = Util.getLocalResource("issues/issue149-losing-directives.yaml"); - // System.out.println(input); - Constructor constr = new Constructor(); - TypeDescription description = new TypeDescription(ComponentBean.class, new Tag( - "tag:ualberta.ca,2012:" + 29)); - constr.addTypeDescription(description); - Yaml yaml = new Yaml(constr); - Iterator<Object> parsed = yaml.loadAll(input).iterator(); - ComponentBean bean1 = (ComponentBean) parsed.next(); - assertEquals(0, bean1.getProperty1()); - assertEquals("aaa", bean1.getProperty2()); - ComponentBean bean2 = (ComponentBean) parsed.next(); - assertEquals(3, bean2.getProperty1()); - assertEquals("bbb", bean2.getProperty2()); - assertFalse(parsed.hasNext()); - } + public void testOneDocument() { + String input = Util.getLocalResource("issues/issue149-one-document.yaml"); + // System.out.println(input); + Constructor constr = new Constructor(); + TypeDescription description = + new TypeDescription(ComponentBean.class, new Tag("tag:ualberta.ca,2012:29")); + constr.addTypeDescription(description); + Yaml yaml = new Yaml(constr); + Iterator<Object> parsed = yaml.loadAll(input).iterator(); + ComponentBean bean = (ComponentBean) parsed.next(); + assertEquals(0, bean.getProperty1()); + assertEquals("aaa", bean.getProperty2()); + assertFalse(parsed.hasNext()); + } + + public void testDirectives() { + String input = Util.getLocalResource("issues/issue149-losing-directives.yaml"); + // System.out.println(input); + Constructor constr = new Constructor(); + TypeDescription description = + new TypeDescription(ComponentBean.class, new Tag("tag:ualberta.ca,2012:" + 29)); + constr.addTypeDescription(description); + Yaml yaml = new Yaml(constr); + Iterator<Object> parsed = yaml.loadAll(input).iterator(); + ComponentBean bean1 = (ComponentBean) parsed.next(); + assertEquals(0, bean1.getProperty1()); + assertEquals("aaa", bean1.getProperty2()); + ComponentBean bean2 = (ComponentBean) parsed.next(); + assertEquals(3, bean2.getProperty1()); + assertEquals("bbb", bean2.getProperty2()); + assertFalse(parsed.hasNext()); + } - public void testDirectives2() { - String input = Util.getLocalResource("issues/issue149-losing-directives-2.yaml"); - // System.out.println(input); - Constructor constr = new Constructor(); - TypeDescription description = new TypeDescription(ComponentBean.class, new Tag( - "tag:ualberta.ca,2012:" + 29)); - constr.addTypeDescription(description); - Yaml yaml = new Yaml(constr); - Iterator<Object> parsed = yaml.loadAll(input).iterator(); - ComponentBean bean1 = (ComponentBean) parsed.next(); - assertEquals(0, bean1.getProperty1()); - assertEquals("aaa", bean1.getProperty2()); - ComponentBean bean2 = (ComponentBean) parsed.next(); - assertEquals(3, bean2.getProperty1()); - assertEquals("bbb", bean2.getProperty2()); - assertFalse(parsed.hasNext()); - } -}
\ No newline at end of file + public void testDirectives2() { + String input = Util.getLocalResource("issues/issue149-losing-directives-2.yaml"); + // System.out.println(input); + Constructor constr = new Constructor(); + TypeDescription description = + new TypeDescription(ComponentBean.class, new Tag("tag:ualberta.ca,2012:" + 29)); + constr.addTypeDescription(description); + Yaml yaml = new Yaml(constr); + Iterator<Object> parsed = yaml.loadAll(input).iterator(); + ComponentBean bean1 = (ComponentBean) parsed.next(); + assertEquals(0, bean1.getProperty1()); + assertEquals("aaa", bean1.getProperty2()); + ComponentBean bean2 = (ComponentBean) parsed.next(); + assertEquals(3, bean2.getProperty1()); + assertEquals("bbb", bean2.getProperty2()); + assertFalse(parsed.hasNext()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue150/Car.java b/src/test/java/org/yaml/snakeyaml/issues/issue150/Car.java index 1973d9d1..b602bd98 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue150/Car.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue150/Car.java @@ -1,47 +1,45 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue150; import java.util.Collection; /** - * + * * @author tturki - * + * */ public class Car { - private String plate; - private Collection<Wheel> wheels; - public Car() { - } + private String plate; + private Collection<Wheel> wheels; + + public Car() {} - public String getPlate() { - return plate; - } + public String getPlate() { + return plate; + } - public void setPlate(String plate) { - this.plate = plate; - } + public void setPlate(String plate) { + this.plate = plate; + } - public Collection<Wheel> getWheels() { - return wheels; - } + public Collection<Wheel> getWheels() { + return wheels; + } - public void setWheels(Collection<Wheel> wheels) { - this.wheels = wheels; - } -}
\ No newline at end of file + public void setWheels(Collection<Wheel> wheels) { + this.wheels = wheels; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue150/Wheel.java b/src/test/java/org/yaml/snakeyaml/issues/issue150/Wheel.java index bae16372..dbd767f4 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue150/Wheel.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue150/Wheel.java @@ -1,31 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue150; public class Wheel { - private Integer id; - public Wheel() { - } + private Integer id; - public Integer getId() { - return id; - } + public Wheel() {} - public void setId(Integer id) { - this.id = id; - } -}
\ No newline at end of file + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue150/YamlLoadAsIssueTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue150/YamlLoadAsIssueTest.java index f4002d46..ea2af791 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue150/YamlLoadAsIssueTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue150/YamlLoadAsIssueTest.java @@ -1,32 +1,26 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue150; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.regex.Pattern; - import org.junit.Before; import org.junit.Test; import org.yaml.snakeyaml.Yaml; @@ -41,101 +35,102 @@ import org.yaml.snakeyaml.nodes.Tag; public class YamlLoadAsIssueTest { - private StringBuilder doc; - - @Before - public void setUp() { - doc = new StringBuilder(); - line("!car"); - line("plate: 12-XP-F4"); - line("wheels:"); - line("- w#1"); - line("- w#2"); - line("- w#3"); - line("- w#4"); + private StringBuilder doc; + + @Before + public void setUp() { + doc = new StringBuilder(); + line("!car"); + line("plate: 12-XP-F4"); + line("wheels:"); + line("- w#1"); + line("- w#2"); + line("- w#3"); + line("- w#4"); + } + + private StringBuilder line(String text) { + return doc.append(text).append('\n'); + } + + @Test + public void loadConstructsDocumentCorrectly() { + Yaml yaml = yaml(); + Object result = yaml.load(reader()); + assertNotNull(result); + assertEquals(Car.class, result.getClass()); + assertEquals("12-XP-F4", ((Car) result).getPlate()); + assertEquals(4, ((Car) result).getWheels().size()); + } + + private Yaml yaml() { + Yaml yaml = new Yaml(new MyConstructor()); + yaml.addImplicitResolver(new Tag("!wheel"), Pattern.compile("w#\\d+"), "w"); + return yaml; + } + + @Test + public void ignoreImplicitTag() { + Yaml yaml = yaml(); + Car car = yaml.loadAs(reader(), Car.class); + assertNotNull(car); + assertEquals("12-XP-F4", car.getPlate()); + ArrayList<Wheel> wheels = new ArrayList<Wheel>(car.getWheels()); + assertEquals(4, wheels.size()); + for (int i = 0; i < wheels.size(); i++) { + assertEquals(wheels.get(i).getId(), Integer.valueOf(i + 1)); } + } - private StringBuilder line(String text) { - return doc.append(text).append('\n'); - } + private Reader reader() { + return new StringReader(doc.toString()); + } - @Test - public void loadConstructsDocumentCorrectly() { - Yaml yaml = yaml(); - Object result = yaml.load(reader()); - assertNotNull(result); - assertEquals(Car.class, result.getClass()); - assertEquals("12-XP-F4", ((Car) result).getPlate()); - assertEquals(4, ((Car) result).getWheels().size()); - } - - private Yaml yaml() { - Yaml yaml = new Yaml(new MyConstructor()); - yaml.addImplicitResolver(new Tag("!wheel"), Pattern.compile("w#\\d+"), "w"); - return yaml; - } + private class MyConstructor extends Constructor { - @Test - public void ignoreImplicitTag() { - Yaml yaml = yaml(); - Car car = yaml.loadAs(reader(), Car.class); - assertNotNull(car); - assertEquals("12-XP-F4", car.getPlate()); - ArrayList<Wheel> wheels = new ArrayList<Wheel>(car.getWheels()); - assertEquals(4, wheels.size()); - for (int i = 0; i < wheels.size(); i++) { - assertEquals(wheels.get(i).getId(), Integer.valueOf(i + 1)); - } + public MyConstructor() { + yamlConstructors.put(new Tag("!car"), new ConstructCar()); + yamlConstructors.put(new Tag("!wheel"), new ConstructWheel()); } - private Reader reader() { - return new StringReader(doc.toString()); + private String toScalarString(Node node) { + return constructScalar((ScalarNode) node); } - private class MyConstructor extends Constructor { - public MyConstructor() { - yamlConstructors.put(new Tag("!car"), new ConstructCar()); - yamlConstructors.put(new Tag("!wheel"), new ConstructWheel()); - } - - private String toScalarString(Node node) { - return (String) constructScalar((ScalarNode) node); + private class ConstructCar extends AbstractConstruct { + + @SuppressWarnings("unchecked") + public Car construct(Node node) { + Car car = new Car(); + MappingNode mapping = (MappingNode) node; + List<NodeTuple> list = mapping.getValue(); + for (NodeTuple tuple : list) { + String field = toScalarString(tuple.getKeyNode()); + if ("plate".equals(field)) { + car.setPlate(toScalarString(tuple.getValueNode())); + } + if ("wheels".equals(field)) { + SequenceNode snode = (SequenceNode) tuple.getValueNode(); + List<Wheel> wheels = (List<Wheel>) constructSequence(snode); + car.setWheels(wheels); + } } + return car; + } + } - private class ConstructCar extends AbstractConstruct { - - @SuppressWarnings("unchecked") - public Car construct(Node node) { - Car car = new Car(); - MappingNode mapping = (MappingNode) node; - List<NodeTuple> list = mapping.getValue(); - for (NodeTuple tuple : list) { - String field = toScalarString(tuple.getKeyNode()); - if ("plate".equals(field)) { - car.setPlate(toScalarString(tuple.getValueNode())); - } - if ("wheels".equals(field)) { - SequenceNode snode = (SequenceNode) tuple.getValueNode(); - List<Wheel> wheels = (List<Wheel>) constructSequence(snode); - car.setWheels(wheels); - } - } - return car; - } - } + private class ConstructWheel extends AbstractConstruct { - private class ConstructWheel extends AbstractConstruct { - - public Wheel construct(Node node) { - Wheel w = null; - String strValue = toScalarString(node); - if (strValue != null && strValue.length() > 2) { - strValue = strValue.trim().substring(2); - w = new Wheel(); - w.setId(Integer.valueOf(strValue)); - } - return w; - } + public Wheel construct(Node node) { + Wheel w = null; + String strValue = toScalarString(node); + if (strValue != null && strValue.length() > 2) { + strValue = strValue.trim().substring(2); + w = new Wheel(); + w.setId(Integer.valueOf(strValue)); } + return w; + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue151/EscapedUnicodeTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue151/EscapedUnicodeTest.java index 86a88fcd..e3500af3 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue151/EscapedUnicodeTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue151/EscapedUnicodeTest.java @@ -1,36 +1,33 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue151; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class EscapedUnicodeTest extends TestCase { - public void testUnicode() { - Yaml yaml = new Yaml(); - // http://www.tutorialspoint.com/html/ascii_table_lookup.htm - String str = (String) yaml.load("\"\\xC3\\xA4\""); - assertEquals("2 escape sequences must be converted to 2 characters.", "รยค", str); - } + public void testUnicode() { + Yaml yaml = new Yaml(); + // http://www.tutorialspoint.com/html/ascii_table_lookup.htm + String str = yaml.load("\"\\xC3\\xA4\""); + assertEquals("2 escape sequences must be converted to 2 characters.", "รยค", str); + } - public void testUnicode2() { - Yaml yaml = new Yaml(); - String str = (String) yaml.load("\"Acetylsalicyls\\xE4ure\""); - assertEquals("E4 -> รค", "Acetylsalicylsรคure", str); - } + public void testUnicode2() { + Yaml yaml = new Yaml(); + String str = yaml.load("\"Acetylsalicyls\\xE4ure\""); + assertEquals("E4 -> รค", "Acetylsalicylsรคure", str); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue154/MissingPropertyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue154/MissingPropertyTest.java index 6a4c5146..431643a6 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue154/MissingPropertyTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue154/MissingPropertyTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue154; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.error.YAMLException; @@ -24,62 +21,62 @@ import org.yaml.snakeyaml.representer.Representer; public class MissingPropertyTest extends TestCase { - private Yaml yaml; + private Yaml yaml; - public void setUp() { - yaml = new Yaml(); - } + public void setUp() { + yaml = new Yaml(); + } - /** - * A normal scalar property should work fine. - */ - public void testPublicField() throws Exception { - String doc = "hello: 5"; - TestBean bean = yaml.loadAs(doc, TestBean.class); - assertNotNull(bean); - assertEquals(5, bean.hello); - } + /** + * A normal scalar property should work fine. + */ + public void testPublicField() throws Exception { + String doc = "hello: 5"; + TestBean bean = yaml.loadAs(doc, TestBean.class); + assertNotNull(bean); + assertEquals(5, bean.hello); + } - /** - * By default, unknown fields should throw a YAMLException. - */ - public void testUnknownField() throws Exception { - try { - String doc = "goodbye: 10"; - yaml.loadAs(doc, TestBean.class); - } catch (YAMLException e) { - assertTrue(e.getMessage().contains("Cannot create property=goodbye")); - } + /** + * By default, unknown fields should throw a YAMLException. + */ + public void testUnknownField() throws Exception { + try { + String doc = "goodbye: 10"; + yaml.loadAs(doc, TestBean.class); + } catch (YAMLException e) { + assertTrue(e.getMessage().contains("Cannot create property=goodbye")); } + } - /** - * A new method setSkipMissingProperties(boolean) was added to configure - * whether missing properties should throw a YAMLException (the default) or - * simply show a warning. The default is false. - */ - public void testSkipMissingProperties() throws Exception { - Representer representer = new Representer(); - representer.getPropertyUtils().setSkipMissingProperties(true); - yaml = new Yaml(new Constructor(), representer); - String doc = "goodbye: 10\nhello: 5\nfizz: [1]"; - TestBean bean = yaml.loadAs(doc, TestBean.class); - assertNotNull(bean); - assertEquals(5, bean.hello); - } + /** + * A new method setSkipMissingProperties(boolean) was added to configure whether missing + * properties should throw a YAMLException (the default) or simply show a warning. The default is + * false. + */ + public void testSkipMissingProperties() throws Exception { + Representer representer = new Representer(); + representer.getPropertyUtils().setSkipMissingProperties(true); + yaml = new Yaml(new Constructor(), representer); + String doc = "goodbye: 10\nhello: 5\nfizz: [1]"; + TestBean bean = yaml.loadAs(doc, TestBean.class); + assertNotNull(bean); + assertEquals(5, bean.hello); + } - /** - * The default for setSkipMissingProperties(boolean) is false; this just - * ensures it works if set manually. - */ - public void testNoSkipMissingProperties() throws Exception { - try { - Representer representer = new Representer(); - representer.getPropertyUtils().setSkipMissingProperties(false); - yaml = new Yaml(new Constructor(), representer); - String doc = "goodbye: 10"; - yaml.loadAs(doc, TestBean.class); - } catch (YAMLException e) { - assertTrue(e.getMessage().contains("Cannot create property=goodbye")); - } + /** + * The default for setSkipMissingProperties(boolean) is false; this just ensures it works if set + * manually. + */ + public void testNoSkipMissingProperties() throws Exception { + try { + Representer representer = new Representer(); + representer.getPropertyUtils().setSkipMissingProperties(false); + yaml = new Yaml(new Constructor(), representer); + String doc = "goodbye: 10"; + yaml.loadAs(doc, TestBean.class); + } catch (YAMLException e) { + assertTrue(e.getMessage().contains("Cannot create property=goodbye")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue154/TestBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue154/TestBean.java index 264b58b0..522d210a 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue154/TestBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue154/TestBean.java @@ -1,20 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue154; public class TestBean { - public int hello; + + public int hello; } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue155/BinaryTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue155/BinaryTest.java index f5c5ef29..21323f83 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue155/BinaryTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue155/BinaryTest.java @@ -1,34 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue155; +import java.nio.charset.StandardCharsets; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class BinaryTest extends TestCase { - public void testBinaryString() throws Exception { - String data = "\u2666"; - byte[] bytes = data.getBytes("UTF-8"); - String inconsistentString = new String(bytes, "ISO-8859-1"); - Yaml yaml = new Yaml(); - String payload = yaml.dump(inconsistentString); - // System.out.println("payload: '" + payload + "'"); - String loaded = new String((byte[]) yaml.load(payload), "UTF-8"); - assertEquals(inconsistentString, loaded); - } + public void testBinaryString() throws Exception { + String data = "\u2666"; + byte[] bytes = data.getBytes(StandardCharsets.UTF_8); + String inconsistentString = new String(bytes, StandardCharsets.ISO_8859_1); + Yaml yaml = new Yaml(); + String payload = yaml.dump(inconsistentString); + // System.out.println("payload: '" + payload + "'"); + String loaded = new String((byte[]) yaml.load(payload), StandardCharsets.UTF_8); + assertEquals(inconsistentString, loaded); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue163/LinearScalaTralingTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue163/LinearScalaTralingTest.java index 6210f924..598a1ec8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue163/LinearScalaTralingTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue163/LinearScalaTralingTest.java @@ -1,43 +1,39 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue163; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class LinearScalaTralingTest extends TestCase { - public void testClipChomping() throws Exception { - String data = "testnode: |\n This is line 1\n This is line 2\n"; - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map<String, String> payload = (Map<String, String>) yaml.load(data); - assertEquals("This is line 1\nThis is line 2\n", payload.get("testnode")); - } + public void testClipChomping() throws Exception { + String data = "testnode: |\n This is line 1\n This is line 2\n"; + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<String, String> payload = yaml.load(data); + assertEquals("This is line 1\nThis is line 2\n", payload.get("testnode")); + } - public void testStripChomping() throws Exception { - // mind the trailing '|-' to indicate strip chomping - String data = "testnode: |-\n This is line 1\n This is line 2\n"; - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map<String, String> payload = (Map<String, String>) yaml.load(data); - assertEquals("No traling line break expected.", "This is line 1\nThis is line 2", - payload.get("testnode")); - } + public void testStripChomping() throws Exception { + // mind the trailing '|-' to indicate strip chomping + String data = "testnode: |-\n This is line 1\n This is line 2\n"; + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<String, String> payload = yaml.load(data); + assertEquals("No traling line break expected.", "This is line 1\nThis is line 2", + payload.get("testnode")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue171/ClassWithGenericMap.java b/src/test/java/org/yaml/snakeyaml/issues/issue171/ClassWithGenericMap.java index 5cfe7cc5..15ac3712 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue171/ClassWithGenericMap.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue171/ClassWithGenericMap.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue171; @@ -20,5 +18,7 @@ import java.util.HashMap; import java.util.Map; class ClassWithGenericMap { - public final Map<String, Collection<Integer>> services = new HashMap<String, Collection<Integer>>(); -}
\ No newline at end of file + + public final Map<String, Collection<Integer>> services = + new HashMap<String, Collection<Integer>>(); +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue171/CustomRepresenter.java b/src/test/java/org/yaml/snakeyaml/issues/issue171/CustomRepresenter.java index 093f90a9..976d9ed1 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue171/CustomRepresenter.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue171/CustomRepresenter.java @@ -1,34 +1,35 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue171; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; class CustomRepresenter extends Representer { - public CustomRepresenter() { - this.representers.put(ClassWithGenericMap.class, new RepresentClassX()); - } - private class RepresentClassX implements Represent { - public Node representData(Object data) { - ClassWithGenericMap classX = (ClassWithGenericMap) data; - return representMapping(Tag.MAP, classX.services, false); - } + public CustomRepresenter() { + this.representers.put(ClassWithGenericMap.class, new RepresentClassX()); + } + + private class RepresentClassX implements Represent { + + public Node representData(Object data) { + ClassWithGenericMap classX = (ClassWithGenericMap) data; + return representMapping(Tag.MAP, classX.services, DumperOptions.FlowStyle.BLOCK); } -}
\ No newline at end of file + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue171/GenericExtendsObjectTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue171/GenericExtendsObjectTest.java index 4ff2a491..9dc67fad 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue171/GenericExtendsObjectTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue171/GenericExtendsObjectTest.java @@ -1,36 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue171; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class GenericExtendsObjectTest extends TestCase { - public void testNoCompilationError() throws Exception { - Yaml yaml = new Yaml(new CustomRepresenter()); - ClassWithGenericMap map = new ClassWithGenericMap(); - List<Integer> list = new ArrayList<Integer>(); - list.add(7); - map.services.put("wow", list); - String output = yaml.dump(map); - assertEquals("wow: [7]\n", output); - } + public void testNoCompilationError() throws Exception { + Yaml yaml = new Yaml(new CustomRepresenter()); + ClassWithGenericMap map = new ClassWithGenericMap(); + List<Integer> list = new ArrayList<Integer>(); + list.add(7); + map.services.put("wow", list); + String output = yaml.dump(map); + assertEquals("wow: [7]\n", output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue173/RecursiveAnchorTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue173/RecursiveAnchorTest.java index 4571d1ce..a712c169 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue173/RecursiveAnchorTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue173/RecursiveAnchorTest.java @@ -1,54 +1,50 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue173; import java.util.HashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.representer.Representer; public class RecursiveAnchorTest extends TestCase { - public void testWithoutCustomStyle() throws Exception { - Map<String, Map<String, Object>> rootMap = new HashMap<String, Map<String, Object>>(); - Map<String, Object> enclosedMap = new HashMap<String, Object>(); - enclosedMap.put("world", "test"); - rootMap.put("test", enclosedMap); - Yaml yaml = new Yaml(); - String output = yaml.dump(rootMap); - assertEquals("test: {world: test}\n", output); - } - - public void testWithBlockStyle() throws Exception { - Map<String, Map<String, Object>> rootMap = new HashMap<String, Map<String, Object>>(); - Map<String, Object> enclosedMap = new HashMap<String, Object>(); - enclosedMap.put("world", "test"); - rootMap.put("test", enclosedMap); - - DumperOptions yamlOptions = new DumperOptions(); - yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - - Representer yamlRepresenter = new Representer(); - - Yaml yaml = new Yaml(yamlRepresenter, yamlOptions); - String output = yaml.dump(rootMap); - assertEquals("test:\n world: test\n", output); - } + public void testWithoutCustomStyle() throws Exception { + Map<String, Map<String, Object>> rootMap = new HashMap<String, Map<String, Object>>(); + Map<String, Object> enclosedMap = new HashMap<String, Object>(); + enclosedMap.put("world", "test"); + rootMap.put("test", enclosedMap); + Yaml yaml = new Yaml(); + String output = yaml.dump(rootMap); + assertEquals("test: {world: test}\n", output); + } + + public void testWithBlockStyle() throws Exception { + Map<String, Map<String, Object>> rootMap = new HashMap<String, Map<String, Object>>(); + Map<String, Object> enclosedMap = new HashMap<String, Object>(); + enclosedMap.put("world", "test"); + rootMap.put("test", enclosedMap); + + DumperOptions yamlOptions = new DumperOptions(); + yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + Representer yamlRepresenter = new Representer(); + + Yaml yaml = new Yaml(yamlRepresenter, yamlOptions); + String output = yaml.dump(rootMap); + assertEquals("test:\n world: test\n", output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue176/SingleQuoteTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue176/SingleQuoteTest.java index be5a0404..75297d07 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue176/SingleQuoteTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue176/SingleQuoteTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue176; import java.util.LinkedHashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; @@ -28,36 +24,36 @@ import org.yaml.snakeyaml.representer.Representer; public class SingleQuoteTest extends TestCase { - public void testNoSingleQuoteForBlockStyle() throws Exception { - checkQuotes(true, "cows:\n steak:cow: '11'"); - } + public void testNoSingleQuoteForBlockStyle() throws Exception { + checkQuotes(true, "cows:\n steak:cow: '11'"); + } - public void testSingleQuoteForFlowStyle() throws Exception { - checkQuotes(false, "cows: {'steak:cow': '11'}"); - } + public void testSingleQuoteForFlowStyle() throws Exception { + checkQuotes(false, "cows: {'steak:cow': '11'}"); + } - private void checkQuotes(boolean isBlock, String expectation) { - DumperOptions options = new DumperOptions(); - options.setIndent(4); - if (isBlock) { - options.setDefaultFlowStyle(FlowStyle.BLOCK); - } - Representer representer = new Representer(); - - Yaml yaml = new Yaml(new SafeConstructor(), representer, options); - - LinkedHashMap<String, Object> lvl1 = new LinkedHashMap<String, Object>(); - lvl1.put("steak:cow", "11"); - LinkedHashMap<String, Object> root = new LinkedHashMap<String, Object>(); - root.put("cows", lvl1); - String output = yaml.dump(root); - assertEquals(expectation + "\n", output); - - // parse the value back - @SuppressWarnings("unchecked") - Map<String, Object> cows = (Map<String, Object>) yaml.load(output); - @SuppressWarnings("unchecked") - Map<String, String> cow = (Map<String, String>) cows.get("cows"); - assertEquals("11", cow.get("steak:cow")); + private void checkQuotes(boolean isBlock, String expectation) { + DumperOptions options = new DumperOptions(); + options.setIndent(4); + if (isBlock) { + options.setDefaultFlowStyle(FlowStyle.BLOCK); } + Representer representer = new Representer(); + + Yaml yaml = new Yaml(new SafeConstructor(), representer, options); + + LinkedHashMap<String, Object> lvl1 = new LinkedHashMap<String, Object>(); + lvl1.put("steak:cow", "11"); + LinkedHashMap<String, Object> root = new LinkedHashMap<String, Object>(); + root.put("cows", lvl1); + String output = yaml.dump(root); + assertEquals(expectation + "\n", output); + + // parse the value back + @SuppressWarnings("unchecked") + Map<String, Object> cows = yaml.load(output); + @SuppressWarnings("unchecked") + Map<String, String> cow = (Map<String, String>) cows.get("cows"); + assertEquals("11", cow.get("steak:cow")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBean.java index ea46af97..a5c7e9c5 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBean.java @@ -1,26 +1,25 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue177; public class PointBean { - public int x; - public int y; - @Override - public String toString() { - return "PointBean"; - } + public int x; + public int y; + + @Override + public String toString() { + return "PointBean"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBeanTest.java index 274cba3a..beff107d 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue177/PointBeanTest.java @@ -1,43 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue177; import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class PointBeanTest extends TestCase { - public void testNoSingleQuoteForBlockStyle() throws Exception { - String input = Util.getLocalResource("issues/issue177-1.yaml"); - try { - Yaml yaml = new Yaml(); - yaml.load(input); - fail(); - } catch (Exception e) { - assertEquals("Cannot create property=points for JavaBean=All Points\n" - + " in 'string', line 1, column 1:\n" - + " !!org.yaml.snakeyaml.issues.issu ... \n" + " ^\n" - + "Cannot create property=x for JavaBean=PointBean\n" - + " in 'string', line 7, column 5:\n" + " x: a\n" + " ^\n" - + "For input string: \"a\"\n" + " in 'string', line 7, column 8:\n" - + " x: a\n" + " ^\n" + "\n" - + " in 'string', line 3, column 3:\n" + " pt1:\n" + " ^\n", - e.getMessage()); - } + public void testNoSingleQuoteForBlockStyle() throws Exception { + String input = Util.getLocalResource("issues/issue177-1.yaml"); + try { + Yaml yaml = new Yaml(); + yaml.load(input); + fail(); + } catch (Exception e) { + assertEquals("Cannot create property=points for JavaBean=All Points\n" + + " in 'string', line 1, column 1:\n" + " !!org.yaml.snakeyaml.issues.issu ... \n" + + " ^\n" + "Cannot create property=x for JavaBean=PointBean\n" + + " in 'string', line 7, column 5:\n" + " x: a\n" + " ^\n" + + "For input string: \"a\"\n" + " in 'string', line 7, column 8:\n" + " x: a\n" + + " ^\n" + "\n" + " in 'string', line 3, column 3:\n" + " pt1:\n" + + " ^\n", e.getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue177/Points.java b/src/test/java/org/yaml/snakeyaml/issues/issue177/Points.java index e0e57c5a..6e6fa86b 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue177/Points.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue177/Points.java @@ -1,27 +1,26 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue177; import java.util.Map; public class Points { - public Map<String, PointBean> points; - @Override - public String toString() { - return "All Points"; - } + public Map<String, PointBean> points; + + @Override + public String toString() { + return "All Points"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBean.java index 691959f4..6d72f2a7 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBean.java @@ -1,21 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue182; public class InfinityFloatBean { - public float infinityFloat; - public Float infinityFloatObject; + + public float infinityFloat; + public Float infinityFloatObject; } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBeanTest.java index f589f03d..99c2a101 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue182/InfinityFloatBeanTest.java @@ -1,36 +1,33 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue182; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class InfinityFloatBeanTest extends TestCase { - public void testInfinityFloatBean() throws Exception { + public void testInfinityFloatBean() throws Exception { - InfinityFloatBean bean = new InfinityFloatBean(); - bean.infinityFloat = Float.POSITIVE_INFINITY; - bean.infinityFloatObject = Float.POSITIVE_INFINITY; + InfinityFloatBean bean = new InfinityFloatBean(); + bean.infinityFloat = Float.POSITIVE_INFINITY; + bean.infinityFloatObject = Float.POSITIVE_INFINITY; - Yaml yaml = new Yaml(); - String yamled = yaml.dump(bean); - InfinityFloatBean loadedBean = yaml.loadAs(yamled, InfinityFloatBean.class); - assertEquals(Float.POSITIVE_INFINITY, loadedBean.infinityFloat); - assertEquals(Float.POSITIVE_INFINITY, loadedBean.infinityFloatObject); - } + Yaml yaml = new Yaml(); + String yamled = yaml.dump(bean); + InfinityFloatBean loadedBean = yaml.loadAs(yamled, InfinityFloatBean.class); + assertEquals(Float.POSITIVE_INFINITY, loadedBean.infinityFloat); + assertEquals(Float.POSITIVE_INFINITY, loadedBean.infinityFloatObject); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBean.java index 0d498468..5a093f70 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBean.java @@ -1,20 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue183; public class NumberBean { - public Number number; + + public Number number; } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBeanTest.java index 8200a013..7a6a1444 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue183/NumberBeanTest.java @@ -1,95 +1,104 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue183; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class NumberBeanTest extends TestCase { - public void testNumberBean() throws Exception { - - NumberBean number = new NumberBean(); - number.number = 1; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(number); - NumberBean loaded = yaml.loadAs(dump, NumberBean.class); - assertEquals(new Long(1), loaded.number); - } - - public void testNumberAsFloatInfinity() throws Exception { - NumberBean number = new NumberBean(); - number.number = Float.POSITIVE_INFINITY; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(number); - NumberBean loaded = yaml.loadAs(dump, NumberBean.class); - assertEquals(Float.POSITIVE_INFINITY, loaded.number.floatValue()); - } - - public void testNumberAsDoubleInfinity() throws Exception { - NumberBean number = new NumberBean(); - number.number = Double.POSITIVE_INFINITY; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(number); - NumberBean loaded = yaml.loadAs(dump, NumberBean.class); - assertEquals(Double.POSITIVE_INFINITY, loaded.number.doubleValue()); - } - - public void testNumberAsNegativeFloatInfinity() throws Exception { - NumberBean number = new NumberBean(); - number.number = Float.NEGATIVE_INFINITY; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(number); - NumberBean loaded = yaml.loadAs(dump, NumberBean.class); - assertEquals(Float.NEGATIVE_INFINITY, loaded.number.floatValue()); - } - - public void testNumberAsNegativeDoubleInfinity() throws Exception { - NumberBean number = new NumberBean(); - number.number = Double.NEGATIVE_INFINITY; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(number); - NumberBean loaded = yaml.loadAs(dump, NumberBean.class); - assertEquals(Double.NEGATIVE_INFINITY, loaded.number.doubleValue()); - } - - public void testNumberAsFloatNaN() throws Exception { - NumberBean number = new NumberBean(); - number.number = Float.NaN; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(number); - NumberBean loaded = yaml.loadAs(dump, NumberBean.class); - assertEquals(Float.NaN, loaded.number.floatValue()); - } - - public void testNumberAsDoubleNaN() throws Exception { - NumberBean number = new NumberBean(); - number.number = Double.NaN; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(number); - NumberBean loaded = yaml.loadAs(dump, NumberBean.class); - assertEquals(Double.NaN, loaded.number.doubleValue()); - } + public void testNumberAsInteger() throws Exception { + + NumberBean number = new NumberBean(); + number.number = 1; + assertEquals(Integer.class, number.number.getClass()); + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals("Integer is converted to Double.", Double.valueOf(1), loaded.number); + } + + public void testNumberAsDouble() throws Exception { + + NumberBean number = new NumberBean(); + number.number = 1.0; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals(number.number, loaded.number); + } + + public void testNumberAsFloatInfinity() throws Exception { + NumberBean number = new NumberBean(); + number.number = Float.POSITIVE_INFINITY; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals(Float.POSITIVE_INFINITY, loaded.number.floatValue()); + } + + public void testNumberAsDoubleInfinity() throws Exception { + NumberBean number = new NumberBean(); + number.number = Double.POSITIVE_INFINITY; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals(Double.POSITIVE_INFINITY, loaded.number.doubleValue()); + } + + public void testNumberAsNegativeFloatInfinity() throws Exception { + NumberBean number = new NumberBean(); + number.number = Float.NEGATIVE_INFINITY; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals(Float.NEGATIVE_INFINITY, loaded.number.floatValue()); + } + + public void testNumberAsNegativeDoubleInfinity() throws Exception { + NumberBean number = new NumberBean(); + number.number = Double.NEGATIVE_INFINITY; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals(Double.NEGATIVE_INFINITY, loaded.number.doubleValue()); + } + + public void testNumberAsFloatNaN() throws Exception { + NumberBean number = new NumberBean(); + number.number = Float.NaN; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals(Float.NaN, loaded.number.floatValue()); + } + + public void testNumberAsDoubleNaN() throws Exception { + NumberBean number = new NumberBean(); + number.number = Double.NaN; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(number); + NumberBean loaded = yaml.loadAs(dump, NumberBean.class); + assertEquals(Double.NaN, loaded.number.doubleValue()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue188/ErrorMessageTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue188/ErrorMessageTest.java index fa17b680..39a941d4 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue188/ErrorMessageTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue188/ErrorMessageTest.java @@ -1,35 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue188; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class ErrorMessageTest extends TestCase { - public void testErrorMessage() throws Exception { + public void testErrorMessage() throws Exception { - try { - Yaml yaml = new Yaml(); - String doc = "templates:\n" + " master:\n" + " type: Compute : invalid123"; - yaml.load(doc); - fail(); - } catch (Exception e) { - assertFalse(e.getMessage(), e.getMessage().contains("null")); - } + try { + Yaml yaml = new Yaml(); + String doc = "templates:\n" + " master:\n" + " type: Compute : invalid123"; + yaml.load(doc); + fail(); + } catch (Exception e) { + assertFalse(e.getMessage(), e.getMessage().contains("null")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue192/EqualsSignTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue192/EqualsSignTest.java index f48f7d14..a012d5a3 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue192/EqualsSignTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue192/EqualsSignTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue192; @@ -20,11 +18,11 @@ import org.yaml.snakeyaml.Yaml; public class EqualsSignTest extends TestCase { - public void testMappingNode() { - new Yaml().load("part1: ="); - } + public void testMappingNode() { + new Yaml().load("part1: ="); + } - public void testScalarNode() { - new Yaml().load("="); - } + public void testScalarNode() { + new Yaml().load("="); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue193/AbstractBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue193/AbstractBeanTest.java index 8476a6a7..074b0076 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue193/AbstractBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue193/AbstractBeanTest.java @@ -1,25 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue193; import junit.framework.TestCase; - -import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.BaseConstructor; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.introspector.BeanAccess; import org.yaml.snakeyaml.introspector.PropertyUtils; @@ -27,26 +22,26 @@ import org.yaml.snakeyaml.representer.Representer; public class AbstractBeanTest extends TestCase { - public void testErrorMessage() throws Exception { + public void testErrorMessage() throws Exception { - BeanA1 b = new BeanA1(); - b.setId(2l); - b.setName("name1"); + BeanA1 b = new BeanA1(); + b.setId(2L); + b.setName("name1"); - Constructor c = new Constructor(); - Representer r = new Representer(); + Constructor c = new Constructor(); + Representer r = new Representer(); - PropertyUtils pu = new PropertyUtils(); - c.setPropertyUtils(pu); - r.setPropertyUtils(pu); + PropertyUtils pu = new PropertyUtils(); + c.setPropertyUtils(pu); + r.setPropertyUtils(pu); - pu.getProperties(BeanA1.class, BeanAccess.FIELD); + pu.getProperties(BeanA1.class, BeanAccess.FIELD); - Yaml yaml = new Yaml(c, r); - // yaml.setBeanAccess(BeanAccess.FIELD); - String dump = yaml.dump(b); - BeanA1 b2 = (BeanA1) yaml.load(dump); - assertEquals(b.getId(), b2.getId()); - assertEquals(b.getName(), b2.getName()); - } + Yaml yaml = new Yaml(c, r); + // yaml.setBeanAccess(BeanAccess.FIELD); + String dump = yaml.dump(b); + BeanA1 b2 = yaml.load(dump); + assertEquals(b.getId(), b2.getId()); + assertEquals(b.getName(), b2.getName()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA.java b/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA.java index e2ab61b9..a8f54009 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA.java @@ -1,22 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue193; public abstract class BeanA { - public abstract Object getId(); + public abstract Object getId(); } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA1.java b/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA1.java index f7b7719f..15323d05 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA1.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue193/BeanA1.java @@ -1,40 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue193; public class BeanA1 extends BeanA { - private Long id; + private Long id; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - private String name; + private String name; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue193/TestYaml.java b/src/test/java/org/yaml/snakeyaml/issues/issue193/TestYaml.java index 662c74bd..7b1c9cee 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue193/TestYaml.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue193/TestYaml.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue193; @@ -19,50 +17,47 @@ import org.yaml.snakeyaml.Yaml; public class TestYaml { - public static abstract class BeanA { + public static abstract class BeanA { - public abstract Object getId(); + public abstract Object getId(); - } - - public static class BeanA1 extends BeanA { + } - private Long id; + public static class BeanA1 extends BeanA { - // @Override - public Long getId() { - return id; - } + private Long id; - public void setId(Long id) { - this.id = id; - } + // @Override + public Long getId() { + return id; + } - private String name; + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + private String name; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; } - public static void main(String[] args) { + } - System.out.println("test..."); - BeanA1 b = new BeanA1(); - b.setId(2l); - b.setName("name1"); - Yaml yaml = new Yaml(); - String dump = yaml.dump(b); + public static void main(String[] args) { - System.out.println("dump:" + dump); + BeanA1 b = new BeanA1(); + b.setId(2L); + b.setName("name1"); + Yaml yaml = new Yaml(); + String dump = yaml.dump(b); - dump = "!!org.yaml.snakeyaml.issues.issue193.TestYaml$BeanA1 {id: 2, name: name1}"; + dump = "!!org.yaml.snakeyaml.issues.issue193.TestYaml$BeanA1 {id: 2, name: name1}"; - yaml.load(dump); - } + yaml.load(dump); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifier.java b/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifier.java index 0557412e..99190bc8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifier.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifier.java @@ -1,19 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue203; -public interface ContentIdentifier extends Identifiable<Long> {}; +public interface ContentIdentifier extends Identifiable<Long> { + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifierImpl.java b/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifierImpl.java index b4c10f8c..d9419d21 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifierImpl.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue203/ContentIdentifierImpl.java @@ -1,29 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue203; -public class ContentIdentifierImpl implements ContentIdentifier { +public class ContentIdentifierImpl implements ContentIdentifier { - private Long id; + private final Long id; - public ContentIdentifierImpl(Long id) { - this.id = id; - } + public ContentIdentifierImpl(Long id) { + this.id = id; + } - public Long getId() { - return id; - } -}
\ No newline at end of file + public Long getId() { + return id; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue203/DataBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue203/DataBean.java index dc96d04c..68d319a7 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue203/DataBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue203/DataBean.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue203; public class DataBean { - private String id; - private ContentIdentifier content; - public String getId() { - return id; - } + private String id; + private ContentIdentifier content; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } - public ContentIdentifier getContent() { - return content; - } - public void setContent(ContentIdentifier content) { - this.content = content; - } + public ContentIdentifier getContent() { + return content; + } + + public void setContent(ContentIdentifier content) { + this.content = content; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue203/GenericTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue203/GenericTest.java index 165fbe6b..ec2924b6 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue203/GenericTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue203/GenericTest.java @@ -1,32 +1,28 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue203; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class GenericTest extends TestCase { - public void testGenericInterface() { - Yaml yaml = new Yaml(); - String uuu = "!!org.yaml.snakeyaml.issues.issue203.DataBean\n" - + "content: !!org.yaml.snakeyaml.issues.issue203.ContentIdentifierImpl 33\n" - + "id: 555"; - DataBean obj = (DataBean) yaml.load(uuu); - assertEquals(33, obj.getContent().getId().intValue()); - } + public void testGenericInterface() { + Yaml yaml = new Yaml(); + String uuu = "!!org.yaml.snakeyaml.issues.issue203.DataBean\n" + + "content: !!org.yaml.snakeyaml.issues.issue203.ContentIdentifierImpl 33\n" + "id: 555"; + DataBean obj = yaml.load(uuu); + assertEquals(33, obj.getContent().getId().intValue()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue203/Identifiable.java b/src/test/java/org/yaml/snakeyaml/issues/issue203/Identifiable.java index dbe1ffe2..6426925f 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue203/Identifiable.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue203/Identifiable.java @@ -1,22 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue203; import java.io.Serializable; public interface Identifiable<ID extends Serializable> { - public ID getId(); -}
\ No newline at end of file + + ID getId(); +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue205/AppleSmileTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue205/AppleSmileTest.java index f17556ec..7141113c 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue205/AppleSmileTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue205/AppleSmileTest.java @@ -1,36 +1,33 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue205; +import java.io.InputStream; +import java.util.Map; import junit.framework.TestCase; import org.yaml.snakeyaml.Yaml; -import java.io.InputStream; - public class AppleSmileTest extends TestCase { - public void testEmoji() { - //http://support.apple.com/en-us/ht4976 - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("issues/ios_emoji_surrogate.yaml"); - Yaml yaml = new Yaml(); - try { - yaml.load(input); - fail("Surrogate characters must not be accepted."); - } catch (Exception e) { - assertEquals("special characters are not allowed", e.getMessage()); - } - } + public void testEmoji() { + // http://support.apple.com/en-us/ht4976 + InputStream input = Thread.currentThread().getContextClassLoader() + .getResourceAsStream("issues/ios_emoji_surrogate.yaml"); + Yaml yaml = new Yaml(); + Map<String, String> map = yaml.load(input); + String ios_emoji = map.get("text"); + assertEquals("๐ท๐", ios_emoji); + System.out.println(ios_emoji); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue207/OctalNumberTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue207/OctalNumberTest.java index 82dd5d50..b3962708 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue207/OctalNumberTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue207/OctalNumberTest.java @@ -1,41 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue207; -import junit.framework.TestCase; -import org.yaml.snakeyaml.Yaml; +import static org.junit.Assert.assertEquals; -import java.io.InputStream; import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; -public class OctalNumberTest extends TestCase { +public class OctalNumberTest { - public void testOctalNumbersMoreThenSeven() { - Yaml yaml = new Yaml(); - assertEquals(7, yaml.load("07")); - assertEquals(63, yaml.load("077")); - assertEquals(0, yaml.load("0")); - assertEquals("0A", yaml.load("0A")); - assertEquals("09", yaml.load("!!str 09")); + @Test + public void testOctalNumbersMoreThenSeven() { + Yaml yaml = new Yaml(); + assertEquals(Integer.valueOf(7), yaml.load("07")); + assertEquals(Integer.valueOf(63), yaml.load("077")); + assertEquals(Integer.valueOf(0), yaml.load("0")); + assertEquals("0A", yaml.load("0A")); + assertEquals("09", yaml.load("!!str 09")); - /* TODO fix 207 and 130 - assertEquals("08", yaml.load("08")); - assertEquals("09", yaml.load("09")); - Map<String, String> parsed9 = (Map<String, String>) yaml.load("a: 09"); - assertEquals("09", parsed9.get("a")); - */ - } + assertEquals("08", yaml.load("08")); + assertEquals("09", yaml.load("09")); + Map<String, String> parsed9 = yaml.load("a: 09"); + assertEquals("09", parsed9.get("a")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue24/LineNumberTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue24/LineNumberTest.java index 3ea8ead0..222cce67 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue24/LineNumberTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue24/LineNumberTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue24; import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -24,16 +21,17 @@ import org.yaml.snakeyaml.Yaml; * to test http://code.google.com/p/snakeyaml/issues/detail?id=24 */ public class LineNumberTest extends TestCase { - public void test1() { - String resource = Util.getLocalResource("issues/issue24-1.yaml"); - // System.out.println(resource); - Yaml yaml = new Yaml(); - try { - yaml.load(resource); - fail(); - } catch (Exception e) { - assertTrue(e.toString(), e.toString().contains("line 3")); - assertTrue(e.toString(), e.toString().contains("column 12")); - } + + public void test1() { + String resource = Util.getLocalResource("issues/issue24-1.yaml"); + // System.out.println(resource); + Yaml yaml = new Yaml(); + try { + yaml.load(resource); + fail(); + } catch (Exception e) { + assertTrue(e.toString(), e.toString().contains("line 3")); + assertTrue(e.toString(), e.toString().contains("column 12")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue29/BigJavaBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue29/BigJavaBean.java index 5141662e..cb20be40 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue29/BigJavaBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue29/BigJavaBean.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue29; @@ -19,109 +17,120 @@ import java.util.List; import java.util.Map; public class BigJavaBean { - private String name; - private String address; - private String description; - private int id; - private List<Integer> numbers; - private Map<String, String> data; - - public BigJavaBean() { - } - public BigJavaBean(int id, String name, String address, String description) { - super(); - this.name = name; - this.address = address; - this.description = description; - this.id = id; - } + private String name; + private String address; + private String description; + private int id; + private List<Integer> numbers; + private Map<String, String> data; - public String getName() { - return name; - } + public BigJavaBean() {} - public void setName(String name) { - this.name = name; - } + public BigJavaBean(int id, String name, String address, String description) { + super(); + this.name = name; + this.address = address; + this.description = description; + this.id = id; + } - public String getAddress() { - return address; - } + public String getName() { + return name; + } - public String getDescription() { - return description; - } + public void setName(String name) { + this.name = name; + } - public int getId() { - return id; - } + public String getAddress() { + return address; + } - public List<Integer> getNumbers() { - return numbers; - } + public String getDescription() { + return description; + } - public void setNumbers(List<Integer> numbers) { - this.numbers = numbers; - } + public int getId() { + return id; + } - public Map<String, String> getData() { - return data; - } + public List<Integer> getNumbers() { + return numbers; + } - public void setData(Map<String, String> data) { - this.data = data; - } + public void setNumbers(List<Integer> numbers) { + this.numbers = numbers; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((address == null) ? 0 : address.hashCode()); - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + id; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((numbers == null) ? 0 : numbers.hashCode()); - return result; - } + public Map<String, String> getData() { + return data; + } + + public void setData(Map<String, String> data) { + this.data = data; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((address == null) ? 0 : address.hashCode()); + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + id; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((numbers == null) ? 0 : numbers.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - BigJavaBean other = (BigJavaBean) obj; - if (address == null) { - if (other.address != null) - return false; - } else if (!address.equals(other.address)) - return false; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (id != other.id) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (numbers == null) { - if (other.numbers != null) - return false; - } else if (!numbers.equals(other.numbers)) - return false; - return true; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BigJavaBean other = (BigJavaBean) obj; + if (address == null) { + if (other.address != null) { + return false; + } + } else if (!address.equals(other.address)) { + return false; + } + if (data == null) { + if (other.data != null) { + return false; + } + } else if (!data.equals(other.data)) { + return false; + } + if (description == null) { + if (other.description != null) { + return false; + } + } else if (!description.equals(other.description)) { + return false; + } + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (numbers == null) { + return other.numbers == null; + } else { + return numbers.equals(other.numbers); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStyleTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStyleTest.java index 384b83d1..f5f1d236 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStyleTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStyleTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue29; import java.util.LinkedHashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.ScalarStyle; import org.yaml.snakeyaml.Util; @@ -32,85 +28,87 @@ import org.yaml.snakeyaml.representer.Representer; * to test http://code.google.com/p/snakeyaml/issues/detail?id=29 */ public class FlexibleScalarStyleTest extends TestCase { - public void testLong() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.FOLDED); - Yaml yaml = new Yaml(options); - String result = yaml - .dump("qqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq " - + "qqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq " - + "qqqqqqqqqqqqqqqqqqqqqqqqq 111111111111111111111111\n " - + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqqqq\n"); - // System.out.println(result); - assertTrue(result.startsWith(">\n")); - assertEquals( - ">\n qqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq\n qqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqq 111111111111111111111111\n qqqqqqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqqqq\n", - result); - } - public void testNoFoldedScalar() { - DumperOptions options = new DumperOptions(); - options.setWidth(30); - Yaml yaml = new Yaml(options); - String output = yaml.dump(getData()); - // System.out.println(output); - String etalon = Util.getLocalResource("representer/scalar-style1.yaml"); - assertEquals(etalon, output); - } + public void testLong() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.FOLDED); + Yaml yaml = new Yaml(options); + String result = + yaml.dump("qqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq " + + "qqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq " + + "qqqqqqqqqqqqqqqqqqqqqqqqq 111111111111111111111111\n " + + "qqqqqqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqqqq\n"); + // System.out.println(result); + assertTrue(result.startsWith(">\n")); + assertEquals( + ">\n qqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqq\n qqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqq 111111111111111111111111\n qqqqqqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqqqqqqqqqq\n", + result); + } - public void testCustomScalarStyle() { - DumperOptions options = new DumperOptions(); - options.setWidth(30); - Yaml yaml = new Yaml(new MyRepresenter(), options); - String output = yaml.dump(getData()); - // System.out.println(output); - String etalon = Util.getLocalResource("representer/scalar-style2.yaml"); - assertEquals(etalon, output); - } + public void testDefaultScalarStyle() { + DumperOptions options = new DumperOptions(); + options.setWidth(30); + Yaml yaml = new Yaml(options); + String output = yaml.dump(getData()); + // System.out.println(output); + String etalon = Util.getLocalResource("representer/scalar-style1.yaml"); + assertEquals(etalon, output); + } - public void testCustomScalarStyleNoSplitLines() { - DumperOptions options = new DumperOptions(); - options.setWidth(30); - options.setSplitLines(false); - Yaml yaml = new Yaml(new MyRepresenter(), options); - String output = yaml.dump(getData()); - // System.out.println(output); - String etalon = Util.getLocalResource("representer/scalar-style3.yaml"); - assertEquals(etalon, output); - } + public void testCustomScalarStyle() { + DumperOptions options = new DumperOptions(); + options.setWidth(30); + Yaml yaml = new Yaml(new MyRepresenter(), options); + String output = yaml.dump(getData()); + // System.out.println(output); + String etalon = Util.getLocalResource("representer/scalar-style2.yaml"); + assertEquals(etalon, output); + } - private Map<String, String> getData() { - Map<String, String> map = new LinkedHashMap<String, String>(); - map.put("name", "Steve Jobs"); - map.put("address", "Name\nStreet Number\nCountry"); - map.put("description", - "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); - return map; - } + public void testCustomScalarStyleNoSplitLines() { + DumperOptions options = new DumperOptions(); + options.setWidth(30); + options.setSplitLines(false); + Yaml yaml = new Yaml(new MyRepresenter(), options); + String output = yaml.dump(getData()); + // System.out.println(output); + String etalon = Util.getLocalResource("representer/scalar-style3.yaml"); + assertEquals(etalon, output); + } - private class MyRepresenter extends Representer { + private Map<String, String> getData() { + Map<String, String> map = new LinkedHashMap<String, String>(); + map.put("name", "Steve Jobs"); + map.put("address", "Name\nStreet Number\nCountry"); + map.put("description", + "1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000"); + return map; + } - public MyRepresenter() { - super(); - this.representers.put(String.class, new FlexibleRepresent()); - } + private class MyRepresenter extends Representer { + + public MyRepresenter() { + super(); + this.representers.put(String.class, new FlexibleRepresent()); + } + + private class FlexibleRepresent extends RepresentString { - private class FlexibleRepresent extends RepresentString { - public Node representData(Object data) { - ScalarNode node = (ScalarNode) super.representData(data); - if (node.getStyle() == null) { - // if Plain scalar style - if (node.getValue().length() < 25) { - return node; - } else { - // Folded scalar style - return new ScalarNode(node.getTag(), node.getValue(), node.getStartMark(), - node.getEndMark(), '>'); - } - } else { - return node; - } - } + public Node representData(Object data) { + ScalarNode node = (ScalarNode) super.representData(data); + if (node.isPlain()) { + // if Plain scalar style + if (node.getValue().length() < 25) { + return node; + } else { + // Folded scalar style + return new ScalarNode(node.getTag(), node.getValue(), node.getStartMark(), + node.getEndMark(), ScalarStyle.FOLDED); + } + } else { + return node; } + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStylesInJavaBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStylesInJavaBeanTest.java index afddbc8e..06d0b665 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStylesInJavaBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue29/FlexibleScalarStylesInJavaBeanTest.java @@ -1,21 +1,18 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue29; -import java.beans.IntrospectionException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -24,9 +21,8 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.BeanAccess; import org.yaml.snakeyaml.introspector.Property; @@ -37,111 +33,112 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; public class FlexibleScalarStylesInJavaBeanTest extends TestCase { - public void testDifferentStyles() { - BigJavaBean bean1 = new BigJavaBean(1, "simple", "line 1\nline2\nzipcode", "short text1"); - List<Integer> numbers1 = new ArrayList<Integer>(Arrays.asList(1, 2, 3)); - bean1.setNumbers(numbers1); - Map<String, String> data1 = new HashMap<String, String>(); - data1.put("key1", "value1"); - data1.put("key2", "value2"); - bean1.setData(data1); - // - BigJavaBean bean2 = new BigJavaBean(1, "second", "line 111\nline 222\nzipcode 12345\n\n", - "info: semicolon is used"); - List<Integer> numbers2 = new ArrayList<Integer>(Arrays.asList(4, 5, 6, 777, 888, 999, 1000)); - bean2.setNumbers(numbers2); - Map<String, String> data2 = new HashMap<String, String>(); - data2.put("key21", "value12"); - data2.put("key22", "value with\ntwo lines"); - bean2.setData(data2); - // - List<BigJavaBean> list = new ArrayList<BigJavaBean>(); - list.add(bean1); - list.add(bean2); - Yaml yaml = new Yaml(new MyRepresenter()); - yaml.setBeanAccess(BeanAccess.FIELD); - String output = yaml.dump(list); - // System.out.println(output); - // parse back - @SuppressWarnings("unchecked") - List<BigJavaBean> parsed = (List<BigJavaBean>) yaml.load(output); - assertEquals(2, parsed.size()); - assertEquals(bean1, parsed.get(0)); - assertEquals(bean2, parsed.get(1)); + public void testDifferentStyles() { + BigJavaBean bean1 = new BigJavaBean(1, "simple", "line 1\nline2\nzipcode", "short text1"); + List<Integer> numbers1 = new ArrayList<Integer>(Arrays.asList(1, 2, 3)); + bean1.setNumbers(numbers1); + Map<String, String> data1 = new HashMap<String, String>(); + data1.put("key1", "value1"); + data1.put("key2", "value2"); + bean1.setData(data1); + // + BigJavaBean bean2 = new BigJavaBean(1, "second", "line 111\nline 222\nzipcode 12345\n\n", + "info: semicolon is used"); + List<Integer> numbers2 = new ArrayList<Integer>(Arrays.asList(4, 5, 6, 777, 888, 999, 1000)); + bean2.setNumbers(numbers2); + Map<String, String> data2 = new HashMap<String, String>(); + data2.put("key21", "value12"); + data2.put("key22", "value with\ntwo lines"); + bean2.setData(data2); + // + List<BigJavaBean> list = new ArrayList<BigJavaBean>(); + list.add(bean1); + list.add(bean2); + Yaml yaml = new Yaml(new MyRepresenter()); + yaml.setBeanAccess(BeanAccess.FIELD); + String output = yaml.dump(list); + // System.out.println(output); + // parse back + @SuppressWarnings("unchecked") + List<BigJavaBean> parsed = yaml.load(output); + assertEquals(2, parsed.size()); + assertEquals(bean1, parsed.get(0)); + assertEquals(bean2, parsed.get(1)); + + } + + private class MyRepresenter extends Representer { + + /* + * Change the default order. Important data goes first. + */ + @Override + protected Set<Property> getProperties(Class<? extends Object> type) { + if (type.isAssignableFrom(BigJavaBean.class)) { + Set<Property> standard = super.getProperties(type); + Set<Property> sorted = new TreeSet<Property>(new PropertyComparator()); + sorted.addAll(standard); + return sorted; + } else { + return super.getProperties(type); + } } - private class MyRepresenter extends Representer { - /* - * Change the default order. Important data goes first. - */ - @Override - protected Set<Property> getProperties(Class<? extends Object> type) - throws IntrospectionException { - if (type.isAssignableFrom(BigJavaBean.class)) { - Set<Property> standard = super.getProperties(type); - Set<Property> sorted = new TreeSet<Property>(new PropertyComparator()); - sorted.addAll(standard); - return sorted; - } else { - return super.getProperties(type); - } - } + private class PropertyComparator implements Comparator<Property> { - private class PropertyComparator implements Comparator<Property> { - public int compare(Property o1, Property o2) { - // important go first - List<String> order = new ArrayList<String>(Arrays.asList("id", "name", - "description", "address")); - for (String name : order) { - int c = compareByName(o1, o2, name); - if (c != 0) { - return c; - } - } - // all the rest - return o1.compareTo(o2); - } + public int compare(Property o1, Property o2) { + // important go first + List<String> order = + new ArrayList<String>(Arrays.asList("id", "name", "description", "address")); + for (String name : order) { + int c = compareByName(o1, o2, name); + if (c != 0) { + return c; + } + } + // all the rest + return o1.compareTo(o2); + } - private int compareByName(Property o1, Property o2, String name) { - if (o1.getName().equals(name)) { - return -1; - } else if (o2.getName().equals(name)) { - return 1; - } - return 0;// compare further - } + private int compareByName(Property o1, Property o2, String name) { + if (o1.getName().equals(name)) { + return -1; + } else if (o2.getName().equals(name)) { + return 1; } + return 0;// compare further + } + } - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, - Object propertyValue, Tag customTag) { - if (javaBean instanceof BigJavaBean) { - BigJavaBean bean = (BigJavaBean) javaBean; - NodeTuple standard = super.representJavaBeanProperty(javaBean, property, - propertyValue, customTag); - if (property.getName().equals("numbers")) { - // when the list is small, make it block collection style - if (bean.getNumbers().size() < 5) { - SequenceNode n = (SequenceNode) standard.getValueNode(); - return new NodeTuple(standard.getKeyNode(), new SequenceNode(n.getTag(), - true, n.getValue(), n.getStartMark(), n.getEndMark(), false)); - } - } - if (property.getName().equals("description")) { - // if description contains ':' use folded scalar style and - // not single quoted scalar style - if (bean.getDescription().indexOf(':') > 0) { - ScalarNode n = (ScalarNode) standard.getValueNode(); - return new NodeTuple(standard.getKeyNode(), new ScalarNode(n.getTag(), - n.getValue(), n.getStartMark(), n.getEndMark(), '>')); - } - } - return standard; - } else { - return super - .representJavaBeanProperty(javaBean, property, propertyValue, customTag); - } + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, + Object propertyValue, Tag customTag) { + if (javaBean instanceof BigJavaBean) { + BigJavaBean bean = (BigJavaBean) javaBean; + NodeTuple standard = + super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + if (property.getName().equals("numbers")) { + // when the list is small, make it block collection style + if (bean.getNumbers().size() < 5) { + SequenceNode n = (SequenceNode) standard.getValueNode(); + return new NodeTuple(standard.getKeyNode(), new SequenceNode(n.getTag(), true, + n.getValue(), n.getStartMark(), n.getEndMark(), DumperOptions.FlowStyle.BLOCK)); + } + } + if (property.getName().equals("description")) { + // if description contains ':' use folded scalar style and + // not single quoted scalar style + if (bean.getDescription().indexOf(':') > 0) { + ScalarNode n = (ScalarNode) standard.getValueNode(); + return new NodeTuple(standard.getKeyNode(), new ScalarNode(n.getTag(), n.getValue(), + n.getStartMark(), n.getEndMark(), DumperOptions.ScalarStyle.FOLDED)); + } } + return standard; + } else { + return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue306/BeanWithId.java b/src/test/java/org/yaml/snakeyaml/issues/issue306/BeanWithId.java index 40f849e3..84221a98 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue306/BeanWithId.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue306/BeanWithId.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue306; import java.util.UUID; public class BeanWithId { - private int value; - private UUID id; - public int getValue() { - return value; - } + private int value; + private UUID id; - public void setValue(int value) { - this.value = value; - } + public int getValue() { + return value; + } - public UUID getId() { - return id; - } + public void setValue(int value) { + this.value = value; + } - public void setId(UUID id) { - this.id = id; - } + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue306/UuidSupportTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue306/UuidSupportTest.java index 36228688..bef675f1 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue306/UuidSupportTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue306/UuidSupportTest.java @@ -1,88 +1,85 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue306; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.UUID; +import java.util.regex.Pattern; import org.junit.Test; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Tag; -import java.util.UUID; -import java.util.regex.Pattern; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - public class UuidSupportTest { - public static final Pattern UUID_PATTERN = Pattern - .compile("^(?:\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})$"); - public static final Tag UUID_TAG = new Tag(Tag.PREFIX + "java.util.UUID"); + public static final Pattern UUID_PATTERN = Pattern + .compile("^(?:\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})$"); + public static final Tag UUID_TAG = new Tag(Tag.PREFIX + "java.util.UUID"); - @Test - public void pattern() { - assertTrue(UUID_PATTERN.matcher("7f511847-781a-45df-9c8d-1e32e028b9b3").matches()); - assertTrue(UUID_PATTERN.matcher("AC4877BE-0C31-4458-A86E-0272EFE1AAA8").matches()); - } + @Test + public void pattern() { + assertTrue(UUID_PATTERN.matcher("7f511847-781a-45df-9c8d-1e32e028b9b3").matches()); + assertTrue(UUID_PATTERN.matcher("AC4877BE-0C31-4458-A86E-0272EFE1AAA8").matches()); + } - @Test - public void dumpAsString() { - UUID uuid = UUID.randomUUID(); - String str = uuid.toString(); - Yaml yaml = new Yaml(); - yaml.addImplicitResolver(UUID_TAG, UUID_PATTERN, null); - String output = yaml.dump(str); - assertEquals("'" + str + "'\n", output); - assertEquals(str + "\n", yaml.dump(uuid)); - } + @Test + public void dumpAsString() { + UUID uuid = UUID.randomUUID(); + String str = uuid.toString(); + Yaml yaml = new Yaml(); + yaml.addImplicitResolver(UUID_TAG, UUID_PATTERN, null); + String output = yaml.dump(str); + assertEquals("'" + str + "'\n", output); + assertEquals(str + "\n", yaml.dump(uuid)); + } - @Test - public void loadAsUuid() { - Yaml yaml = new Yaml(); - yaml.addImplicitResolver(UUID_TAG, UUID_PATTERN, null); - UUID uuid = (UUID) yaml.load("7f511847-781a-45df-9c8d-1e32e028b9b3"); - assertEquals("7f511847-781a-45df-9c8d-1e32e028b9b3", uuid.toString()); - } + @Test + public void loadAsUuid() { + Yaml yaml = new Yaml(); + yaml.addImplicitResolver(UUID_TAG, UUID_PATTERN, null); + UUID uuid = yaml.load("7f511847-781a-45df-9c8d-1e32e028b9b3"); + assertEquals("7f511847-781a-45df-9c8d-1e32e028b9b3", uuid.toString()); + } - @Test - public void loadFromBean() { - String input = Util.getLocalResource("issues/issue306-1.yaml"); - Yaml yaml = new Yaml(); - BeanWithId bean = yaml.loadAs(input, BeanWithId.class); - assertEquals("7f511847-781a-45df-9c8d-1e32e028b9b3", bean.getId().toString()); - } + @Test + public void loadFromBean() { + String input = Util.getLocalResource("issues/issue306-1.yaml"); + Yaml yaml = new Yaml(); + BeanWithId bean = yaml.loadAs(input, BeanWithId.class); + assertEquals("7f511847-781a-45df-9c8d-1e32e028b9b3", bean.getId().toString()); + } - @Test - public void dumpUuid() { - UUID uuid = UUID.randomUUID(); - Yaml yaml = new Yaml(); - String output = yaml.dump(uuid); - assertEquals("!!java.util.UUID '" + uuid.toString() + "'\n", output); - } + @Test + public void dumpUuid() { + UUID uuid = UUID.randomUUID(); + Yaml yaml = new Yaml(); + String output = yaml.dump(uuid); + assertEquals("!!java.util.UUID '" + uuid + "'\n", output); + } - @Test - public void dumpBean() { - BeanWithId bean = new BeanWithId(); - bean.setValue(3); - UUID uuid = UUID.fromString("ac4877be-0c31-4458-a86e-0272efe1aaa8"); - bean.setId(uuid); - Yaml yaml = new Yaml(); - String output = yaml.dumpAs(bean, Tag.MAP, DumperOptions.FlowStyle.BLOCK); - String expected = Util.getLocalResource("issues/issue306-2.yaml"); - assertEquals(expected, output); - } + @Test + public void dumpBean() { + BeanWithId bean = new BeanWithId(); + bean.setValue(3); + UUID uuid = UUID.fromString("ac4877be-0c31-4458-a86e-0272efe1aaa8"); + bean.setId(uuid); + Yaml yaml = new Yaml(); + String output = yaml.dumpAs(bean, Tag.MAP, DumperOptions.FlowStyle.BLOCK); + String expected = Util.getLocalResource("issues/issue306-2.yaml"); + assertEquals(expected, output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue307/Blocks.java b/src/test/java/org/yaml/snakeyaml/issues/issue307/Blocks.java new file mode 100644 index 00000000..23fec53a --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue307/Blocks.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue307; + +public class Blocks { + + @OrderAnnotation(order = 3) + public int x; + + @OrderAnnotation(order = 2) + public int y; + + @OrderAnnotation(order = 1) + public int z; +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue307/CustomerBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue307/CustomerBean.java new file mode 100644 index 00000000..e30b177b --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue307/CustomerBean.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue307; + +public class CustomerBean extends OrderBean { + + @OrderAnnotation(order = -1) + String customerName; + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderAnnotation.java b/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderAnnotation.java new file mode 100644 index 00000000..5d67d20b --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderAnnotation.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue307; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface OrderAnnotation { + + int order() default 0; +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderBean.java new file mode 100644 index 00000000..ddaa6193 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderBean.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue307; + +public class OrderBean { + + public String name; + + @OrderAnnotation(order = 1) + public Blocks type; + + @OrderAnnotation(order = 2) + public Integer age; + + @OrderAnnotation(order = 3) + public String text; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Blocks getType() { + return type; + } + + public void setType(Blocks type) { + this.type = type; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderTest.java new file mode 100644 index 00000000..0e0c6269 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue307/OrderTest.java @@ -0,0 +1,104 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue307; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Comparator; +import java.util.Set; +import java.util.TreeSet; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.introspector.BeanAccess; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertyUtils; +import org.yaml.snakeyaml.representer.Representer; + +public class OrderTest extends TestCase { + + public void test_order() { + Representer representer = new Representer(); + representer.setPropertyUtils(new OrderUtil()); + Yaml yaml = new Yaml(representer); + String s = Util.getLocalResource("issues/issue307-order.yaml"); + OrderBean orderBean = yaml.loadAs(s, OrderBean.class); + String dump = yaml.dump(orderBean); + // System.out.println(dump); + String str = "!!org.yaml.snakeyaml.issues.issue307.OrderBean\n" + "name: tian\n" + + "type: {z: 256, y: 255, x: 254}\n" + "age: 22\n" + "text: omit\n"; + assertEquals(str, dump); + } + + public void test_extend_order() { + Representer representer = new Representer(); + representer.setPropertyUtils(new OrderUtil()); + Yaml yaml = new Yaml(representer); + String s = Util.getLocalResource("issues/issue307-order.yaml"); + CustomerBean orderBean2 = yaml.loadAs(s, CustomerBean.class); + orderBean2.setCustomerName("customer"); + String dump = yaml.dump(orderBean2); + // System.out.println(dump); + String str = "!!org.yaml.snakeyaml.issues.issue307.CustomerBean\n" + "customerName: customer\n" + + "name: tian\n" + "type: {z: 256, y: 255, x: 254}\n" + "age: 22\n" + "text: omit\n"; + assertEquals(str, dump); + } + + public static class OrderUtil extends PropertyUtils { + + @Override + protected Set<Property> createPropertySet(final Class<?> type, BeanAccess bAccess) { + Set<Property> properties = new TreeSet<>(new Comparator<Property>() { + @Override + public int compare(Property prop1, Property prop2) { + Integer order1 = getValue(prop1.getName(), type); + Integer order2 = getValue(prop2.getName(), type); + if (order1 == null) { + order1 = 0; + } + if (order2 == null) { + order2 = 0; + } + if (order1 < order2) { + return -1; + } + if (order1 > order2) { + return 1; + } + return prop1.getName().compareTo(prop2.getName()); + } + }); + properties.addAll(super.createPropertySet(type, bAccess)); + return properties; + } + + public Integer getValue(String name, Class<?> type) { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setBeanAccess(BeanAccess.FIELD); + Property property = propertyUtils.getProperty(type, name); + Annotation annotation = property.getAnnotation(OrderAnnotation.class); + Integer invoke = null; + if (annotation != null) { + try { + Method method = annotation.annotationType().getDeclaredMethod("order"); + invoke = (Integer) method.invoke(annotation, null); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } + return invoke; + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue310/Option.java b/src/test/java/org/yaml/snakeyaml/issues/issue310/Option.java index 9c0cddb4..c78efe21 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue310/Option.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue310/Option.java @@ -1,34 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue310; public final class Option<T> { - private final T value; + private final T value; - public static <T> Option<T> valueOf(T v) { - return new Option<T>(v); - } + public static <T> Option<T> valueOf(T v) { + return new Option<T>(v); + } - private Option(T v) { - this.value = v; - } + private Option(T v) { + this.value = v; + } - public T getValue() { - return value; - } + public T getValue() { + return value; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue310/Person.java b/src/test/java/org/yaml/snakeyaml/issues/issue310/Person.java index c18cde2c..5adf6299 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue310/Person.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue310/Person.java @@ -1,46 +1,44 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue310; public class Person { - private final int id; - private final String name; - private final Option<Double> income; + private final int id; + private final String name; + private final Option<Double> income; - public Person() { - this(0, "", Option.valueOf(0.)); - } + public Person() { + this(0, "", Option.valueOf(0.)); + } - public Person(int id, String name, Option<Double> income) { - this.id = id; - this.name = name; - this.income = income; - } + public Person(int id, String name, Option<Double> income) { + this.id = id; + this.name = name; + this.income = income; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Option<Double> getIncome() { - return income; - } + public Option<Double> getIncome() { + return income; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue310/PropertyWithPrivateCostructorTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue310/PropertyWithPrivateCostructorTest.java index cb527624..d84db4e8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue310/PropertyWithPrivateCostructorTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue310/PropertyWithPrivateCostructorTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue310; @@ -26,50 +24,51 @@ import org.yaml.snakeyaml.representer.Representer; public class PropertyWithPrivateCostructorTest { - public static class OptionRepresenter extends Representer { + public static class OptionRepresenter extends Representer { - public OptionRepresenter() { - this.representers.put(Option.class, new RepresentOption()); - } + public OptionRepresenter() { + this.representers.put(Option.class, new RepresentOption()); + } - private class RepresentOption implements Represent { - public Node representData(Object data) { - Option<?> opt = (Option<?>) data; - return represent(opt.getValue()); - } - } + private class RepresentOption implements Represent { + public Node representData(Object data) { + Option<?> opt = (Option<?>) data; + return represent(opt.getValue()); + } } - @Test - public void loadFromString() { + } - String yamlStr = "id: 123\n" + "income: 123456.78\n" + "name: Neo Anderson"; + @Test + public void loadFromString() { - Person loadedPerson = yaml().loadAs(yamlStr, Person.class); + String yamlStr = "id: 123\n" + "income: 123456.78\n" + "name: Neo Anderson"; - assertEquals("id", loadedPerson.getId(), 123); - assertEquals("name", loadedPerson.getName(), "Neo Anderson"); - assertEquals("income", loadedPerson.getIncome().getValue().doubleValue(), 123456.78, 0.); - } + Person loadedPerson = yaml().loadAs(yamlStr, Person.class); - @Test - public void dumpNload() { + assertEquals("id", loadedPerson.getId(), 123); + assertEquals("name", loadedPerson.getName(), "Neo Anderson"); + assertEquals("income", loadedPerson.getIncome().getValue().doubleValue(), 123456.78, 0.); + } - Person person = new Person(123, "Neo Anderson", Option.valueOf(123456.78)); + @Test + public void dumpNload() { - String dump = yaml().dumpAsMap(person); + Person person = new Person(123, "Neo Anderson", Option.valueOf(123456.78)); - Person loadedPerson = yaml().loadAs(dump, Person.class); + String dump = yaml().dumpAsMap(person); - assertEquals("id", loadedPerson.getId(), 123); - assertEquals("name", loadedPerson.getName(), "Neo Anderson"); - assertEquals("income", loadedPerson.getIncome().getValue().doubleValue(), 123456.78, 0.); - } + Person loadedPerson = yaml().loadAs(dump, Person.class); - private Yaml yaml() { - Yaml _yaml = new Yaml(new OptionRepresenter()); - _yaml.setBeanAccess(BeanAccess.FIELD); - return _yaml; - } + assertEquals("id", loadedPerson.getId(), 123); + assertEquals("name", loadedPerson.getName(), "Neo Anderson"); + assertEquals("income", loadedPerson.getIncome().getValue().doubleValue(), 123456.78, 0.); + } + + private Yaml yaml() { + Yaml _yaml = new Yaml(new OptionRepresenter()); + _yaml.setBeanAccess(BeanAccess.FIELD); + return _yaml; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue311/BeanWithEnum.java b/src/test/java/org/yaml/snakeyaml/issues/issue311/BeanWithEnum.java index 7bd5e2cf..18888336 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue311/BeanWithEnum.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue311/BeanWithEnum.java @@ -1,57 +1,55 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue311; public class BeanWithEnum { - private boolean boolField; - private String name; - private BooleanEnum enumField; + private boolean boolField; + private String name; + private BooleanEnum enumField; - public BeanWithEnum() { - this(true, "", BooleanEnum.UNKNOWN); - } + public BeanWithEnum() { + this(true, "", BooleanEnum.UNKNOWN); + } - public BeanWithEnum(boolean boolField, String name, BooleanEnum enumField) { - this.boolField = boolField; - this.name = name; - this.enumField = enumField; - } + public BeanWithEnum(boolean boolField, String name, BooleanEnum enumField) { + this.boolField = boolField; + this.name = name; + this.enumField = enumField; + } - public boolean isBoolField() { - return boolField; - } + public boolean isBoolField() { + return boolField; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public BooleanEnum getEnumField() { - return enumField; - } + public BooleanEnum getEnumField() { + return enumField; + } - public void setBoolField(boolean boolField) { - this.boolField = boolField; - } + public void setBoolField(boolean boolField) { + this.boolField = boolField; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public void setEnumField(BooleanEnum enumField) { - this.enumField = enumField; - } + public void setEnumField(BooleanEnum enumField) { + this.enumField = enumField; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnum.java b/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnum.java index f37aabd5..8b85ae29 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnum.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnum.java @@ -1,45 +1,44 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue311; public enum BooleanEnum { - TRUE(true), FALSE(false), UNKNOWN(); + TRUE(true), FALSE(false), UNKNOWN(); - private boolean boolValue; - private boolean defined; + private final boolean boolValue; + private final boolean defined; - BooleanEnum(boolean p) { - boolValue = p; - defined = true; - } + BooleanEnum(boolean p) { + boolValue = p; + defined = true; + } - BooleanEnum() { - boolValue = false; - defined = false; - } + BooleanEnum() { + boolValue = false; + defined = false; + } - boolean getBoolValue() { - if (!defined) - throw new IllegalArgumentException("Undefined has no value"); - else - return boolValue; + boolean getBoolValue() { + if (!defined) { + throw new IllegalArgumentException("Undefined has no value"); + } else { + return boolValue; } + } - boolean isDefined() { - return defined; - } -}
\ No newline at end of file + boolean isDefined() { + return defined; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnumTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnumTest.java index 3f0107ac..205dd060 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnumTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue311/BooleanEnumTest.java @@ -1,20 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue311; +import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; @@ -26,87 +26,92 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import static org.junit.Assert.assertEquals; - public class BooleanEnumTest { - @Test - public void loadEnum() { - - Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); - BeanWithEnum parsed = yaml.loadAs("{boolField: true, enumField: true, name: '10'}", BeanWithEnum.class); - //System.out.println(parsed.getEnumField()); - assertEquals(BooleanEnum.TRUE, parsed.getEnumField()); - assertEquals("10", parsed.getName()); + @Test + public void loadEnum() { + + Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); + BeanWithEnum parsed = + yaml.loadAs("{boolField: true, enumField: true, name: '10'}", BeanWithEnum.class); + // System.out.println(parsed.getEnumField()); + assertEquals(BooleanEnum.TRUE, parsed.getEnumField()); + assertEquals("10", parsed.getName()); + } + + @Test + public void loadEnumUndefined() { + + Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); + BeanWithEnum parsed = + yaml.loadAs("{boolField: true, enumField: nonsense, name: bar}", BeanWithEnum.class); + // System.out.println(parsed.getEnumField()); + assertEquals(BooleanEnum.UNKNOWN, parsed.getEnumField()); + assertEquals("bar", parsed.getName()); + } + + @Test + public void dumpEnum() { + + BeanWithEnum bean = new BeanWithEnum(true, "10", BooleanEnum.TRUE); + Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); + String output = yaml.dumpAs(bean, Tag.MAP, DumperOptions.FlowStyle.FLOW); + assertEquals("{boolField: true, enumField: 'true', name: '10'}\n", output); + } + + class MyRepresenter extends Representer { + + public MyRepresenter() { + this.representers.put(BooleanEnum.class, new RepresentEnum()); } - @Test - public void loadEnumUndefined() { - - Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); - BeanWithEnum parsed = yaml.loadAs("{boolField: true, enumField: nonsense, name: bar}", BeanWithEnum.class); - //System.out.println(parsed.getEnumField()); - assertEquals(BooleanEnum.UNKNOWN, parsed.getEnumField()); - assertEquals("bar", parsed.getName()); - } + private class RepresentEnum implements Represent { - @Test - public void dumpEnum() { + public Node representData(Object data) { + BooleanEnum myEnum = (BooleanEnum) data; + String value; + switch (myEnum) { + case TRUE: + value = "true"; + break; - BeanWithEnum bean = new BeanWithEnum(true, "10", BooleanEnum.TRUE); - Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); - String output = yaml.dumpAs(bean, Tag.MAP, DumperOptions.FlowStyle.FLOW); - assertEquals("{boolField: true, enumField: 'true', name: '10'}\n", output); - } + case FALSE: + value = "false"; + break; - class MyRepresenter extends Representer { - public MyRepresenter() { - this.representers.put(BooleanEnum.class, new RepresentEnum()); - } + case UNKNOWN: + value = "unknown"; + break; - private class RepresentEnum implements Represent { - public Node representData(Object data) { - BooleanEnum myEnum = (BooleanEnum) data; - String value; - switch (myEnum) { - case TRUE: - value = "true"; - break; - - case FALSE: - value = "false"; - break; - - case UNKNOWN: - value = "unknown"; - break; - - default: - throw new IllegalArgumentException(); - } - return representScalar(Tag.STR, value); - } + default: + throw new IllegalArgumentException(); } + return representScalar(Tag.STR, value); + } } + } - class MyConstructor extends Constructor { - public MyConstructor() { - this.yamlClassConstructors.put(NodeId.scalar, new ConstructEnum()); - } + class MyConstructor extends Constructor { + + public MyConstructor() { + this.yamlClassConstructors.put(NodeId.scalar, new ConstructEnum()); + } - private class ConstructEnum extends ConstructScalar { - public Object construct(Node node) { - if (node.getType().equals(BooleanEnum.class)) { - String val = (String) constructScalar((ScalarNode) node); - if ("true".equals(val)) { - return BooleanEnum.TRUE; - } else if ("false".equals(val)) { - return BooleanEnum.FALSE; - } else - return BooleanEnum.UNKNOWN; - } - return super.construct(node); - } + private class ConstructEnum extends ConstructScalar { + + public Object construct(Node node) { + if (node.getType().equals(BooleanEnum.class)) { + String val = constructScalar((ScalarNode) node); + if ("true".equals(val)) { + return BooleanEnum.TRUE; + } else if ("false".equals(val)) { + return BooleanEnum.FALSE; + } else { + return BooleanEnum.UNKNOWN; + } } + return super.construct(node); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue318/ContextClassLoaderTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue318/ContextClassLoaderTest.java index 82f29ee7..a9ae9dca 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue318/ContextClassLoaderTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue318/ContextClassLoaderTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue318; @@ -27,7 +25,6 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Properties; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,102 +32,116 @@ import org.yaml.snakeyaml.Yaml; public class ContextClassLoaderTest { - static public class DomainBean { - - private int value = 0; - - public void setValue(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + value; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DomainBean other = (DomainBean) obj; - if (value != other.value) - return false; - return true; - } + static public class DomainBean { + + private int value = 0; + + public void setValue(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + value; + return result; } - private URLClassLoader yamlCL; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + DomainBean other = (DomainBean) obj; + return value == other.value; + } - @Before - public void before() throws MalformedURLException { - Properties classpath = new Properties(); - InputStream cpProperties = getClass().getResourceAsStream("classpath.properties"); - try { - classpath.load(cpProperties); - } catch (IOException e2) { - fail(e2.getLocalizedMessage()); - } + } - File runtimeClassesDir = new File(classpath.getProperty("runtime_classes_dir")); + private URLClassLoader yamlCL; - yamlCL = new URLClassLoader(new URL[] { runtimeClassesDir.toURI().toURL() }, null); + @Before + public void before() throws MalformedURLException { + Properties classpath = new Properties(); + InputStream cpProperties = getClass().getResourceAsStream("classpath.properties"); + try { + classpath.load(cpProperties); + } catch (IOException e2) { + fail(e2.getLocalizedMessage()); } - @After - public void after() { - // URLClassLoader.close is @since 1.7 - // if (yamlCL != null) { - // try { - // yamlCL.close(); - // } catch (IOException e) { - // e.printStackTrace(); - // } finally { + File runtimeClassesDir = new File(classpath.getProperty("runtime_classes_dir")); + + ClassLoader noSnakeYAMLClassLoader = + new ClassLoader(Thread.currentThread().getContextClassLoader()) { + + @Override + protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.startsWith("org.yaml.snakeyaml")) { + return super.loadClass(name, resolve); + } + throw new ClassNotFoundException("Can't load SnakeYaml classes by this ClassLoader"); + } + + }; + + yamlCL = + new URLClassLoader(new URL[] {runtimeClassesDir.toURI().toURL()}, noSnakeYAMLClassLoader); + } + + @After + public void after() { + if (yamlCL != null) { + try { + yamlCL.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { yamlCL = null; - // } - // } + } } + } - @Test(expected = ClassNotFoundException.class) - public void expectNoDomainClassInYamlCL() throws ClassNotFoundException { - yamlCL.loadClass(DomainBean.class.getName()); - } + @Test(expected = ClassNotFoundException.class) + public void expectNoDomainClassInYamlCL() throws ClassNotFoundException { + yamlCL.loadClass(DomainBean.class.getName()); + } - @Test - public void yamlClassInYAMLCL() throws ClassNotFoundException { - yamlCL.loadClass(Yaml.class.getName()); - } + @Test + public void yamlClassInYAMLCL() throws ClassNotFoundException { + yamlCL.loadClass(Yaml.class.getName()); + } - @Test - public void domainInDifferentConstructor() throws ClassNotFoundException, - InstantiationException, IllegalAccessException, NoSuchMethodException, - SecurityException, IllegalArgumentException, InvocationTargetException { + @Test + public void domainInDifferentConstructor() throws ClassNotFoundException, InstantiationException, + IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, + InvocationTargetException { - Class<?> yamlClass = yamlCL.loadClass(Yaml.class.getName()); + Class<?> yamlClass = yamlCL.loadClass(Yaml.class.getName()); - DomainBean bean = new DomainBean(); - bean.setValue(13); + DomainBean bean = new DomainBean(); + bean.setValue(13); - Object yaml = yamlClass.newInstance(); + Object yaml = yamlClass.newInstance(); - Method dumpMethod = yaml.getClass().getMethod("dump", new Class<?>[] { Object.class }); - String dump = dumpMethod.invoke(yaml, bean).toString(); + Method dumpMethod = yaml.getClass().getMethod("dump", Object.class); + String dump = dumpMethod.invoke(yaml, bean).toString(); - Method loadMethod = yaml.getClass().getMethod("load", new Class<?>[] { String.class }); - DomainBean object = (DomainBean) loadMethod.invoke(yaml, dump); + Method loadMethod = yaml.getClass().getMethod("load", String.class); + DomainBean object = (DomainBean) loadMethod.invoke(yaml, dump); - assertEquals(bean, object); - } + assertEquals(bean, object); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue322_382/PropertyWithoutGetterTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue322_382/PropertyWithoutGetterTest.java new file mode 100644 index 00000000..51dca53e --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue322_382/PropertyWithoutGetterTest.java @@ -0,0 +1,111 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue322_382; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class PropertyWithoutGetterTest { + + @Test + public void testPublicFooWithPublicFields() { + Constructor constructor = new Constructor(); + constructor.addTypeDescription(new TypeDescription(PublicFooWithPublicFields.class, "!foo")); + Yaml yaml = new Yaml(constructor); + + PublicFooWithPublicFields foo = + yaml.loadAs("!foo\ncountryCodes: [NZ, NO]\nsome: NO", PublicFooWithPublicFields.class); + + assertEquals(2, foo.countryCodes.size()); + assertEquals("NZ", foo.countryCodes.get(0)); + assertEquals("The type (String) must be taken from the field.", "NO", foo.countryCodes.get(1)); + assertEquals("NO", foo.some); + } + + @Test + public void testStaticFooWithoutGetter() { + Constructor constructor = new Constructor(); + constructor.addTypeDescription(new TypeDescription(StaticFooWithoutGetter.class, "!foo")); + Yaml yaml = new Yaml(constructor); + + StaticFooWithoutGetter foo = + yaml.loadAs("!foo\ncountryCodes: [NZ, NO]\nsome: NO", StaticFooWithoutGetter.class); + + assertEquals(2, foo.countryCodes.size()); + assertEquals("NZ", foo.countryCodes.get(0)); + assertEquals("The type List(String) must be taken from the setter.", "NO", + foo.countryCodes.get(1)); + assertEquals("NO", foo.some); + } + + @Test + public void testStaticFooWithGetter() { + Constructor constructor = new Constructor(); + constructor.addTypeDescription(new TypeDescription(StaticFooWithGetter.class, "!foo")); + Yaml yaml = new Yaml(constructor); + + StaticFooWithGetter foo = + yaml.loadAs("!foo\ncountryCodes: [NZ, NO]\nsome: NO", StaticFooWithGetter.class); + + assertEquals(2, foo.countryCodes.size()); + assertEquals("NZ", foo.countryCodes.get(0)); + assertEquals("The type List(String) must be taken from the getter.", "NO", + foo.countryCodes.get(1)); + assertEquals("NO", foo.some); + } + + public static class StaticFooWithoutGetter { + + private List<String> countryCodes = new ArrayList<String>(); + private String some; + + public void setCountryCodes(List<String> countryCodes) { + for (Object countryCode : countryCodes) { + // System.out.println(countryCode.getClass().getName()); + } + this.countryCodes = countryCodes; + } + + public void setSome(String sime) { + this.some = sime; + } + } + + public static class StaticFooWithGetter { + + private List<String> countryCodes = new ArrayList<String>(); + private String some; + + public List<String> getCountryCodes() { + return countryCodes; + } + + public void setCountryCodes(List<String> countryCodes) { + for (Object countryCode : countryCodes) { + // System.out.println(countryCode.getClass().getName()); + } + this.countryCodes = countryCodes; + } + + public void setSome(String sime) { + this.some = sime; + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue322_382/PublicFooWithPublicFields.java b/src/test/java/org/yaml/snakeyaml/issues/issue322_382/PublicFooWithPublicFields.java new file mode 100644 index 00000000..9b2a7e5a --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue322_382/PublicFooWithPublicFields.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue322_382; + +import java.util.ArrayList; +import java.util.List; + +public class PublicFooWithPublicFields { + + public List<String> countryCodes = new ArrayList<String>(); + public String some; + + public void setCountryCodes(List<String> countryCodes) { + for (Object countryCode : countryCodes) { + System.out.println(countryCode.getClass().getName()); + } + this.countryCodes = countryCodes; + } + + public void setSome(String sime) { + this.some = sime; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue332/Data.java b/src/test/java/org/yaml/snakeyaml/issues/issue332/Data.java index 56eeb4c7..28cb08e8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue332/Data.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue332/Data.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue332; @@ -19,52 +17,48 @@ import java.beans.ConstructorProperties; import java.math.BigDecimal; public class Data { - private String label; - private String unit; + private String label; - private BigDecimal value; + private String unit; - public BigDecimal getValue() { - return value; - } + private BigDecimal value; - public String getLabel() { - return label; - } + public BigDecimal getValue() { + return value; + } - @ConstructorProperties({"label", "value", "unit"}) - public Data(String label, BigDecimal value, String unit) { - this.label = label; - this.value = value; - this.unit = unit; - } + public String getLabel() { + return label; + } -// public void setLabel(String label) { -// this.label = label; -// } -// -// public void setUnit(String unit) { -// this.unit = unit; -// } -// -// public void setValue(BigDecimal value) { -// this.value = value; -// } + @ConstructorProperties({"label", "value", "unit"}) + public Data(String label, BigDecimal value, String unit) { + this.label = label; + this.value = value; + this.unit = unit; + } - public String getUnit() { - return unit; - } + // public void setLabel(String label) { + // this.label = label; + // } + // + // public void setUnit(String unit) { + // this.unit = unit; + // } + // + // public void setValue(BigDecimal value) { + // this.value = value; + // } - public Data() { - } + public String getUnit() { + return unit; + } - @Override - public String toString() { - return "Data{" + - "label='" + label + '\'' + - ", unit='" + unit + '\'' + - ", value=" + value + - '}'; - } + public Data() {} + + @Override + public String toString() { + return "Data{" + "label='" + label + '\'' + ", unit='" + unit + '\'' + ", value=" + value + '}'; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue332/DataTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue332/DataTest.java index 6b6098df..55a87fd0 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue332/DataTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue332/DataTest.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue332; -import org.junit.Test; -import org.yaml.snakeyaml.Yaml; +import static org.junit.Assert.assertEquals; import java.math.BigDecimal; - -import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; public class DataTest { - @Test - public void testGetUnit() throws Exception { - Data data = new Data("Voltage", BigDecimal.TEN, "V"); - assertEquals("!!org.yaml.snakeyaml.issues.issue332.Data {}", new Yaml().dump(data).trim()); - //TODO assertEquals("!!org.yaml.snakeyaml.issues.issue332.Data {label: Voltage, unit: V, value: !!float '10'}", new Yaml().dump(data).trim()); - } + @Test + public void testGetUnit() throws Exception { + Data data = new Data("Voltage", BigDecimal.TEN, "V"); + assertEquals("!!org.yaml.snakeyaml.issues.issue332.Data {}", new Yaml().dump(data).trim()); + // TODO assertEquals("!!org.yaml.snakeyaml.issues.issue332.Data {label: Voltage, unit: V, value: + // !!float '10'}", new Yaml().dump(data).trim()); + } - @Test - public void testLoad() throws Exception { - String doc = "!!org.yaml.snakeyaml.issues.issue332.Data [Voltage, 10, volts]"; - assertEquals("Data{label='Voltage', unit='volts', value=10}", (new Yaml().load(doc)).toString()); - } -}
\ No newline at end of file + @Test + public void testLoad() throws Exception { + String doc = "!!org.yaml.snakeyaml.issues.issue332.Data [Voltage, 10, volts]"; + assertEquals("Data{label='Voltage', unit='volts', value=10}", + (new Yaml().load(doc)).toString()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue335/JavaLangObjectTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue335/JavaLangObjectTest.java new file mode 100644 index 00000000..0d97c6ef --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue335/JavaLangObjectTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue335; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +public class JavaLangObjectTest { + + @Test + public void testLoadObjectAsMapping() throws Exception { + Object obj = new Yaml().load("!!java.lang.Object {}"); + assertEquals(Object.class, obj.getClass()); + } + + @Test + public void testLoadObjectAsScalar() throws Exception { + try { + new Yaml().load("!!java.lang.Object"); + fail("Object has no single argument constructor"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("No single argument constructor found")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue337/DuplicateKeyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue337/DuplicateKeyTest.java new file mode 100644 index 00000000..c5d88945 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue337/DuplicateKeyTest.java @@ -0,0 +1,176 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue337; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertEquals; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.DuplicateKeyException; + +public class DuplicateKeyTest { + + public static class MapProvider<K, V> { + + private Map<K, V> map = new LinkedHashMap<K, V>(); + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map<K, V> getMap() { + return map; + } + + public void setMap(Map<K, V> map) { + this.map = map; + } + + @SuppressWarnings("rawtypes") + @Override + public boolean equals(Object obj) { + if (obj instanceof MapProvider) { + return map.equals(((MapProvider) obj).getMap()); + } else { + return false; + } + } + + @Override + public int hashCode() { + return map.hashCode(); + } + } + + // test guff + public static class FooEntry { + + private String id; + private String url; + + public FooEntry() {} + + public FooEntry(String id, String url) { + this.id = id; + this.url = url; + } + + public String getUrl() { + return this.url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + } + + @Test + public void defaultConfigurationNoErrorsWithDuplicates() { + String input = Util.getLocalResource("issues/issue337-duplicate-keys.yaml"); + Yaml yaml = new Yaml(); + MapProvider<String, FooEntry> testdata = yaml.loadAs(input, MapProvider.class); + assertEquals("has-dup-keys", testdata.getName()); + assertEquals(1, testdata.getMap().size()); + assertEquals("daaf8911-36e4-4e92-86ea-eb77ac2c1e91", testdata.getMap().get("someitem").getId()); + } + + @Test + public void errorOnDuplicateKeys() { + String input = Util.getLocalResource("issues/issue337-duplicate-keys.yaml"); + LoaderOptions lc = new LoaderOptions(); + lc.setAllowDuplicateKeys(false); + Yaml yaml = new Yaml(lc); + try { + yaml.loadAs(input, MapProvider.class); + } catch (DuplicateKeyException e) { + assertTrue(e.getMessage(), e.getMessage().contains("found duplicate key someitem")); + assertTrue(e.getMessage(), e.getMessage().contains("line 3, column 3")); + } + } + + @Test + public void errorOnDuplicateKeysInJavaBeanProperty() { + String input = Util.getLocalResource("issues/issue337-duplicate-keys-javabean-property.yaml"); + LoaderOptions lc = new LoaderOptions(); + lc.setAllowDuplicateKeys(false); + Yaml yaml = new Yaml(lc); + try { + MapProvider<String, FooEntry> testdata = yaml.loadAs(input, MapProvider.class); + assertEquals("has-dup-keys", testdata.getName()); + } catch (DuplicateKeyException e) { + assertTrue(e.getMessage(), e.getMessage().contains("found duplicate key name")); + assertTrue(e.getMessage(), e.getMessage().contains("line 9, column 1")); + } + } + + @Test + public void acceptDuplicateKeysInJavaBeanProperty() { + String input = Util.getLocalResource("issues/issue337-duplicate-keys-javabean-property.yaml"); + LoaderOptions lc = new LoaderOptions(); + lc.setAllowDuplicateKeys(true); + Yaml yaml = new Yaml(lc); + MapProvider<String, FooEntry> testdata = yaml.loadAs(input, MapProvider.class); + assertEquals("has-dup-keys", testdata.getName()); + } + + @Test + public void defaultConfigUniqueKeysWorks() { + String input = Util.getLocalResource("issues/issue337-duplicate-keys-no-dups.yaml"); + Yaml yaml = new Yaml(); + MapProvider<String, FooEntry> testdata = yaml.loadAs(input, MapProvider.class); + assertEquals("no-dups-test", testdata.getName()); + assertEquals(3, testdata.getMap().size()); + assertEquals("aead4b16-4b61-4eff-b241-6eff26eaa778", + testdata.getMap().get("someitem1").getId()); + assertEquals("daaf8911-36e4-4e92-86ea-eb77ac2c1e91", + testdata.getMap().get("someitem3").getId()); + } + + @Test + public void noDuplicatesConfigMutablePostChange() { + String input = Util.getLocalResource("issues/issue337-duplicate-keys-no-dups.yaml"); + LoaderOptions lc = new LoaderOptions(); + lc.setAllowDuplicateKeys(false); + Yaml yaml = new Yaml(lc); + MapProvider<String, FooEntry> testdata = yaml.loadAs(input, MapProvider.class); + assertEquals("no-dups-test", testdata.getName()); + assertEquals(3, testdata.getMap().size()); + assertEquals("aead4b16-4b61-4eff-b241-6eff26eaa778", + testdata.getMap().get("someitem1").getId()); + assertEquals("daaf8911-36e4-4e92-86ea-eb77ac2c1e91", + testdata.getMap().get("someitem3").getId()); + testdata.getMap().put("someitem1", new FooEntry("AnotherEntry", "AnotherURL")); + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiBean.java new file mode 100644 index 00000000..131ef5a4 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiBean.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue341; + +public class MultiBean { + + private Long id; + private String name; + + public MultiBean(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiRepresenter.java b/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiRepresenter.java new file mode 100644 index 00000000..06efd876 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiRepresenter.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue341; + +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.representer.Representer; + +class MultiRepresenter extends Representer { + + public MultiRepresenter() { + multiRepresenters.put(null, new RepresentAsSring()); + } + + private class RepresentAsSring extends RepresentString { + + public Node representData(Object data) { + return super.representData(data.toString()); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiRepresenterTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiRepresenterTest.java new file mode 100644 index 00000000..60202c09 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue341/MultiRepresenterTest.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue341; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +public class MultiRepresenterTest { + + @Test + public void testLoadObjectAsMapping() throws Exception { + String dump = new Yaml(new MultiRepresenter()).dump(new MultiBean(17L, "foo")); + assertTrue(dump.startsWith("org.yaml.snakeyaml.issues.issue341.MultiBean@")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue348/MultiLevelImmutableTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue348/MultiLevelImmutableTest.java new file mode 100644 index 00000000..accc8f75 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue348/MultiLevelImmutableTest.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue348; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.issues.issue348.model.Bar; +import org.yaml.snakeyaml.issues.issue348.model.Baz; +import org.yaml.snakeyaml.issues.issue348.model.Foo; + +public class MultiLevelImmutableTest { + + @Test + public void testUnexpectedRecursive() { + Yaml yaml = new Yaml(); + String data = Util.getLocalResource("issues/issue348.yaml"); + Map<?, ?> loadedMap = yaml.loadAs(data, Map.class); + + for (Map.Entry<?, ?> entry : loadedMap.entrySet()) { + assertThat(entry.getValue(), instanceOf(List.class)); + } + + Object foo = ((List) loadedMap.get("foo")).get(0); + Object bar = ((List) loadedMap.get("bar")).get(0); + Object baz = ((List) loadedMap.get("baz")).get(0); + assertThat(foo, instanceOf(Foo.class)); + assertThat(bar, instanceOf(Bar.class)); + assertThat(baz, instanceOf(Baz.class)); + + assertEquals(foo, ((Bar) bar).getFoo()); + assertEquals(bar, ((Baz) baz).getBar()); + assertEquals("foo", ((Foo) foo).getFoo()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Bar.java b/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Bar.java new file mode 100644 index 00000000..dd6db14a --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Bar.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue348.model; + +public class Bar { + + private Foo foo; + + public Bar() {} + + public Bar(Foo foo) { + this.foo = foo; + } + + public Foo getFoo() { + return foo; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Baz.java b/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Baz.java new file mode 100644 index 00000000..8ddade2a --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Baz.java @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue348.model; + +public class Baz { + + private Bar bar; + + public Baz() {} + + public Baz(Bar bar) { + this.bar = bar; + } + + public Bar getBar() { + return bar; + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Foo.java b/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Foo.java new file mode 100644 index 00000000..f95b348a --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue348/model/Foo.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue348.model; + +public class Foo { + + private String foo; + + public Foo() {} + + public Foo(String str) { + this.foo = str; + } + + public String getFoo() { + return foo; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue349/YamlBase64BinaryTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue349/YamlBase64BinaryTest.java new file mode 100644 index 00000000..3185cb0c --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue349/YamlBase64BinaryTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue349; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class YamlBase64BinaryTest extends TestCase { + + public void testLocalBinaryTags() throws IOException { + String[] names = {"1", "2", "3"}; + for (String name : names) { + toBeTested(name); + } + } + + public void toBeTested(String name) throws IOException { + Yaml yaml = new Yaml(); + InputStream inputStream = + YamlBase64BinaryTest.class.getResourceAsStream("/issues/issue349-" + name + ".yaml"); + Map<String, Object> bean = yaml.load(inputStream); + byte[] jpeg = (byte[]) bean.get("picture"); + assertEquals(65, jpeg.length); + inputStream.close(); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue351/MergedOrderTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue351/MergedOrderTest.java new file mode 100644 index 00000000..b9400757 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue351/MergedOrderTest.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue351; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +public class MergedOrderTest { + + @SuppressWarnings("rawtypes") + @Test + public void mergedLinkedMapOrder() throws IOException { + Yaml yaml = new Yaml(); + InputStream inputStream = MergedOrderTest.class.getResourceAsStream("/issues/issue351_1.yaml"); + Map<?, ?> bean = yaml.loadAs(inputStream, Map.class); + + Object first = bean.get("prize_cashBack_fixture"); + Object second = bean.get("prize_cashBack_sendEmail_fixture"); + + assertThat(first, instanceOf(Map.class)); + assertThat(second, instanceOf(Map.class)); + + assertArrayEquals(((Map) first).entrySet().toArray(), ((Map) second).entrySet().toArray()); + + inputStream.close(); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue354/PunctuationInTheBeginningTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue354/PunctuationInTheBeginningTest.java new file mode 100644 index 00000000..6aaa7269 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue354/PunctuationInTheBeginningTest.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue354; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; + +/** + * The test does not fix anything. It just proves that SnakeYAML works as it should according to the + * spec 1.1 + */ +public class PunctuationInTheBeginningTest { + + @Test + public void testBacktickAndAtSign() throws IOException { + String input = Util.getLocalResource("issues/issue354.yaml"); + Yaml yaml = new Yaml(); + Map<String, Object> bean = yaml.load(input); + assertEquals("This is\n`a literal\n", bean.get("foo")); + assertEquals("And\n@this\n", bean.get("bar")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue358/UnexpectedIndentTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue358/UnexpectedIndentTest.java new file mode 100644 index 00000000..74cc4104 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue358/UnexpectedIndentTest.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue358; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +public class UnexpectedIndentTest { + + @Test + public void testIndicatorIndentMuchSmaller() { + check(4, 6); // standard + check(4, 5); // ugly, but acceptable, because the YAML will be valid + try { + check(4, 4); + fail("Invalid indent may cause invalid YAML"); + } catch (YAMLException e) { + assertEquals("Indicator indent must be smaller then indent.", e.getMessage()); + } + try { + check(6, 4); + fail("Invalid indent may cause invalid YAML"); + } catch (YAMLException e) { + assertEquals("Indicator indent must be smaller then indent.", e.getMessage()); + } + } + + private void check(int indicatorIndent, int indent) { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setIndicatorIndent(indicatorIndent); + options.setIndent(indent); + Map<String, Object> map = create(); + String dumped = new Yaml(options).dump(map); + // System.out.println(dumped); + Map<String, Object> parsed = new Yaml().load(dumped); + assertEquals(map, parsed); + } + + private Map<String, Object> create() { + Map<String, Object> map = new HashMap<String, Object>(); + List<Map<String, String>> list = new ArrayList<Map<String, String>>(); + Map<String, String> member1 = new HashMap<String, String>(); + member1.put("db_1", "ds"); + member1.put("name", "asd"); + list.add(member1); + Map<String, String> member2 = new HashMap<String, String>(); + member2.put("db_2", "daas"); + member2.put("name", "adas"); + list.add(member2); + map.put("some", list); + return map; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue373/ModelMapIntegerBigdecimal.java b/src/test/java/org/yaml/snakeyaml/issues/issue373/ModelMapIntegerBigdecimal.java new file mode 100644 index 00000000..ab882359 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue373/ModelMapIntegerBigdecimal.java @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue373; + +import java.math.BigDecimal; +import java.util.Map; + +public class ModelMapIntegerBigdecimal { + + private Map<Integer, BigDecimal> mapIntegerBigDecimal; + + public ModelMapIntegerBigdecimal() {} + + public Map<Integer, BigDecimal> getMapIntegerBigDecimal() { + return mapIntegerBigDecimal; + } + + public void setMapIntegerBigDecimal(Map<Integer, BigDecimal> mapIntegerBigDecimal) { + this.mapIntegerBigDecimal = mapIntegerBigDecimal; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue373/UnknownRepresenterTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue373/UnknownRepresenterTest.java new file mode 100644 index 00000000..0820b116 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue373/UnknownRepresenterTest.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue373; + +import static junit.framework.TestCase.assertTrue; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +/** + * Redundant test - it does not test anything. It is here only to prove that SnakeYAML does what it + * should. + */ +public class UnknownRepresenterTest { + + @Test + public void testIndicatorIndentMuchSmaller() { + ModelMapIntegerBigdecimal mv = new ModelMapIntegerBigdecimal(); + + Map<Integer, BigDecimal> m = new HashMap<Integer, BigDecimal>(); + Integer a = 1; + BigDecimal b = new BigDecimal("0.01"); + m.put(a, b); + mv.setMapIntegerBigDecimal(m); + + Yaml yaml = new Yaml(); + String str = yaml.dump(mv); + // System.out.println(str); + assertTrue(str.contains("mapIntegerBigDecimal: {1: 0.01")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue374/NumberAsJavaBeanPropertyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue374/NumberAsJavaBeanPropertyTest.java new file mode 100644 index 00000000..a15725f1 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue374/NumberAsJavaBeanPropertyTest.java @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue374; + +import static org.junit.Assert.assertEquals; + +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.Locale; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + + +public class NumberAsJavaBeanPropertyTest { + + @Test + public void testNumberAsDouble() { + Locale originalLocale = Locale.getDefault(); + + Locale.setDefault(Locale.CANADA_FRENCH); + + AmbiguousNumberType original = new AmbiguousNumberType(); + original.number = 1.1; + assertEquals(Double.class, original.number.getClass()); + + Yaml yaml = new Yaml(); + String str = yaml.dump(original); + + AmbiguousNumberType interpreted = yaml.load(str); + + Locale.setDefault(originalLocale); + assertEquals(original.number, interpreted.number); + } + + public static class AmbiguousNumberType { + + public Number number; + } + + @Test + public void testNumberAsInteger() { + AmbiguousNumberType original = new AmbiguousNumberType(); + original.number = 1; + assertEquals(Integer.class, original.number.getClass()); + + Yaml yaml = new Yaml(); + String str = yaml.dump(original); + + AmbiguousNumberType interpreted = yaml.load(str); + + assertEquals(Double.valueOf(original.number.intValue()), interpreted.number); + } + + @Test + public void testNumberAsLong() { + AmbiguousNumberType original = new AmbiguousNumberType(); + original.number = 1L; + assertEquals(Long.class, original.number.getClass()); + + Yaml yaml = new Yaml(); + String str = yaml.dump(original); + + AmbiguousNumberType interpreted = yaml.load(str); + + assertEquals(Double.valueOf(original.number.intValue()), interpreted.number); + } + + @Test + public void testNumberFormatParse() throws ParseException { + NumberFormat nf = NumberFormat.getInstance(Locale.US); + assertEquals(Long.valueOf(1), nf.parse("1")); + assertEquals("NumberFormat converts 1.0 to 1 - this is against the specification.", + Long.valueOf(1), nf.parse("1.0")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue375/EmptyDocumentTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue375/EmptyDocumentTest.java new file mode 100644 index 00000000..3671e60d --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue375/EmptyDocumentTest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue375; + +import org.junit.Assert; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +public class EmptyDocumentTest { + + @Test + public void returnNullForEmptyDocument() { + Yaml yaml = new Yaml(); + Assert.assertNull(yaml.loadAs("", TestObject.class)); + Assert.assertNull(yaml.loadAs("\n \n", TestObject.class)); + Assert.assertNull(yaml.loadAs("---\n", TestObject.class)); + Assert.assertNull(yaml.loadAs("---\n#comment\n...\n", TestObject.class)); + } + + public static class TestObject { + + private int attribute1; + + public int getAttribute1() { + return attribute1; + } + + public void setAttribute1(int attribute1) { + this.attribute1 = attribute1; + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue377/BillionLaughsAttackTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue377/BillionLaughsAttackTest.java new file mode 100644 index 00000000..ea2e3ce8 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue377/BillionLaughsAttackTest.java @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue377; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +/** + * https://en.wikipedia.org/wiki/Billion_laughs_attack#Variations + */ +public class BillionLaughsAttackTest { + + public static final String data = + "a: &a [\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\"]\n" + + "b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]\n" + "c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]\n" + + "d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]\n" + "e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]\n" + + "f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]\n" + "g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]\n" + + "h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]\n" + "i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]"; + + public static final String scalarAliasesData = + "a: &a foo\n" + "b: *a\n" + "c: *a\n" + "d: *a\n" + "e: *a\n" + "f: *a\n" + "g: *a\n"; + + @Test + public void billionLaughsAttackLoaded() { + LoaderOptions settings = new LoaderOptions(); + settings.setMaxAliasesForCollections(72); + Yaml yaml = new Yaml(settings); + Map map = yaml.load(data); + assertNotNull(map); + } + + @Test + public void billionLaughsAttackExpanded() { + LoaderOptions settings = new LoaderOptions(); + settings.setMaxAliasesForCollections(100); + Yaml yaml = new Yaml(settings); + Map map = yaml.load(data); + assertNotNull(map); + try { + map.toString(); + fail("Expected overflow"); + } catch (Throwable e) { + assertTrue("Catched exception " + e + " is not an instance of OutOfMemoryError", + e instanceof OutOfMemoryError); + } + } + + @Test + public void billionLaughsAttackWithRestrictedAliases() { + LoaderOptions settings = new LoaderOptions(); + Yaml yaml = new Yaml(settings); + try { + yaml.load(data); + fail(); + } catch (YAMLException e) { + assertEquals("Number of aliases for non-scalar nodes exceeds the specified max=50", + e.getMessage()); + } + } + + @Test + public void doNotRestrictScalarAliases() { + LoaderOptions settings = new LoaderOptions(); + settings.setMaxAliasesForCollections(5); // smaller than number of aliases for scalars + Yaml yaml = new Yaml(settings); + Map map = yaml.load(scalarAliasesData); + assertNotNull(map); + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue377/ReferencesTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue377/ReferencesTest.java new file mode 100644 index 00000000..cb17cb8a --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue377/ReferencesTest.java @@ -0,0 +1,131 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue377; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.HashMap; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; + +public class ReferencesTest { + + /** + * Create data which is difficult to parse. + * + * @param size - size of the map, defines the complexity + * @return YAML to parse + */ + private String createDump(int size) { + HashMap root = new HashMap(); + HashMap s1, s2, t1, t2; + s1 = root; + s2 = new HashMap(); + /* + * the time to parse grows very quickly SIZE -> time to parse in seconds 25 -> 1 26 -> 2 27 -> 3 + * 28 -> 8 29 -> 13 30 -> 28 31 -> 52 32 -> 113 33 -> 245 34 -> 500 + */ + for (int i = 0; i < size; i++) { + + t1 = new HashMap(); + t2 = new HashMap(); + t1.put("foo", "1"); + t2.put("bar", "2"); + + s1.put("a", t1); + s1.put("b", t2); + s2.put("a", t1); + s2.put("b", t2); + + s1 = t1; + s2 = t2; + } + + // this is VERY BAD code + // the map has itself as a key (no idea why it may be used except of a DoS attack) + HashMap f = new HashMap(); + f.put(f, "a"); + f.put("g", root); + + Yaml yaml = new Yaml(new SafeConstructor()); + String output = yaml.dump(f); + return output; + } + + @Test + public void referencesWithRecursiveKeysNotAllowedByDefault() { + String output = createDump(30); + // System.out.println(output); + long time1 = System.currentTimeMillis(); + // Load + LoaderOptions settings = new LoaderOptions(); + settings.setMaxAliasesForCollections(150); + Yaml yaml = new Yaml(settings); + try { + yaml.load(output); + fail(); + } catch (Exception e) { + assertEquals("Recursive key for mapping is detected but it is not configured to be allowed.", + e.getMessage()); + } + long time2 = System.currentTimeMillis(); + float duration = (time2 - time1) / 1000; + assertTrue("It should fail quickly. Time was " + duration + " seconds.", duration < 1.0); + } + + @Test + public void parseManyAliasesForCollections() { + String output = createDump(25); + // Load + // long time1 = System.currentTimeMillis(); + LoaderOptions settings = new LoaderOptions(); + settings.setMaxAliasesForCollections(50); + settings.setAllowRecursiveKeys(true); + Yaml yaml = new Yaml(settings); + yaml.load(output); + // Disabling this as it runs slower than 0.9 on my machine + // long time2 = System.currentTimeMillis(); + // double duration = (time2 - time1) / 1000.0; + // assertTrue("It should take time. Time was " + duration + " seconds.", duration > 0.9); + // assertTrue("Time was " + duration + " seconds.", duration < 5.0); + } + + @Test + public void referencesWithRestrictedNesting() { + // without alias restriction this size should occupy tons of CPU, memory and time to parse + int depth = 35; + String bigYAML = createDump(depth); + // Load + long time1 = System.currentTimeMillis(); + LoaderOptions settings = new LoaderOptions(); + settings.setMaxAliasesForCollections(1000); + settings.setAllowRecursiveKeys(true); + settings.setNestingDepthLimit(depth); + Yaml yaml = new Yaml(settings); + try { + yaml.load(bigYAML); + fail(); + } catch (Exception e) { + assertEquals("Nesting Depth exceeded max 35", e.getMessage()); + } + long time2 = System.currentTimeMillis(); + float duration = (time2 - time1) / 1000; + assertTrue("It should fail quickly. Time was " + duration + " seconds.", duration < 1.0); + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue377/ReferencesWithListsTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue377/ReferencesWithListsTest.java new file mode 100644 index 00000000..d1b9dd40 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue377/ReferencesWithListsTest.java @@ -0,0 +1,73 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue377; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; + +/** + * Recursive keys setting has no influence on sequences + */ +public class ReferencesWithListsTest { + + @Test + public void referencesWithRecursiveKeysInListAllowedByDefault() { + String output = "a: &test\n" + "- *test"; + LoaderOptions settings = new LoaderOptions(); + settings.setAllowRecursiveKeys(true); + Yaml yaml = new Yaml(settings); + // System.out.println(output); + Map<String, Object> parsed = yaml.load(output); + assertNotNull(output, parsed); + assertEquals(1, parsed.size()); + } + + @Test + public void referencesWithRecursiveSequences() { + String output = "&test\n" + "- *test"; + LoaderOptions settings = new LoaderOptions(); + settings.setAllowRecursiveKeys(true); + Yaml yaml = new Yaml(settings); + // System.out.println(output); + List<Object> parsed = yaml.load(output); + assertNotNull(output, parsed); + assertEquals(1, parsed.size()); + } + + @Test + public void referencesWithRecursiveKeysInList() { + String output = "a: &test\n" + "- *test"; + LoaderOptions settings = new LoaderOptions(); + settings.setAllowRecursiveKeys(false); + Yaml yaml = new Yaml(settings); + // System.out.println(output); + Map<String, Object> parsed = yaml.load(output); + assertNotNull(output, parsed); + assertEquals(1, parsed.size()); + // try { + // yaml.load(output); + // fail("Should not have been reached, expected an exception because recursive keys are not + // allowed."); + // } catch (Exception e) { + // assertEquals("Recursive key for mapping is detected but it is not configured to be allowed.", + // e.getMessage()); + // } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue38/Bean.java b/src/test/java/org/yaml/snakeyaml/issues/issue38/Bean.java index d644561e..1ac04482 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue38/Bean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue38/Bean.java @@ -1,50 +1,48 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue38; public class Bean { - int value; - - public Bean() { - } - - public Bean(int value) { - this.value = value; - } - - @Override - public boolean equals(Object obj) { - return toString().equals(obj.toString()); - } - - @Override - public int hashCode() { - return value; - } - - @Override - public String toString() { - return "Bean " + String.valueOf(value); - } - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } -}
\ No newline at end of file + + int value; + + public Bean() {} + + public Bean(int value) { + this.value = value; + } + + @Override + public boolean equals(Object obj) { + return toString().equals(obj.toString()); + } + + @Override + public int hashCode() { + return value; + } + + @Override + public String toString() { + return "Bean " + value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue38/BigNumberIdTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue38/BigNumberIdTest.java index d80168ac..22ac5989 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue38/BigNumberIdTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue38/BigNumberIdTest.java @@ -1,46 +1,46 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue38; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; /** * to test http://code.google.com/p/snakeyaml/issues/detail?id=38 */ public class BigNumberIdTest extends TestCase { - @SuppressWarnings("unchecked") - public void testBigNumberFormat() { - List<Bean> list = new ArrayList<Bean>(2000); - for (int i = 1; i < 1010; i++) { - Bean value = new Bean(i); - list.add(value); - list.add(value); - } - Yaml yaml = new Yaml(); - String output = yaml.dump(list); - // System.out.println(output); - // - List<Bean> list2 = (List<Bean>) yaml.load(output); - for (Bean bean : list2) { - assertTrue(bean.getValue() > 0); - } + + @SuppressWarnings("unchecked") + public void testBigNumberFormat() { + List<Bean> list = new ArrayList<Bean>(2000); + for (int i = 1; i < 1010; i++) { + Bean value = new Bean(i); + list.add(value); + list.add(value); + } + LoaderOptions options = new LoaderOptions(); + options.setMaxAliasesForCollections(1500); + Yaml yaml = new Yaml(options); + String output = yaml.dump(list); + // System.out.println(output); + // + List<Bean> list2 = yaml.load(output); + for (Bean bean : list2) { + assertTrue(bean.getValue() > 0); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue383/RepresenterConfigurationTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue383/RepresenterConfigurationTest.java new file mode 100644 index 00000000..a30ae49c --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue383/RepresenterConfigurationTest.java @@ -0,0 +1,197 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue383; + +import static org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK; +import static org.yaml.snakeyaml.DumperOptions.FlowStyle.FLOW; +import static org.yaml.snakeyaml.DumperOptions.ScalarStyle.FOLDED; +import static org.yaml.snakeyaml.DumperOptions.ScalarStyle.PLAIN; + +import java.util.Calendar; +import java.util.TimeZone; +import org.junit.Assert; +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.introspector.PropertyUtils; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.representer.Representer; + +public class RepresenterConfigurationTest { + + @Test + public void testDefaultFlowStyleNotOverridden() { + Representer representer = new Representer(); + representer.setDefaultFlowStyle(BLOCK); + Yaml yaml = new Yaml(representer); + + MappingNode node = (MappingNode) yaml.represent(new TestObject(27, "test")); + Assert.assertEquals(DumperOptions.FlowStyle.BLOCK, node.getFlowStyle()); + } + + @Test + public void testDefaultFlowStyleIsOverridden() { + Representer representer = new Representer(); + representer.setDefaultFlowStyle(BLOCK); + + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setDefaultFlowStyle(FLOW); + + Yaml yaml = new Yaml(representer, dumperOptions); + + MappingNode node = (MappingNode) yaml.represent(new TestObject(27, "test")); + Assert.assertEquals(DumperOptions.FlowStyle.FLOW, node.getFlowStyle()); + } + + @Test + public void testDefaultScalarStyleNotOverridden() { + Representer representer = new Representer(); + representer.setDefaultScalarStyle(FOLDED); + + Yaml yaml = new Yaml(representer); + + ScalarNode node = (ScalarNode) yaml.represent("test"); + Assert.assertEquals(FOLDED, node.getScalarStyle()); + Assert.assertEquals(FOLDED.getChar(), node.getStyle()); + } + + @Test + public void testDefaultScalarStyleOverridden() { + Representer representer = new Representer(); + representer.setDefaultScalarStyle(FOLDED); + + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setDefaultScalarStyle(PLAIN); + + Yaml yaml = new Yaml(representer, dumperOptions); + + ScalarNode node = (ScalarNode) yaml.represent("test"); + Assert.assertEquals(node.getScalarStyle(), PLAIN); + Assert.assertEquals(node.getStyle(), PLAIN.getChar()); + } + + @Test + public void testPlainStyleByDefault() { + Yaml yaml = new Yaml(); + ScalarNode node = (ScalarNode) yaml.represent("test"); + Assert.assertEquals(PLAIN, node.getScalarStyle()); + Assert.assertEquals(PLAIN.getChar(), node.getStyle()); + } + + @Test + public void testTimeZoneNotOverridden() { + Representer representer = new Representer(); + representer.setTimeZone(TimeZone.getTimeZone("Europe/Kiev")); + + Yaml yaml = new Yaml(representer); + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(0); + + ScalarNode node = (ScalarNode) yaml.represent(calendar.getTime()); + + Assert.assertEquals("1970-01-01T03:00:00+03:00", node.getValue()); + } + + @Test + public void testTimeZoneOverridden() { + Representer representer = new Representer(); + representer.setTimeZone(TimeZone.getTimeZone("Europe/Kiev")); + + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setTimeZone(TimeZone.getTimeZone("UTC")); + + Yaml yaml = new Yaml(representer, dumperOptions); + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(0); + + ScalarNode node = (ScalarNode) yaml.represent(calendar.getTime()); + + Assert.assertEquals("1970-01-01T00:00:00Z", node.getValue()); + } + + @Test + public void testDefaultTimeZone() { + Yaml yaml = new Yaml(); + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(0); + + ScalarNode node = (ScalarNode) yaml.represent(calendar.getTime()); + + Assert.assertEquals("1970-01-01T00:00:00Z", node.getValue()); + } + + @Test + public void testAllowReadOnlyPropertiesNotOverridden() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setAllowReadOnlyProperties(true); + Representer representer = new Representer(); + representer.setPropertyUtils(propertyUtils); + + Yaml yaml = new Yaml(representer); + MappingNode mappingNode = (MappingNode) yaml.represent(new TestObject(27, "test")); + Assert.assertEquals(2, mappingNode.getValue().size()); + } + + @Test + public void testAllowReadOnlyPropertiesOverridden() { + PropertyUtils propertyUtils = new PropertyUtils(); + propertyUtils.setAllowReadOnlyProperties(true); + Representer representer = new Representer(); + representer.setPropertyUtils(propertyUtils); + + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setAllowReadOnlyProperties(false); + + Yaml yaml = new Yaml(representer, dumperOptions); + MappingNode mappingNode = (MappingNode) yaml.represent(new TestObject(27, "test")); + Assert.assertEquals(1, mappingNode.getValue().size()); + } + + @Test + public void testReadOnlyPropertiesNotAllowedByDefault() { + Yaml yaml = new Yaml(); + MappingNode mappingNode = (MappingNode) yaml.represent(new TestObject(27, "test")); + Assert.assertEquals(1, mappingNode.getValue().size()); + } + + + public static class TestObject { + + private int id; + + private final String value; + + public TestObject(int id, String value) { + this.id = id; + this.value = value; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getValue() { + return value; + } + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue386/DuplicateKeysOrderTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue386/DuplicateKeysOrderTest.java new file mode 100644 index 00000000..a791f76b --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue386/DuplicateKeysOrderTest.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue386; + +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Map; +import org.junit.Test; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; + +public class DuplicateKeysOrderTest { + + @Test + public void deleteDuplicatKeysInCorrectOrder() { + String input = Util.getLocalResource("issues/issue386-duplicate-keys-order.yaml"); + Yaml yaml = new Yaml(); + Map<String, String> testMap = yaml.load(input); + + assertThat("Number of keys in map", testMap.size(), is(4)); + assertThat(testMap.keySet(), hasItems("key1", "key2", "key3", "lostone")); + + assertThat(testMap.get("key1"), is("1st-2")); + assertThat(testMap.get("key2"), is("2nd-2")); + assertThat(testMap.get("key3"), is("3rd-3")); + assertThat(testMap.get("lostone"), is("Not meeee!!!")); + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue387/YamlExecuteProcessContextTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue387/YamlExecuteProcessContextTest.java new file mode 100644 index 00000000..c4bd63d5 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue387/YamlExecuteProcessContextTest.java @@ -0,0 +1,72 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue387; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; + +import java.util.Collection; +import java.util.Set; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class YamlExecuteProcessContextTest { + + public enum ExecuteProcessConstants { + EXECUTE_ID, EXECUTE_STATUS_START, EXECUTE_STATUS_DONE + } + + @NoArgsConstructor + @AllArgsConstructor + @Data + public static class YamlExecuteProcessContext { + + private String executionID; + private String schemaName; + private String username; + private String hostname; + private String sql; + private Collection<YamlExecuteProcessUnit> unitStatuses; + private Long startTimeMillis; + } + + @NoArgsConstructor + @AllArgsConstructor + @Data + public static class YamlExecuteProcessUnit { + + private String unitID; + private ExecuteProcessConstants status; + } + + @Test + public void parameterizedCollectionTest() { + String marshal = "unitStatuses: !!set\n" + " ? status: EXECUTE_STATUS_DONE\n" + + " unitID: '159917166'\n" + " : null\n"; + Constructor constructor = new Constructor(YamlExecuteProcessContext.class); + YamlExecuteProcessContext unmarshal = + new Yaml(constructor).loadAs(marshal, YamlExecuteProcessContext.class); + + assertThat(unmarshal.getUnitStatuses(), instanceOf(Set.class)); + + for (YamlExecuteProcessUnit unit : unmarshal.getUnitStatuses()) { + assertEquals(unit.getStatus(), ExecuteProcessConstants.EXECUTE_STATUS_DONE); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue395/ReportPositionForDuplicateKeyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue395/ReportPositionForDuplicateKeyTest.java new file mode 100644 index 00000000..f62eaff0 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue395/ReportPositionForDuplicateKeyTest.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue395; + +import static junit.framework.TestCase.assertTrue; + +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.constructor.DuplicateKeyException; +import org.yaml.snakeyaml.representer.Representer; +import org.yaml.snakeyaml.resolver.Resolver; + +public class ReportPositionForDuplicateKeyTest { + + @Test + public void deleteDuplicatKeysInCorrectOrder() { + LoaderOptions loaderOptions = new LoaderOptions(); + loaderOptions.setAllowDuplicateKeys(false); + Yaml yaml = new Yaml(new Constructor(), new Representer(), new DumperOptions(), loaderOptions, + new Resolver()); + try { + yaml.load("key1: a\nkey1: b"); + } catch (DuplicateKeyException e) { + assertTrue(e.getMessage(), e.getMessage().contains("found duplicate key key1")); + assertTrue(e.getMessage(), e.getMessage().contains("line 1, column 1")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInListTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInListTest.java new file mode 100644 index 00000000..9071f903 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInListTest.java @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue397; + +import java.util.List; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class ColonInFlowContextInListTest extends TestCase { + + private final Yaml loader = new Yaml(); + + public void testList() { + List<String> list = loader.load("[ http://foo ]"); + assertTrue(list.contains("http://foo")); + } + + public void testListNoSpaces() { + List<String> list = loader.load("[http://foo]"); + assertTrue(list.contains("http://foo")); + } + + public void testList2() { + List<String> list = loader.load("[ http://foo,http://bar ]"); + assertTrue(list.contains("http://foo")); + assertTrue(list.contains("http://bar")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInMapTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInMapTest.java new file mode 100644 index 00000000..568f6ffd --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInMapTest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue397; + +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class ColonInFlowContextInMapTest extends TestCase { + + private final Yaml loader = new Yaml(); + + public void test1() { + Map<String, Integer> map = loader.load("{a: 1}"); + assertEquals(Integer.valueOf(1), map.get("a")); + } + + public void test2() { + Map<String, Integer> map = loader.load("{a:}"); + assertTrue(map.containsKey("a")); + } + + public void test3() { + Map<String, Integer> map = loader.load("{a}"); + assertTrue(map.containsKey("a")); + } + + public void testTheOnlyCounterIntuitiveCase() { + Map<String, Integer> map = loader.load("{a:1}"); + assertTrue(map.containsKey("a:1")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInSetTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInSetTest.java new file mode 100644 index 00000000..acc12f75 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue397/ColonInFlowContextInSetTest.java @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue397; + +import java.util.Set; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class ColonInFlowContextInSetTest extends TestCase { + + private final Yaml loader = new Yaml(); + + public void testSet() { + Set<String> set = loader.load("!!set { http://foo }"); + assertTrue(set.contains("http://foo")); + } + + public void testSetNoSpaces() { + Set<String> set = loader.load("!!set {http://foo}"); + assertTrue(set.contains("http://foo")); + } + + public void testSet2() { + Set<String> set = loader.load("!!set { http://foo,http://bar }"); + assertTrue(set.contains("http://foo")); + assertTrue(set.contains("http://bar")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBean.java index e0c7dabc..94956ae9 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBean.java @@ -1,34 +1,33 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue40; import java.math.BigDecimal; public class DogFoodBean { - BigDecimal decimal; - public DogFoodBean() { - decimal = BigDecimal.ZERO; - } + BigDecimal decimal; - public BigDecimal getDecimal() { - return decimal; - } + public DogFoodBean() { + decimal = BigDecimal.ZERO; + } - public void setDecimal(BigDecimal decimal) { - this.decimal = decimal; - } + public BigDecimal getDecimal() { + return decimal; + } + + public void setDecimal(BigDecimal decimal) { + this.decimal = decimal; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBeanTest.java index f0891e15..650cad4b 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue40/DogFoodBeanTest.java @@ -1,72 +1,67 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue40; import java.math.BigDecimal; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class DogFoodBeanTest extends TestCase { - public void testOwnBigDecimal() { - DogFoodBean input = new DogFoodBean(); - input.setDecimal(new BigDecimal("5")); - Yaml yaml = new Yaml(); - String text = yaml.dump(input); - // System.out.println(text); - assertEquals("!!org.yaml.snakeyaml.issues.issue40.DogFoodBean {decimal: !!float '5'}\n", - text); - DogFoodBean output = (DogFoodBean) yaml.load(text); - assertEquals(output.getDecimal(), input.getDecimal()); - } + public void testOwnBigDecimal() { + DogFoodBean input = new DogFoodBean(); + input.setDecimal(new BigDecimal("5")); + Yaml yaml = new Yaml(); + String text = yaml.dump(input); + // System.out.println(text); + assertEquals("!!org.yaml.snakeyaml.issues.issue40.DogFoodBean {decimal: !!float '5'}\n", text); + DogFoodBean output = yaml.load(text); + assertEquals(output.getDecimal(), input.getDecimal()); + } - public void testBigDecimalPrecision() { - DogFoodBean input = new DogFoodBean(); - input.setDecimal(new BigDecimal("5.123")); - Yaml yaml = new Yaml(); - String text = yaml.dump(input); - // System.out.println(text); - assertEquals("!!org.yaml.snakeyaml.issues.issue40.DogFoodBean {decimal: 5.123}\n", text); - DogFoodBean output = (DogFoodBean) yaml.load(text); - assertEquals(input.getDecimal(), output.getDecimal()); - } + public void testBigDecimalPrecision() { + DogFoodBean input = new DogFoodBean(); + input.setDecimal(new BigDecimal("5.123")); + Yaml yaml = new Yaml(); + String text = yaml.dump(input); + // System.out.println(text); + assertEquals("!!org.yaml.snakeyaml.issues.issue40.DogFoodBean {decimal: 5.123}\n", text); + DogFoodBean output = yaml.load(text); + assertEquals(input.getDecimal(), output.getDecimal()); + } - public void testBigDecimalNoRootTag() { - DogFoodBean input = new DogFoodBean(); - input.setDecimal(new BigDecimal("5.123")); - Yaml yaml = new Yaml(); - String text = yaml.dumpAsMap(input); - // System.out.println(text); - assertEquals("decimal: 5.123\n", text); - Yaml loader = new Yaml(); - DogFoodBean output = loader.loadAs(text, DogFoodBean.class); - assertEquals(input.getDecimal(), output.getDecimal()); - } + public void testBigDecimalNoRootTag() { + DogFoodBean input = new DogFoodBean(); + input.setDecimal(new BigDecimal("5.123")); + Yaml yaml = new Yaml(); + String text = yaml.dumpAsMap(input); + // System.out.println(text); + assertEquals("decimal: 5.123\n", text); + Yaml loader = new Yaml(); + DogFoodBean output = loader.loadAs(text, DogFoodBean.class); + assertEquals(input.getDecimal(), output.getDecimal()); + } - public void testBigDecimal1() { - Yaml yaml = new Yaml(); - String text = yaml.dump(new BigDecimal("5")); - assertEquals("!!float '5'\n", text); - } + public void testBigDecimal1() { + Yaml yaml = new Yaml(); + String text = yaml.dump(new BigDecimal("5")); + assertEquals("!!float '5'\n", text); + } - public void testBigDecimal2() { - Yaml yaml = new Yaml(); - String text = yaml.dump(new BigDecimal("5.123")); - assertEquals("5.123\n", text); - } + public void testBigDecimal2() { + Yaml yaml = new Yaml(); + String text = yaml.dump(new BigDecimal("5.123")); + assertEquals("5.123\n", text); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue409/DumpEnumAsJavabeanPropertyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue409/DumpEnumAsJavabeanPropertyTest.java new file mode 100644 index 00000000..05819395 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue409/DumpEnumAsJavabeanPropertyTest.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue409; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.Tag; + +public class DumpEnumAsJavabeanPropertyTest extends TestCase { + + public static class Bean { + + public ExtendedEnum myEnum = ExtendedEnum.B; + } + + public enum ExtendedEnum { + A { + public String toGreek() { + return "alpha"; + } + }, + B { + public String toGreek() { + return "beta"; + } + } // issue 409 + } + + public void testDumpExtendedEnum() { + Yaml yaml = new Yaml(); + String text = yaml.dumpAs(new Bean(), Tag.MAP, DumperOptions.FlowStyle.AUTO); + assertEquals("{myEnum: B}\n", text); + Bean actual = yaml.loadAs(text, Bean.class); + assertEquals(ExtendedEnum.B, actual.myEnum); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue416/IndentWithIndicatorTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue416/IndentWithIndicatorTest.java new file mode 100644 index 00000000..5f4769bb --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue416/IndentWithIndicatorTest.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue416; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; + +public class IndentWithIndicatorTest extends TestCase { + + public void testIndentWithIndicator1() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setIndentWithIndicator(true); + options.setIndent(2); + options.setIndicatorIndent(1); + + Yaml yaml = new Yaml(options); + String output = yaml.dump(createData()); + + String doc = Util.getLocalResource("issues/issue416-1.yaml"); + + assertEquals(doc, output); + } + + public void testIndentWithIndicator2() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setIndentWithIndicator(true); + options.setIndent(2); + options.setIndicatorIndent(2); + + Yaml yaml = new Yaml(options); + String output = yaml.dump(createData()); + + String doc = Util.getLocalResource("issues/issue416-2.yaml"); + + assertEquals(doc, output); + } + + public void testIndentWithIndicator3() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setIndentWithIndicator(false); + options.setIndent(4); + options.setIndicatorIndent(2); + + Yaml yaml = new Yaml(options); + String output = yaml.dump(createData()); + + String doc = Util.getLocalResource("issues/issue416_3.yml"); + + assertEquals(doc, output); + } + + private Map<String, Object> createData() { + Map<String, String> fred = new LinkedHashMap<>(); + fred.put("name", "Fred"); + fred.put("role", "creator"); + + Map<String, String> john = new LinkedHashMap<>(); + john.put("name", "John"); + john.put("role", "committer"); + + List<Map<String, String>> developers = new ArrayList<>(); + developers.add(fred); + developers.add(john); + + Map<String, Object> company = new LinkedHashMap<>(); + company.put("developers", developers); + company.put("name", "Yet Another Company"); + company.put("location", "Maastricht"); + + Map<String, Object> data = new LinkedHashMap<>(); + data.put("company", company); + + return data; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue423/DaylightSavingsTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue423/DaylightSavingsTest.java new file mode 100644 index 00000000..6eb68dfd --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue423/DaylightSavingsTest.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue423; + +import java.util.Calendar; +import java.util.TimeZone; +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + +public class DaylightSavingsTest extends TestCase { + + public void testDaylightSavings20181104() { + + // Daylight savings ends on 2018-11-04 and 2 am America/Denver Timezone falls back from -06:00 + // to -07:00 + + TimeZone denverTimeZone = TimeZone.getTimeZone("America/Denver"); + + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setTimeZone(TimeZone.getTimeZone("America/Denver")); + + Yaml yaml = new Yaml(dumperOptions); + + Calendar midnightBeforeFallback = Calendar.getInstance(denverTimeZone); + midnightBeforeFallback.set(2018, Calendar.NOVEMBER, 4, 0, 0); + + String dateString = yaml.dump(midnightBeforeFallback).trim(); // Trim to remove the new line + // character + + assertTrue("Timezone value should be -06:00", dateString.endsWith("-06:00")); + + Calendar oneHourAfterFallback = Calendar.getInstance(denverTimeZone); + oneHourAfterFallback.set(2018, Calendar.NOVEMBER, 4, 3, 0); + + dateString = yaml.dump(oneHourAfterFallback).trim(); + + assertTrue("Timezone value should be -07:00", dateString.endsWith("-07:00")); + + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue426/NullDuplicateKeyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue426/NullDuplicateKeyTest.java new file mode 100644 index 00000000..fe1d30a2 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue426/NullDuplicateKeyTest.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue426; + +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.DuplicateKeyException; + +public class NullDuplicateKeyTest extends TestCase { + + public void testDuplicateKeyIsAllowed() { + Yaml loader = new Yaml(); + Map<String, String> duplicateMap = loader.load("~: foo\n" + "~: bar"); + assertEquals(1, duplicateMap.size()); + assertEquals("bar", duplicateMap.get(null)); + } + + public void testDuplicateKeyIsNotAlowed() { + LoaderOptions options = new LoaderOptions(); + options.setAllowDuplicateKeys(false); + Yaml loader = new Yaml(options); + try { + loader.load("~: foo\n~: bar"); + } catch (DuplicateKeyException e) { + assertTrue(e.getMessage(), e.getMessage().contains("found duplicate key null")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue431/FlexSimleKeyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue431/FlexSimleKeyTest.java new file mode 100644 index 00000000..918361e9 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue431/FlexSimleKeyTest.java @@ -0,0 +1,79 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue431; + +import java.util.HashMap; +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +public class FlexSimleKeyTest extends TestCase { + + private final int len = 130; + + public void testLongKey() { + Yaml dumper = new Yaml(createOptions(len)); + Map<String, Object> root = new HashMap(); + Map<String, String> map = new HashMap<>(); + String key = createKey(len); + map.put(key, "v1"); + root.put("data", map); + assertEquals("data: {? '" + key + "'\n : v1}\n", dumper.dump(root)); + } + + public void testForceLongKeyToBeImplicit() { + Yaml dumper = new Yaml(createOptions(len + 10)); + Map<String, Object> root = new HashMap(); + Map<String, String> map = new HashMap<>(); + String key = createKey(len); + map.put(key, "v1"); + root.put("data", map); + assertEquals("data: {'" + key + "': v1}\n", dumper.dump(root)); + } + + public void testTooLongKeyLength() { + try { + createOptions(1024 + 1); + fail("Length must be restricted to 1024 chars"); + } catch (YAMLException e) { + assertEquals( + "The simple key must not span more than 1024 stream characters. See https://yaml.org/spec/1.1/#id934537", + e.getMessage()); + } + } + + private DumperOptions createOptions(int len) { + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO); + dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); + dumperOptions.setMaxSimpleKeyLength(len); + return dumperOptions; + } + + private String createKey(int length) { + StringBuffer outputBuffer = new StringBuffer(length); + for (int i = 0; i < length; i++) { + outputBuffer.append("" + (i + 1) % 10); + } + String prefix = String.valueOf(length); + String result = + prefix + "_" + outputBuffer.toString().substring(0, length - prefix.length() - 1); + if (result.length() != length) { + throw new RuntimeException("It was: " + result.length()); + } + return result; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue437/BinaryRoundTripTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue437/BinaryRoundTripTest.java new file mode 100644 index 00000000..87786066 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue437/BinaryRoundTripTest.java @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue437; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.events.Event; +import org.yaml.snakeyaml.events.ImplicitTuple; +import org.yaml.snakeyaml.events.ScalarEvent; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.NodeId; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.Tag; + +public class BinaryRoundTripTest extends TestCase { + + public void testBinary() throws UnsupportedEncodingException { + Yaml underTest = new Yaml(); + String source = "\u0096"; + String serialized = underTest.dump(source); + assertEquals("!!binary |-\n" + " wpY=\n", serialized); + // parse back to bytes + byte[] deserialized = underTest.load(serialized); + assertEquals(source, new String(deserialized, StandardCharsets.UTF_8)); + } + + public void testBinaryNode() { + Yaml underTest = new Yaml(); + String source = "\u0096"; + Node node = underTest.represent(source); + // check Node + assertEquals(Tag.BINARY, node.getTag()); + assertEquals(NodeId.scalar, node.getNodeId()); + ScalarNode scalar = (ScalarNode) node; + assertEquals("wpY=", scalar.getValue()); + // check Event + List<Event> events = underTest.serialize(node); + assertEquals(5, events.size()); + ScalarEvent data = (ScalarEvent) events.get(2); + assertEquals(Tag.BINARY.toString(), data.getTag()); + assertEquals(DumperOptions.ScalarStyle.LITERAL, data.getScalarStyle()); + assertEquals("wpY=", data.getValue()); + ImplicitTuple implicit = data.getImplicit(); + assertFalse(implicit.canOmitTagInPlainScalar()); + assertFalse(implicit.canOmitTagInNonPlainScalar()); + } + + public void testStrNode() { + DumperOptions options = new DumperOptions(); + options.setNonPrintableStyle(DumperOptions.NonPrintableStyle.ESCAPE); + Yaml underTest = new Yaml(options); + String source = "\u0096"; + Node node = underTest.represent(source); + assertEquals(Tag.STR, node.getTag()); + assertEquals(NodeId.scalar, node.getNodeId()); + ScalarNode scalar = (ScalarNode) node; + assertEquals("\u0096", scalar.getValue()); + } + + public void testRoundTripBinary() { + DumperOptions options = new DumperOptions(); + options.setNonPrintableStyle(DumperOptions.NonPrintableStyle.ESCAPE); + Yaml underTest = new Yaml(options); + Map<String, String> toSerialized = new HashMap<>(); + toSerialized.put("key", "a\u0096b"); + String output = underTest.dump(toSerialized); + assertEquals("{key: \"a\\x96b\"}\n", output); + Map<String, String> parsed = underTest.load(output); + assertEquals(toSerialized.get("key"), parsed.get("key")); + assertEquals(toSerialized, parsed); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue440/LiteralWithTrailingSpacesTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue440/LiteralWithTrailingSpacesTest.java new file mode 100644 index 00000000..0f5386e3 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue440/LiteralWithTrailingSpacesTest.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue440; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + +public class LiteralWithTrailingSpacesTest extends TestCase { + + public void testLiteral() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.LITERAL); + Yaml yaml = new Yaml(options); + String correct = "this is some text with \"quotes\" and\nline breaks"; + String correctYaml = yaml.dump(correct); + assertEquals("|-\n" + " this is some text with \"quotes\" and\n" + " line breaks\n", + correctYaml); + } + + public void testTrimTrailingWhiteSpace() { + Yaml yaml = new Yaml(); + assertEquals("trailing", yaml.load("trailing ")); + assertEquals("trailing", yaml.load("trailing\r")); + assertEquals("trailing", yaml.load("trailing\n")); + assertEquals("trailing", yaml.load("trailing\r\n")); + assertEquals("trailing", yaml.load("trailing\t\n")); + assertEquals("trailing", yaml.load("trailing\n\n")); + assertEquals("trailing", yaml.load("trailing\n \r \n")); + } + + public void testLiteralWithNewLine() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.LITERAL); + Yaml yaml = new Yaml(options); + String inCorrect = "this is some text with \"quotes\" and \nline breaks"; + String inCorrectYaml = yaml.dump(inCorrect); + // System.out.println(inCorrectYaml); + assertEquals("\"this is some text with \\\"quotes\\\" and \\nline breaks\"\n", inCorrectYaml); + // TODO assertTrue(inCorrectYaml.contains("|")); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue449/LeadingZeroStringTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue449/LeadingZeroStringTest.java new file mode 100644 index 00000000..5eeec69f --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue449/LeadingZeroStringTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue449; + +import java.util.regex.Pattern; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.resolver.Resolver; + +public class LeadingZeroStringTest extends TestCase { + + public void testString() { + Yaml loader = new Yaml(); + // this almost looks like an octal, but it contains digits greater than 7, so it's a string + Object result = loader.load("0123456789"); + assertEquals("0123456789", result); + } + + public void testLeadingZeroForIntIsAccepted() { + Pattern regexp = Resolver.INT; + assertTrue("Valid octal must be recognised.", regexp.matcher("07").matches()); + } + + public void testOctalNumberCannotHave8() { + Pattern regexp = Resolver.INT; + assertFalse(regexp.matcher("08").matches()); + assertFalse(regexp.matcher("0123456789").matches()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue46/FileTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue46/FileTest.java index f80f3ad8..daef2174 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue46/FileTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue46/FileTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue46; import java.io.File; import java.util.HashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; @@ -31,33 +27,36 @@ import org.yaml.snakeyaml.representer.Representer; * Issue 46: Dump a java.io.File object */ public class FileTest extends TestCase { - @SuppressWarnings("unchecked") - public void test() { - File file = new File("src/test/resources/examples/list-bean-1.yaml"); - assertTrue(file.exists()); - Yaml yaml = new Yaml(new MyRepresenter()); - Map<String, File> map = new HashMap<String, File>(); - map.put("one", file); - String output = yaml.dump(map); - // System.out.println(output); - assertTrue(output, output.startsWith("{one: !!java.io.File '")); - assertTrue(output, output.endsWith("list-bean-1.yaml'}\n")); - Map<String, File> parsed = (Map<String, File>) yaml.load(output); - File file2 = parsed.get("one"); - assertTrue(file2.getAbsolutePath(), file2.getAbsolutePath().endsWith("list-bean-1.yaml")); + + @SuppressWarnings("unchecked") + public void test() { + File file = new File("src/test/resources/examples/list-bean-1.yaml"); + assertTrue(file.exists()); + Yaml yaml = new Yaml(new MyRepresenter()); + Map<String, File> map = new HashMap<String, File>(); + map.put("one", file); + String output = yaml.dump(map); + // System.out.println(output); + assertTrue(output, output.startsWith("{one: !!java.io.File '")); + assertTrue(output, output.endsWith("list-bean-1.yaml'}\n")); + Map<String, File> parsed = yaml.load(output); + File file2 = parsed.get("one"); + assertTrue(file2.getAbsolutePath(), file2.getAbsolutePath().endsWith("list-bean-1.yaml")); + } + + public class MyRepresenter extends Representer { + + public MyRepresenter() { + this.representers.put(File.class, new FileRepresenter()); } - public class MyRepresenter extends Representer { - public MyRepresenter() { - this.representers.put(File.class, new FileRepresenter()); - } + public class FileRepresenter implements Represent { - public class FileRepresenter implements Represent { - public Node representData(Object data) { - File file = (File) data; - Node scalar = representScalar(new Tag("!!java.io.File"), file.getAbsolutePath()); - return scalar; - } - } + public Node representData(Object data) { + File file = (File) data; + Node scalar = representScalar(new Tag("!!java.io.File"), file.getAbsolutePath()); + return scalar; + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue467/MergeTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue467/MergeTest.java new file mode 100644 index 00000000..7631337c --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue467/MergeTest.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue467; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class MergeTest extends TestCase { + + public void testMergeAsScalar() { + Yaml loader = new Yaml(); + String data = + "test-list:\n" + " - &1\n" + " a: 1\n" + " b: 2\n" + " - &2 <<: *1\n" + " - <<: *2"; + try { + loader.load(data); + fail(); + } catch (Exception e) { + assertTrue(e.getMessage() + .contains("expected a mapping or list of mappings for merging, but found scalar")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue468/NonAsciiAnchorTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue468/NonAsciiAnchorTest.java new file mode 100644 index 00000000..7374c303 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue468/NonAsciiAnchorTest.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue468; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class NonAsciiAnchorTest extends TestCase { + + private final String NON_ANCHORS = ":,[]{}*&./"; + + public void testNonAsciiAnchor() { + Yaml loader = new Yaml(); + String value = loader.load("&something_ใฟในใฏ ใฟในใฏ"); + assertEquals("ใฟในใฏ", value); + } + + public void testUnderscore() { + Yaml loader = new Yaml(); + String value = loader.load("&_ ใฟในใฏ"); + assertEquals("ใฟในใฏ", value); + } + + public void testSmile() { + Yaml loader = new Yaml(); + String value = loader.load("&\uD83D\uDE01 v1"); + // System.out.println("&\uD83D\uDE01 v1"); + assertEquals("v1", value); + } + + public void testAlpha() { + Yaml loader = new Yaml(); + String value = loader.load("&kรครคk v1"); + assertEquals("v1", value); + } + + public void testNonAllowedAnchor() { + for (int i = 0; i < NON_ANCHORS.length(); i++) { + try { + Character c = NON_ANCHORS.charAt(i); + loadWith(c); + fail("Special chars should not be allowed in anchor name: " + c); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("while scanning an anchor")); + assertTrue(e.getMessage(), e.getMessage().contains("unexpected character found")); + } + } + } + + private void loadWith(char c) { + Yaml loader = new Yaml(); + loader.load("&" + c + " value"); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue47/IncompleteBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue47/IncompleteBean.java index 197946f2..5ce2f2f3 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue47/IncompleteBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue47/IncompleteBean.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue47; public class IncompleteBean { - private int id; - private String name; - public IncompleteBean() { - id = 10; - } + private final int id; + private String name; - public String getName() { - return name; - } + public IncompleteBean() { + id = 10; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public int getId() { - return id; - } -}
\ No newline at end of file + public void setName(String name) { + this.name = name; + } + + public int getId() { + return id; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue47/ReadOnlyPropertiesTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue47/ReadOnlyPropertiesTest.java index a99f63f6..bfb7bd44 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue47/ReadOnlyPropertiesTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue47/ReadOnlyPropertiesTest.java @@ -1,59 +1,56 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue47; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.YAMLException; public class ReadOnlyPropertiesTest extends TestCase { - public void testBean1() { - IncompleteBean bean = new IncompleteBean(); - bean.setName("lunch"); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - assertEquals("name: lunch\n", output); - // - Yaml loader = new Yaml(); - IncompleteBean parsed = loader.loadAs(output, IncompleteBean.class); - assertEquals(bean.getName(), parsed.getName()); - } - public void testBean2() { - IncompleteBean bean = new IncompleteBean(); - bean.setName("lunch"); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - assertEquals("id: 10\nname: lunch\n", output); - // - Yaml loader = new Yaml(); - try { - loader.loadAs(output, IncompleteBean.class); - fail("Setter is missing."); - } catch (YAMLException e) { - String message = e.getMessage(); - assertTrue( - message, - message.contains("Unable to find property 'id' on class: org.yaml.snakeyaml.issues.issue47.IncompleteBean")); - } + public void testBean1() { + IncompleteBean bean = new IncompleteBean(); + bean.setName("lunch"); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + assertEquals("name: lunch\n", output); + // + Yaml loader = new Yaml(); + IncompleteBean parsed = loader.loadAs(output, IncompleteBean.class); + assertEquals(bean.getName(), parsed.getName()); + } + + public void testBean2() { + IncompleteBean bean = new IncompleteBean(); + bean.setName("lunch"); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + assertEquals("id: 10\nname: lunch\n", output); + // + Yaml loader = new Yaml(); + try { + loader.loadAs(output, IncompleteBean.class); + fail("Setter is missing."); + } catch (YAMLException e) { + String message = e.getMessage(); + assertTrue(message, message.contains( + "No writable property 'id' on class: org.yaml.snakeyaml.issues.issue47.IncompleteBean")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue474/ByteParseTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue474/ByteParseTest.java new file mode 100644 index 00000000..74ba36d3 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue474/ByteParseTest.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue474; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class ByteParseTest extends TestCase { + + public void testParseBytes() { + Yaml yamlProcessor = new Yaml(); + Byte[] lb = yamlProcessor.loadAs("[0x01,0x02,0xff,0x7f_ee_00_11]", Byte[].class); + + assertEquals(4, lb.length); + assertEquals(Byte.valueOf((byte) 1), lb[0]); + assertEquals(Byte.valueOf((byte) 2), lb[1]); + assertEquals(Byte.valueOf((byte) -1), lb[2]); + assertEquals(Byte.valueOf((byte) 255), lb[2]); // narrow + assertEquals(Byte.valueOf((byte) 17), lb[3]); + } + + public void testParseShorts() { + Yaml yamlProcessor = new Yaml(); + Short[] lb = yamlProcessor.loadAs("[0x0102,0x7ffe,33000,0x8fff,65000]", Short[].class); + + assertEquals(5, lb.length); + assertEquals(Short.valueOf((short) 258), lb[0]); + assertEquals(Short.valueOf((short) 32766), lb[1]); + assertEquals(Short.valueOf((short) -32536), lb[2]); + assertEquals(Short.valueOf((short) -28673), lb[3]); + assertEquals(Short.valueOf((short) -536), lb[4]); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue478/Location.java b/src/test/java/org/yaml/snakeyaml/issues/issue478/Location.java new file mode 100644 index 00000000..f30ce26e --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue478/Location.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue478; + +public class Location { + + int x; + int y; + int z; + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + public int getZ() { + return z; + } + + public void setZ(int z) { + this.z = z; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue478/PropertyOrderTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue478/PropertyOrderTest.java new file mode 100644 index 00000000..a2a2d256 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue478/PropertyOrderTest.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue478; + +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.introspector.Property; + +public class PropertyOrderTest extends TestCase { + + Set<Property> reverse = new TreeSet<>(); + + public void testParseBytes() { + Yaml y = new Yaml(new org.yaml.snakeyaml.representer.Representer() { + @Override + protected Set<Property> getProperties(Class<? extends Object> type) { + // System.out.println("getProperties: reverse order"); + Iterator<Property> itr = ((TreeSet) super.getProperties(type)).descendingIterator(); + while (itr.hasNext()) { + Property a = itr.next(); + // System.out.println("> " + a.getName()); + reverse.add(a); + } + return reverse; + } + }); + String v = "x: 1\ny: 2\nz: 3\n"; + Location location = y.loadAs(v, Location.class); + + String output = y.dumpAsMap(location); + assertEquals("x", reverse.iterator().next().getName()); + assertEquals(v, output); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue479/CredentialAppConfig.java b/src/test/java/org/yaml/snakeyaml/issues/issue479/CredentialAppConfig.java new file mode 100644 index 00000000..86f1e240 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue479/CredentialAppConfig.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue479; + +public class CredentialAppConfig { + + private Mysql mysql; + private String test1; + + public String getTest1() { + return test1; + } + + public void setTest1(String test1) { + this.test1 = test1; + } + + public Mysql getMysql() { + return mysql; + } + + public void setMysql(Mysql mysql) { + this.mysql = mysql; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue479/DemoProperty.java b/src/test/java/org/yaml/snakeyaml/issues/issue479/DemoProperty.java new file mode 100644 index 00000000..b1043a9e --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue479/DemoProperty.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue479; + +import java.util.Map; + +public class DemoProperty { + + private Map<String, CredentialAppConfig> system; + + public Map<String, CredentialAppConfig> getSystem() { + return system; + } + + public void setSystem(Map<String, CredentialAppConfig> system) { + this.system = system; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue479/MergeKeyDeepMergeTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue479/MergeKeyDeepMergeTest.java new file mode 100644 index 00000000..d9ddadf5 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue479/MergeKeyDeepMergeTest.java @@ -0,0 +1,78 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue479; + +import java.io.InputStream; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.representer.Representer; + +public class MergeKeyDeepMergeTest extends TestCase { + + public void testOnlyTheCurrentMappingIsMerged() { + Constructor constructor = new Constructor(DemoProperty.class); + Representer representer = new Representer(); + representer.getPropertyUtils().setSkipMissingProperties(true); + Yaml yaml = new Yaml(constructor, representer); + + InputStream inputStream = + MergeKeyDeepMergeTest.class.getResourceAsStream("/issues/issue479.yaml"); + DemoProperty property = yaml.load(inputStream); + assertEquals("2", property.getSystem().get("erp").getTest1()); + assertNull(property.getSystem().get("erp").getMysql().getDb_host()); + assertNull(property.getSystem().get("erp").getMysql().getDb_port()); + assertEquals("erp", property.getSystem().get("erp").getMysql().getDb_name()); + assertNull(property.getSystem().get("erp").getMysql().getDb_user()); + assertNull(property.getSystem().get("erp").getMysql().getDb_password()); + } + + public void testMergeKeyDeepMerge() { + Yaml yaml = new Yaml(); + + InputStream inputStream = + MergeKeyDeepMergeTest.class.getResourceAsStream("/issues/issue479.yaml"); + Object property = yaml.load(inputStream); + String output = yaml.dump(property); + // System.out.println(output); + String expected = Util.getLocalResource("issues/issue479-output.yaml"); + assertEquals(expected, output); + } + + public void testMergeAsJavabean() { + Constructor constructor = new Constructor(DemoProperty.class); + Representer representer = new Representer(); + representer.getPropertyUtils().setSkipMissingProperties(true); + Yaml yaml = new Yaml(constructor, representer); + + InputStream inputStream = + MergeKeyDeepMergeTest.class.getResourceAsStream("/issues/issue479-1.yaml"); + DemoProperty property = yaml.load(inputStream); + String output = yaml.dump(property); + // System.out.println(output); + + String v = "!!org.yaml.snakeyaml.issues.issue479.DemoProperty\n" + "system:\n" + " erp:\n" + + " mysql: {db_host: mysql.avatar2.test, db_name: erp, db_password: secret, db_port: 3306,\n" + + " db_user: default}\n" + " test1: '2'\n"; + assertEquals(v, output); + + assertEquals("2", property.getSystem().get("erp").getTest1()); + assertEquals("mysql.avatar2.test", property.getSystem().get("erp").getMysql().getDb_host()); + assertEquals(3306, (int) property.getSystem().get("erp").getMysql().getDb_port()); + assertEquals("erp", property.getSystem().get("erp").getMysql().getDb_name()); + assertEquals("default", property.getSystem().get("erp").getMysql().getDb_user()); + assertEquals("secret", property.getSystem().get("erp").getMysql().getDb_password()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue479/Mysql.java b/src/test/java/org/yaml/snakeyaml/issues/issue479/Mysql.java new file mode 100644 index 00000000..cd778e55 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue479/Mysql.java @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue479; + +public class Mysql { + + private String db_host; + private String db_name; + private Integer db_port; + private String db_user; + private String db_password; + + public String getDb_host() { + return db_host; + } + + public void setDb_host(String db_host) { + this.db_host = db_host; + } + + public Integer getDb_port() { + return db_port; + } + + public void setDb_port(Integer db_port) { + this.db_port = db_port; + } + + public String getDb_user() { + return db_user; + } + + public void setDb_user(String db_user) { + this.db_user = db_user; + } + + public String getDb_password() { + return db_password; + } + + public void setDb_password(String db_password) { + this.db_password = db_password; + } + + public String getDb_name() { + return db_name; + } + + public void setDb_name(String db_name) { + this.db_name = db_name; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue48/Bean.java b/src/test/java/org/yaml/snakeyaml/issues/issue48/Bean.java index cd8ef8a8..ded596a4 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue48/Bean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue48/Bean.java @@ -1,55 +1,53 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue48; public class Bean { - private int value; - private String name; - - public Bean() { - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object obj) { - return toString().equals(obj.toString()); - } - - @Override - public int hashCode() { - return value; - } - - @Override - public String toString() { - return "Bean " + String.valueOf(value); - } - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } -}
\ No newline at end of file + + private int value; + private String name; + + public Bean() {} + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object obj) { + return toString().equals(obj.toString()); + } + + @Override + public int hashCode() { + return value; + } + + @Override + public String toString() { + return "Bean " + value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue48/SkipJavaBeanPropertyTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue48/SkipJavaBeanPropertyTest.java index d5374545..2142e6ac 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue48/SkipJavaBeanPropertyTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue48/SkipJavaBeanPropertyTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue48; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.NodeTuple; @@ -24,33 +21,35 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; public class SkipJavaBeanPropertyTest extends TestCase { - public void testWithNull() { - Bean bean = new Bean(); - bean.setValue(3); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - assertEquals("name: null\nvalue: 3\n", output); - } - public void testWithoutNull() { - Bean bean = new Bean(); - bean.setValue(5); - Yaml yaml = new Yaml(new MyRepresenter()); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - assertEquals("value: 5\n", output); - } + public void testWithNull() { + Bean bean = new Bean(); + bean.setValue(3); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + assertEquals("name: null\nvalue: 3\n", output); + } + + public void testWithoutNull() { + Bean bean = new Bean(); + bean.setValue(5); + Yaml yaml = new Yaml(new MyRepresenter()); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + assertEquals("value: 5\n", output); + } + + private class MyRepresenter extends Representer { - private class MyRepresenter extends Representer { - @Override - protected NodeTuple representJavaBeanProperty(Object bean, Property property, Object value, - Tag customTag) { - if (value != null) { - return super.representJavaBeanProperty(bean, property, value, customTag); - } else { - return null; - } - } + @Override + protected NodeTuple representJavaBeanProperty(Object bean, Property property, Object value, + Tag customTag) { + if (value != null) { + return super.representJavaBeanProperty(bean, property, value, customTag); + } else { + return null; + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue480/AnchorUnicodeTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue480/AnchorUnicodeTest.java new file mode 100644 index 00000000..5c195f66 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue480/AnchorUnicodeTest.java @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue480; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.emitter.EmitterException; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.serializer.AnchorGenerator; + +public class AnchorUnicodeTest extends TestCase { + + private static final Set<Character> INVALID_ANCHOR = new HashSet(); + + static { + INVALID_ANCHOR.add('['); + INVALID_ANCHOR.add(']'); + INVALID_ANCHOR.add('{'); + INVALID_ANCHOR.add('}'); + INVALID_ANCHOR.add(','); + INVALID_ANCHOR.add('*'); + INVALID_ANCHOR.add('&'); + } + + public void testUnicodeAnchor() { + DumperOptions options = new DumperOptions(); + options.setAnchorGenerator(new AnchorGenerator() { + int id = 0; + + @Override + public String nextAnchor(Node node) { + return "ใฟในใฏ" + id++; + } + }); + + Yaml yaml = new Yaml(options); + + List<String> list = new ArrayList<>(); + list.add("abc"); + + List<List<String>> toExport = new ArrayList<>(); + toExport.add(list); + toExport.add(list); + + String output = yaml.dump(toExport); + assertEquals("- &ใฟในใฏ0 [abc]\n- *ใฟในใฏ0\n", output); + } + + public void testInvalidAnchor() { + for (Character ch : INVALID_ANCHOR) { + Yaml yaml = new Yaml(createSettings(ch)); + List<String> list = new ArrayList<>(); + list.add("abc"); + List<List<String>> toExport = new ArrayList<>(); + toExport.add(list); + toExport.add(list); + try { + yaml.dump(toExport); + fail(); + } catch (EmitterException e) { + assertTrue(e.getMessage().startsWith("Invalid character")); + } + } + } + + private DumperOptions createSettings(final Character invalid) { + DumperOptions options = new DumperOptions(); + options.setAnchorGenerator(new AnchorGenerator() { + @Override + public String nextAnchor(Node node) { + return "anchor" + invalid; + } + }); + return options; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue481/DumpAnchorTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue481/DumpAnchorTest.java new file mode 100644 index 00000000..13136292 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue481/DumpAnchorTest.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue481; + +import java.io.StringReader; +import java.io.StringWriter; +import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.serializer.AnchorGenerator; + +public class DumpAnchorTest extends TestCase { + + public void test_anchor_test() { + String str = Util.getLocalResource("issues/issue481.yaml"); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setAnchorGenerator(new AnchorGenerator() { + @Override + public String nextAnchor(Node node) { + return node.getAnchor(); + } + }); + Yaml yaml = new Yaml(options); + + Node node = yaml.compose(new StringReader(str)); + StringWriter out = new StringWriter(); + yaml.serialize(node, out); + assertEquals(str, out.toString()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue484/Base60FloatTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue484/Base60FloatTest.java new file mode 100644 index 00000000..c9897e14 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue484/Base60FloatTest.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue484; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class Base60FloatTest extends TestCase { + + public void test60Float() { + Yaml yamlProcessor = new Yaml(); + Double base60 = yamlProcessor.load("86:00.0"); + assertEquals(5160.0, base60); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue485/RestrictAliasNamesTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue485/RestrictAliasNamesTest.java new file mode 100644 index 00000000..d835ab03 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue485/RestrictAliasNamesTest.java @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue485; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class RestrictAliasNamesTest extends TestCase { + + public void testAliasFromRuby() { + try { + Yaml yamlProcessor = new Yaml(); + yamlProcessor.load("Exclude: **/*_old.rb"); + fail("Should not accept Alias **/*_old.rb"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("unexpected character found *(42)")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarBean.java index 50587eb7..728f441c 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarBean.java @@ -1,39 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue49; import java.util.Calendar; public class CalendarBean { - private Calendar calendar; - private String name; - public String getName() { - return name; - } + private Calendar calendar; + private String name; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public Calendar getCalendar() { - return calendar; - } + public void setName(String name) { + this.name = name; + } - public void setCalendar(Calendar calendar) { - this.calendar = calendar; - } -}
\ No newline at end of file + public Calendar getCalendar() { + return calendar; + } + + public void setCalendar(Calendar calendar) { + this.calendar = calendar; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarTest.java index 09af4a81..d9f10f11 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue49/CalendarTest.java @@ -1,123 +1,120 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue49; +import static org.junit.Assert.assertNotEquals; + import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class CalendarTest extends TestCase { - /** - * Daylight Saving Time is not taken into account - */ - public void testDumpDstIgnored() { - CalendarBean bean = new CalendarBean(); - bean.setName("lunch"); - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(1000000000000L)); - cal.setTimeZone(TimeZone.getTimeZone("GMT-8:00")); - bean.setCalendar(cal); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - assertEquals("calendar: 2001-09-08T17:46:40-8:00\nname: lunch\n", output); - // - Yaml loader = new Yaml(); - CalendarBean parsed = loader.loadAs(output, CalendarBean.class); - assertEquals(bean.getCalendar(), parsed.getCalendar()); - } - /** - * Daylight Saving Time is in effect on this date/time in - * America/Los_Angeles Daylight<br/> - * Saving Time is not in effect on this date/time in GMT - */ - public void testDumpDstIsNotTheSame() { - check(1000000000000L, "America/Los_Angeles", "Must be 7 hours difference.", - "2001-09-08T18:46:40-7:00"); - } + /** + * Daylight Saving Time is not taken into account + */ + public void testDumpDstIgnored() { + CalendarBean bean = new CalendarBean(); + bean.setName("lunch"); + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(1000000000000L)); + cal.setTimeZone(TimeZone.getTimeZone("GMT-8:00")); + bean.setCalendar(cal); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + assertEquals("calendar: 2001-09-08T17:46:40-08:00\nname: lunch\n", output); + // + Yaml loader = new Yaml(); + CalendarBean parsed = loader.loadAs(output, CalendarBean.class); + assertEquals(bean.getCalendar(), parsed.getCalendar()); + } + + /** + * Daylight Saving Time is in effect on this date/time in America/Los_Angeles Daylight<br/> + * Saving Time is not in effect on this date/time in GMT + */ + public void testDumpDstIsNotTheSame() { + check(1000000000000L, "America/Los_Angeles", "Must be 7 hours difference.", + "2001-09-08T18:46:40-07:00"); + } - /** - * Daylight Saving Time is not in effect on this date/time in - * America/Los_Angeles Daylight<br/> - * Saving Time is not in effect on this date/time in GMT - */ - public void testDumpDstIsTheSame() { - check(1266833741374L, "America/Los_Angeles", "Must be 8 hours difference.", - "2010-02-22T02:15:41.374-8:00"); - } + /** + * Daylight Saving Time is not in effect on this date/time in America/Los_Angeles Daylight<br/> + * Saving Time is not in effect on this date/time in GMT + */ + public void testDumpDstIsTheSame() { + check(1266833741374L, "America/Los_Angeles", "Must be 8 hours difference.", + "2010-02-22T02:15:41.374-08:00"); + } - /** - * Test odd time zone - */ - public void testNepal() { - check(1266833741374L, "Asia/Katmandu", "Must be 5:45 hours difference.", - "2010-02-22T16:00:41.374+5:45"); - } + /** + * Test odd time zone + */ + public void testNepal() { + check(1266833741374L, "Asia/Katmandu", "Must be 5:45 hours difference.", + "2010-02-22T16:00:41.374+05:45"); + } - public void testMoreThen10hours() { - check(1266833741374L, "Asia/Kamchatka", "Must be 12 hours difference.", - "2010-02-22T22:15:41.374+12:00"); - } + public void testMoreThen10hours() { + check(1266833741374L, "Asia/Kamchatka", "Must be 12 hours difference.", + "2010-02-22T22:15:41.374+12:00"); + } - private void check(long time, String timeZone, String warning, String etalon) { - CalendarBean bean = new CalendarBean(); - bean.setName("lunch"); - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(time)); - cal.setTimeZone(TimeZone.getTimeZone(timeZone)); - bean.setCalendar(cal); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - assertEquals(warning, "calendar: " + etalon + "\nname: lunch\n", output); - // - Yaml loader = new Yaml(); - CalendarBean parsed = loader.loadAs(output, CalendarBean.class); - assertFalse("TimeZone must deviate.", bean.getCalendar().equals(parsed.getCalendar())); - assertEquals(bean.getCalendar().getTimeInMillis(), parsed.getCalendar().getTimeInMillis()); - } + private void check(long time, String timeZone, String warning, String etalon) { + CalendarBean bean = new CalendarBean(); + bean.setName("lunch"); + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(time)); + cal.setTimeZone(TimeZone.getTimeZone(timeZone)); + bean.setCalendar(cal); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + assertEquals(warning, "calendar: " + etalon + "\nname: lunch\n", output); + // + Yaml loader = new Yaml(); + CalendarBean parsed = loader.loadAs(output, CalendarBean.class); + assertNotEquals("TimeZone must deviate.", bean.getCalendar(), parsed.getCalendar()); + assertEquals(bean.getCalendar().getTimeInMillis(), parsed.getCalendar().getTimeInMillis()); + } - public void testLoadBean() { - Yaml beanLoader = new Yaml(); - CalendarBean bean = beanLoader.loadAs( - "calendar: 2001-12-14t21:59:43.10-05:00\nname: dinner", CalendarBean.class); - assertEquals("dinner", bean.getName()); - Calendar calendar = bean.getCalendar(); - assertEquals(TimeZone.getTimeZone("GMT-5:00").getOffset(calendar.getTime().getTime()), - calendar.getTimeZone().getOffset(calendar.getTime().getTime())); - // - Yaml yaml = new Yaml(); - Date date = (Date) yaml.load("2001-12-14t21:59:43.10-05:00"); - assertEquals(date, calendar.getTime()); - } + public void testLoadBean() { + Yaml beanLoader = new Yaml(); + CalendarBean bean = beanLoader.loadAs("calendar: 2001-12-14t21:59:43.10-05:00\nname: dinner", + CalendarBean.class); + assertEquals("dinner", bean.getName()); + Calendar calendar = bean.getCalendar(); + assertEquals(TimeZone.getTimeZone("GMT-5:00").getOffset(calendar.getTime().getTime()), + calendar.getTimeZone().getOffset(calendar.getTime().getTime())); + // + Yaml yaml = new Yaml(); + Date date = yaml.load("2001-12-14t21:59:43.10-05:00"); + assertEquals(date, calendar.getTime()); + } - public void testLoadWithTag() { - Yaml yaml = new Yaml(); - GregorianCalendar calendar = (GregorianCalendar) yaml - .load("!!java.util.GregorianCalendar 2001-12-14t21:59:43.10-05:00"); - assertEquals(TimeZone.getTimeZone("GMT-5:00").getOffset(calendar.getTime().getTime()), - calendar.getTimeZone().getOffset(calendar.getTime().getTime())); - // - Date date = (Date) yaml.load("2001-12-14t21:59:43.10-05:00"); - assertEquals(date, calendar.getTime()); - } + public void testLoadWithTag() { + Yaml yaml = new Yaml(); + GregorianCalendar calendar = + yaml.load("!!java.util.GregorianCalendar 2001-12-14t21:59:43.10-05:00"); + assertEquals(TimeZone.getTimeZone("GMT-5:00").getOffset(calendar.getTime().getTime()), + calendar.getTimeZone().getOffset(calendar.getTime().getTime())); + // + Date date = yaml.load("2001-12-14t21:59:43.10-05:00"); + assertEquals(date, calendar.getTime()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue50/SnakeyamlTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue50/SnakeyamlTest.java index b288f80a..141d93cf 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue50/SnakeyamlTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue50/SnakeyamlTest.java @@ -1,75 +1,76 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue50; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; /** * test issue 50. */ public class SnakeyamlTest extends TestCase { - public static interface SomeBean { - String getAttribute1(); - String getAttribute2(); - } + public interface SomeBean { + + String getAttribute1(); - /* public */static abstract class BaseSomeBean implements SomeBean { - private String attribute1; + String getAttribute2(); + } - public String getAttribute1() { - return attribute1; - } + /* public */static abstract class BaseSomeBean implements SomeBean { - public void setAttribute1(String attribute1) { - this.attribute1 = attribute1; - } + private String attribute1; + + public String getAttribute1() { + return attribute1; } - public static final class SomeBeanImpl extends BaseSomeBean { - private String attribute2; + public void setAttribute1(String attribute1) { + this.attribute1 = attribute1; + } + } - public SomeBeanImpl(final String attribute1, final String attribute2) { - setAttribute1(attribute1); - setAttribute2(attribute2); - } + public static final class SomeBeanImpl extends BaseSomeBean { - public String getAttribute2() { - return attribute2; - } + private String attribute2; - public void setAttribute2(String attribute2) { - this.attribute2 = attribute2; - } + public SomeBeanImpl(final String attribute1, final String attribute2) { + setAttribute1(attribute1); + setAttribute2(attribute2); + } + + public String getAttribute2() { + return attribute2; + } - @Override - public String toString() { - return "SomeBeanImpl"; - } + public void setAttribute2(String attribute2) { + this.attribute2 = attribute2; } - public void testIntrospector() { - SomeBean someBean = new SomeBeanImpl("value1", "value2"); - Yaml dumper = new Yaml(); - String output = dumper.dump(someBean); - // System.out.println(output); - assertEquals( - "!!org.yaml.snakeyaml.issues.issue50.SnakeyamlTest$SomeBeanImpl {attribute1: value1,\n attribute2: value2}\n", - output); + @Override + public String toString() { + return "SomeBeanImpl"; } + } + + public void testIntrospector() { + SomeBean someBean = new SomeBeanImpl("value1", "value2"); + Yaml dumper = new Yaml(); + String output = dumper.dump(someBean); + // System.out.println(output); + assertEquals( + "!!org.yaml.snakeyaml.issues.issue50.SnakeyamlTest$SomeBeanImpl {attribute1: value1,\n attribute2: value2}\n", + output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue500/FailIteratorOnlyWhenErrorFoundTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue500/FailIteratorOnlyWhenErrorFoundTest.java new file mode 100644 index 00000000..ed4485a2 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue500/FailIteratorOnlyWhenErrorFoundTest.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue500; + +import java.util.Iterator; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class FailIteratorOnlyWhenErrorFoundTest extends TestCase { + + public void testFailure() { + try { + Yaml yamlProcessor = new Yaml(); + String data = + "a: 1\n" + "---\n" + "Some comment \n" + "\n" + "\n" + "b: 2\n" + "\n" + "c: 3\n" + "---"; + Iterable<Object> parsed = yamlProcessor.loadAll(data); + Iterator<Object> iterator = parsed.iterator(); + assertNotNull(iterator.next()); // no failure, first document id valid + iterator.next(); + // for (Object obj : parsed) { + // assertNotNull(obj); + // System.out.println(obj); + // } + fail("Should not accept the second document"); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("in 'reader', line 6, column 2:")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue506/ParseStringsThatAlmostLookLikeInts.java b/src/test/java/org/yaml/snakeyaml/issues/issue506/ParseStringsThatAlmostLookLikeInts.java new file mode 100644 index 00000000..ed55cd61 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue506/ParseStringsThatAlmostLookLikeInts.java @@ -0,0 +1,106 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue506; + +import java.util.regex.Pattern; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.resolver.Resolver; + +public class ParseStringsThatAlmostLookLikeInts extends TestCase { + + public void testHexPrefixedString() { + String in = "0x_"; + String expected = "0x_"; + Object out = new Yaml().load(in); + assertEquals(expected, out); + } + + public void testHexInt() { + String in = "0x_AB"; + Integer expected = 171; + Object out = new Yaml().load(in); + assertEquals(expected, out); + } + + public void testOctalPrefixedString() { + String in = "0_"; + String expected = "0_"; + Object out = new Yaml().load(in); + assertEquals(expected, out); + } + + public void testOctalInt() { + String in = "0_123"; + Integer expected = 83; + Object out = new Yaml().load(in); + assertEquals(expected, out); + } + + public void testBinaryPrefixedString() { + String in = "0b_"; + String expected = "0b_"; + Object out = new Yaml().load(in); + assertEquals(expected, out); + } + + public void testBinaryInt() { + String in = "0b_101"; + Integer expected = 5; + Object out = new Yaml().load(in); + assertEquals(expected, out); + } + + public void testDecimalish() { + String in = "-_"; + String expected = "-_"; + Object out = new Yaml().load(in); + assertEquals(expected, out); + } + + public void testIntPattern() { + Pattern regexp = Resolver.INT; + assertTrue(regexp.matcher("0xabc").matches()); + assertTrue(regexp.matcher("0x_abc").matches()); + assertFalse(regexp.matcher("0x_").matches()); + assertTrue(regexp.matcher("0b_01_00").matches()); + assertFalse(regexp.matcher("0b_").matches()); + assertTrue(regexp.matcher("0_77").matches()); + assertFalse(regexp.matcher("0_").matches()); + } + + public void testFloatPattern() { + Pattern regexp = Resolver.FLOAT; + assertFalse(regexp.matcher("0123456789").matches()); + assertFalse(regexp.matcher("123456789").matches()); + + assertTrue(regexp.matcher("00.3").matches()); + assertTrue(regexp.matcher("00.003").matches()); + assertTrue(regexp.matcher("02.003").matches()); + assertTrue(regexp.matcher("-02.003").matches()); + assertTrue(regexp.matcher("-02.003_001").matches()); + assertTrue(regexp.matcher("-2_000.003_001").matches()); + assertTrue(regexp.matcher(".3").matches()); + assertTrue(regexp.matcher("-.3").matches()); + assertTrue(regexp.matcher("+0.3").matches()); + assertTrue(regexp.matcher("8.1e-06").matches()); + assertTrue(regexp.matcher("8e-06").matches()); + assertTrue(regexp.matcher("8e06").matches()); + assertTrue(regexp.matcher("8e6").matches()); + assertTrue(regexp.matcher("8E6").matches()); + assertTrue(regexp.matcher("8E+06").matches()); + assertTrue(regexp.matcher("8e+6").matches()); + assertTrue(regexp.matcher("+8e+6").matches()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue51/UnicodeStyleTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue51/UnicodeStyleTest.java index 45706652..cdd0a631 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue51/UnicodeStyleTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue51/UnicodeStyleTest.java @@ -1,44 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue51; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.ScalarStyle; import org.yaml.snakeyaml.Yaml; /** - * @see <a - * href="http://code.google.com/p/snakeyaml/issues/detail?id=51">Issue</a> + * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=51">Issue</a> */ public class UnicodeStyleTest extends TestCase { - public void testFoldedStyle() { - Yaml yaml = new Yaml(); - String output = yaml.dump("รญ"); - // System.out.println(output); - assertEquals("รญ\n", output); - } - public void testDoubleQuotedStyle() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); - Yaml yaml = new Yaml(options); - String output = yaml.dump("รญ"); - // System.out.println(output); - assertEquals("\"รญ\"\n", output); - } + public void testFoldedStyle() { + Yaml yaml = new Yaml(); + String output = yaml.dump("รญ"); + // System.out.println(output); + assertEquals("รญ\n", output); + } + + public void testDoubleQuotedStyle() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); + Yaml yaml = new Yaml(options); + String output = yaml.dump("รญ"); + // System.out.println(output); + assertEquals("\"รญ\"\n", output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue512/ListWithCommentTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue512/ListWithCommentTest.java new file mode 100644 index 00000000..cb8fc345 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue512/ListWithCommentTest.java @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue512; + +import java.util.List; +import junit.framework.TestCase; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; + +public class ListWithCommentTest extends TestCase { + + public void testList() { + String str = Util.getLocalResource("issues/issue512.yaml"); + LoaderOptions options = new LoaderOptions(); + options.setProcessComments(true); + Yaml yaml = new Yaml(options); + List<String> obj = yaml.load(str); + assertEquals(2, obj.size()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue517/TrailingTabTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue517/TrailingTabTest.java new file mode 100644 index 00000000..722fd145 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue517/TrailingTabTest.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue517; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class TrailingTabTest extends TestCase { + + public void testTrailingTab() { + String str = "'bar'\t"; + Yaml yaml = new Yaml(); + try { + Object obj = yaml.load(str); + fail("Issue 517"); // TODO FIXME trailing TAB should be ignored + assertNotNull(obj); + } catch (Exception e) { + assertTrue(e.getMessage(), + e.getMessage().contains("found character '\\t(TAB)' that cannot start any token.")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue52/LineBreakDooubleQuotedTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue52/LineBreakDooubleQuotedTest.java index 8682fdde..0bbf58c7 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue52/LineBreakDooubleQuotedTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue52/LineBreakDooubleQuotedTest.java @@ -1,57 +1,54 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue52; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.ScalarStyle; import org.yaml.snakeyaml.Yaml; /** - * @see <a - * href="http://code.google.com/p/snakeyaml/issues/detail?id=52">Issue</a> + * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=52">Issue</a> */ public class LineBreakDooubleQuotedTest extends TestCase { - public void testDoubleQuotedStyle() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); - options.setWidth(20); - options.setIndent(4); - Yaml yaml = new Yaml(options); - String etalon = "12345678901234567890\n\n123 456"; - String output = yaml.dump(etalon); - // System.out.println(output); - assertEquals("\"12345678901234567890\\n\\\n \\n123 456\"\n", output); - String parsed = (String) yaml.load(output); - assertEquals(etalon, parsed); - } - public void testDoubleQuotedStyleNoLineSplit() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); - options.setWidth(20); - options.setSplitLines(false); - options.setIndent(4); - Yaml yaml = new Yaml(options); - String etalon = "12345678901234567890\n\n123 456"; - String output = yaml.dump(etalon); - // System.out.println(output); - assertEquals("\"12345678901234567890\\n\\n123 456\"\n", output); - String parsed = (String) yaml.load(output); - assertEquals(etalon, parsed); - } + public void testDoubleQuotedStyle() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); + options.setWidth(20); + options.setIndent(4); + Yaml yaml = new Yaml(options); + String etalon = "12345678901234567890\n\n123 456"; + String output = yaml.dump(etalon); + // System.out.println(output); + assertEquals("\"12345678901234567890\\n\\\n \\n123 456\"\n", output); + String parsed = yaml.load(output); + assertEquals(etalon, parsed); + } + + public void testDoubleQuotedStyleNoLineSplit() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); + options.setWidth(20); + options.setSplitLines(false); + options.setIndent(4); + Yaml yaml = new Yaml(options); + String etalon = "12345678901234567890\n\n123 456"; + String output = yaml.dump(etalon); + // System.out.println(output); + assertEquals("\"12345678901234567890\\n\\n123 456\"\n", output); + String parsed = yaml.load(output); + assertEquals(etalon, parsed); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue520/ChompingTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue520/ChompingTest.java new file mode 100644 index 00000000..1b4e9384 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue520/ChompingTest.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue520; + +import java.util.Map; +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; + +public class ChompingTest extends TestCase { + + public void testChomp() { + String input = "description: |+\n" + " line\n\n"; + Yaml yaml = new Yaml(); + Map<String, String> obj = yaml.load(input); + assertEquals("line\n\n", obj.get("description")); + + String output = yaml.dump(obj); + assertEquals(input, output); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue522/JavaBeanWithPropertiesLikeBooleanValuesTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue522/JavaBeanWithPropertiesLikeBooleanValuesTest.java new file mode 100644 index 00000000..0a980b5f --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue522/JavaBeanWithPropertiesLikeBooleanValuesTest.java @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue522; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +public class JavaBeanWithPropertiesLikeBooleanValuesTest { + + public static class Workflow { + + public String on; + public String off; + public String y; + public String n; + public String yes; + public String no; + } + + @Test + public void deserialize() { + Yaml yaml = new Yaml(); + + String strYaml = "on: This is on\n" + "off: This is off\n" + "y: This is y\n" + "n: This is n\n" + + "yes: This is yes\n" + "no: This is no\n"; + + Workflow wf = yaml.loadAs(strYaml, Workflow.class); + + assertEquals(wf.on, "This is on"); + assertEquals(wf.off, "This is off"); + assertEquals(wf.y, "This is y"); + assertEquals(wf.n, "This is n"); + assertEquals(wf.yes, "This is yes"); + assertEquals(wf.no, "This is no"); + + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue525/FuzzyStackOverflowTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue525/FuzzyStackOverflowTest.java new file mode 100644 index 00000000..6ab42499 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue525/FuzzyStackOverflowTest.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue525; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +public class FuzzyStackOverflowTest { + + @Test + public void parseOpenUnmatchedMappings() { + try { + Yaml yaml = new Yaml(); + String strYaml = Util.getLocalResource("fuzzer/YamlFuzzer-4626423186325504"); + yaml.load(strYaml); + fail("Should report invalid YAML"); + } catch (YAMLException e) { + assertEquals("Nesting Depth exceeded max 50", e.getMessage()); + } + } + + @Test + public void parseOpenUnmatchedMappingsWithCustomLimit() { + try { + LoaderOptions options = new LoaderOptions(); + options.setNestingDepthLimit(1000); + Yaml yaml = new Yaml(options); + String strYaml = Util.getLocalResource("fuzzer/YamlFuzzer-4626423186325504"); + yaml.load(strYaml); + fail("Should report invalid YAML"); + } catch (YAMLException e) { + assertEquals("Nesting Depth exceeded max 1000", e.getMessage()); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue526/Fuzzy47027Test.java b/src/test/java/org/yaml/snakeyaml/issues/issue526/Fuzzy47027Test.java new file mode 100644 index 00000000..bca42147 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue526/Fuzzy47027Test.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue526; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +// OSS-Fuzz - 47027 +public class Fuzzy47027Test { + + @Test + public void parseOpenUnmatchedSequences_47027() { + try { + Yaml yaml = new Yaml(); + String strYaml = Util.getLocalResource("fuzzer/YamlFuzzer-5427149240139776"); + yaml.load(strYaml); + fail("Should report invalid YAML"); + } catch (YAMLException e) { + assertEquals("Nesting Depth exceeded max 50", e.getMessage()); + } + } + + @Test + public void setCustomLimit100() { + try { + LoaderOptions options = new LoaderOptions(); + options.setNestingDepthLimit(100); + Yaml yaml = new Yaml(options); + String strYaml = Util.getLocalResource("fuzzer/YamlFuzzer-5427149240139776"); + yaml.load(strYaml); + fail("Should report invalid YAML"); + } catch (YAMLException e) { + assertEquals("Nesting Depth exceeded max 100", e.getMessage()); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue527/Fuzzy47047Test.java b/src/test/java/org/yaml/snakeyaml/issues/issue527/Fuzzy47047Test.java new file mode 100644 index 00000000..49848d5b --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue527/Fuzzy47047Test.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue527; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +// Stackoverflow [OSS-Fuzz - 47047] +public class Fuzzy47047Test { + + @Test + public void parseKeyIndicators_47047() { + try { + LoaderOptions options = new LoaderOptions(); + options.setNestingDepthLimit(30); + Yaml yaml = new Yaml(options); + String strYaml = Util.getLocalResource("fuzzer/YamlFuzzer-5868638424399872"); + yaml.load(strYaml); + fail("Should report invalid YAML"); + } catch (YAMLException e) { + assertEquals("Nesting Depth exceeded max 30", e.getMessage()); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue529/Fuzzy47028Test.java b/src/test/java/org/yaml/snakeyaml/issues/issue529/Fuzzy47028Test.java new file mode 100644 index 00000000..02c46878 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue529/Fuzzy47028Test.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue529; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +// StringIndexOutOfBoundsException [OSS-Fuzz 47028] +public class Fuzzy47028Test { + + @Test + public void parseEmptyFloat_47028() { + try { + LoaderOptions options = new LoaderOptions(); + Yaml yaml = new Yaml(options); + yaml.load("- !!float"); + fail("Should report invalid YAML"); + } catch (YAMLException e) { + assertTrue(e.getMessage().contains("while constructing a float")); + assertTrue(e.getMessage().contains("found empty value")); + } + } + + @Test + public void parseEmptyInt_47028() { + try { + LoaderOptions options = new LoaderOptions(); + Yaml yaml = new Yaml(options); + yaml.load("- !!int"); + fail("Should report invalid YAML"); + } catch (YAMLException e) { + assertTrue(e.getMessage().contains("while constructing an int")); + assertTrue(e.getMessage().contains("found empty value")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue530/Fuzzy47039Test.java b/src/test/java/org/yaml/snakeyaml/issues/issue530/Fuzzy47039Test.java new file mode 100644 index 00000000..9c09e1df --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue530/Fuzzy47039Test.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue530; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; + +// Stackoverflow [OSS-Fuzz - 47039] +public class Fuzzy47039Test { + + @Test + public void parseKeyIndicators_47039() { + LoaderOptions options = new LoaderOptions(); + Yaml yaml = new Yaml(options); + String strYaml = Util.getLocalResource("fuzzer/YamlFuzzer-5110034188599296"); + String parsed = yaml.load(strYaml); + assertEquals(strYaml.trim(), parsed); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue531/Fuzzy47081Test.java b/src/test/java/org/yaml/snakeyaml/issues/issue531/Fuzzy47081Test.java new file mode 100644 index 00000000..3410e5f4 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue531/Fuzzy47081Test.java @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue531; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +// Stackoverflow [OSS-Fuzz - 47081] + +/** + * A proof that this issue is a FALSE POSITIVE https://nvd.nist.gov/vuln/detail/CVE-2022-38752 + */ +public class Fuzzy47081Test { + + /** + * Recursive key should NOT be used for untrusted data to avoid + */ + @Test + public void parse47081_no_recursion_allowed() { + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(false); // must be set to false for untrusted source + Yaml yaml = new Yaml(options); + String strYaml = " &a\n" + "- *a\n" + "- *a\n" + "- *a:\n" + "- *a\n" + "- *a\n" + "- *a"; + try { + yaml.load(strYaml); + fail("Should report invalid YAML: " + strYaml); + } catch (YAMLException e) { + assertEquals("Recursive key for mapping is detected but it is not configured to be allowed.", + e.getMessage()); + } + } + + /** + * Recursive list fails (with StackOverflowError) because it is used as a key Recursive key should + * NOT be used for untrusted data + */ + @Test + public void parse47081_allow_recursion() { + try { + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Yaml yaml = new Yaml(options); + String strYaml = "&a\n" + "- *a\n" // if this line is removed, the test properly complains + // about the recursive keys in map -> Recursive key for + // mapping is detected, but it is not configured to be + // allowed. + + "- *a:\n"; // when the colon is removed, the test is Ok, because the recursive list is + // not a key + // System.out.println(strYaml); + yaml.load(strYaml); + fail("Should report invalid YAML: " + strYaml); + } catch (StackOverflowError e) { + assertTrue(true); + } + } + + @Test + public void parse47081_no_colon() { + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Yaml yaml = new Yaml(options); + String strYaml = "&a\n" + "- *a\n" + "- *a\n"; + List<Object> parsed = yaml.load(strYaml); + assertEquals(strYaml, 2, parsed.size()); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue543/Fuzzer50355Test.java b/src/test/java/org/yaml/snakeyaml/issues/issue543/Fuzzer50355Test.java new file mode 100644 index 00000000..a919d08b --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue543/Fuzzer50355Test.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue543; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Util; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; + +// Stackoverflow [OSS-Fuzz - 50355] +public class Fuzzer50355Test { + + @Test + public void parse_50355() { + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(false); + Yaml yaml = new Yaml(options); + String strYaml = Util.getLocalResource("fuzzer/YamlFuzzer-5167495132086272"); + try { + yaml.load(strYaml); + fail("Recursive keys should not be accepted"); + } catch (YAMLException e) { + assertEquals("Recursive key for mapping is detected but it is not configured to be allowed.", + e.getMessage()); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue544/DoubleQuoteTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue544/DoubleQuoteTest.java new file mode 100644 index 00000000..b9a756a1 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue544/DoubleQuoteTest.java @@ -0,0 +1,97 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue544; + +import static org.junit.Assert.assertEquals; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.DumperOptions.ScalarStyle; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.Tag; + +public class DoubleQuoteTest { + + private MappingNode create() { + String content = "๐This process is simple and secure."; + + ScalarNode doubleQuotedKey = + new ScalarNode(Tag.STR, "double_quoted", null, null, ScalarStyle.PLAIN); + ScalarNode doubleQuotedValue = + new ScalarNode(Tag.STR, content, null, null, ScalarStyle.DOUBLE_QUOTED); + NodeTuple doubleQuotedTuple = new NodeTuple(doubleQuotedKey, doubleQuotedValue); + + ScalarNode singleQuotedKey = + new ScalarNode(Tag.STR, "single_quoted", null, null, ScalarStyle.PLAIN); + ScalarNode singleQuotedValue = + new ScalarNode(Tag.STR, content, null, null, ScalarStyle.SINGLE_QUOTED); + NodeTuple singleQuotedTuple = new NodeTuple(singleQuotedKey, singleQuotedValue); + + List<NodeTuple> nodeTuples = new ArrayList<>(); + nodeTuples.add(doubleQuotedTuple); + nodeTuples.add(singleQuotedTuple); + + MappingNode mappingNode = new MappingNode(Tag.MAP, nodeTuples, FlowStyle.BLOCK); + + return mappingNode; + } + + private String emit(DumperOptions dumperOptions) { + Yaml yaml = new Yaml(dumperOptions); + + StringWriter writer = new StringWriter(); + yaml.serialize(create(), writer); + + return writer.toString(); + } + + @Test + public void testUnicode() { + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setAllowUnicode(true); // use as is + String output = emit(dumperOptions); + String expectedOutput = "double_quoted: \"๐This process is simple and secure.\"\n" + + "single_quoted: '๐This process is simple and secure.'\n"; + + assertEquals(expectedOutput, output); + } + + @Test + public void testSubstitution() { + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setAllowUnicode(false); // substitute with U notation + String output = emit(dumperOptions); + String expectedOutput = "double_quoted: \"\\U0001f510This process is simple and secure.\"\n" + + "single_quoted: \"\\U0001f510This process is simple and secure.\"\n"; + + assertEquals(expectedOutput, output); + } + + @Test + public void testDefault() { + DumperOptions dumperOptions = new DumperOptions(); + String output = emit(dumperOptions); + String expectedOutput = "double_quoted: \"๐This process is simple and secure.\"\n" + + "single_quoted: '๐This process is simple and secure.'\n"; + + assertEquals(expectedOutput, output); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue547/ByteLimitTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue547/ByteLimitTest.java new file mode 100644 index 00000000..e6eae1e5 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/issues/issue547/ByteLimitTest.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue547; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; + +public class ByteLimitTest { + + @Test + public void testUnicode() { + LoaderOptions options = new LoaderOptions(); + options.setCodePointLimit(15); + Yaml yaml = new Yaml(options); + try { + yaml.load("12345678901234567890"); + fail("Long input should not be accepted"); + } catch (Exception e) { + assertEquals("The incoming YAML document exceeds the limit: 15 code points.", e.getMessage()); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue55/Blog.java b/src/test/java/org/yaml/snakeyaml/issues/issue55/Blog.java index 228b35b9..9c8eb7a5 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue55/Blog.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue55/Blog.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue55; @@ -19,19 +17,19 @@ import java.util.LinkedList; import java.util.List; class Blog { - private List<Post> posts = new LinkedList<Post>(); - public Blog() { - } + private final List<Post> posts = new LinkedList<Post>(); - public void addPost(Post p) { - // do some business logic here - posts.add(p); - } + public Blog() {} - public List<Post> getPosts() { - // in production code do not return the original set but a wrapped - // unmodifiable set - return posts; - } -}
\ No newline at end of file + public void addPost(Post p) { + // do some business logic here + posts.add(p); + } + + public List<Post> getPosts() { + // in production code do not return the original set but a wrapped + // unmodifiable set + return posts; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue55/FieldListTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue55/FieldListTest.java index c339ef41..9d06a6b8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue55/FieldListTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue55/FieldListTest.java @@ -1,58 +1,55 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue55; import java.util.LinkedList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.BeanAccess; public class FieldListTest extends TestCase { - public void testYaml() { - Yaml beanLoader = new Yaml(); - beanLoader.setBeanAccess(BeanAccess.FIELD); - BlogField rehydrated = beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"), - BlogField.class); - assertEquals(4, rehydrated.getPosts().size()); + public void testYaml() { + Yaml beanLoader = new Yaml(); + beanLoader.setBeanAccess(BeanAccess.FIELD); + BlogField rehydrated = + beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"), BlogField.class); + assertEquals(4, rehydrated.getPosts().size()); + } + + public void testFailureWithoutFieldAccess() { + Yaml beanLoader = new Yaml(); + try { + beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"), BlogField.class); + fail("Private field must not be available"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("No writable property 'posts'")); } + } - public void testFailureWithoutFieldAccess() { - Yaml beanLoader = new Yaml(); - try { - beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"), BlogField.class); - fail("Private field must not be available"); - } catch (Exception e) { - assertTrue(e.getMessage().contains("Unable to find property 'posts'")); - } - } + public static class BlogField { - public static class BlogField { - private List<Integer> posts; + private final List<Integer> posts; - public BlogField() { - posts = new LinkedList<Integer>(); - } + public BlogField() { + posts = new LinkedList<Integer>(); + } - public List<Integer> getPosts() { - return posts; - } + public List<Integer> getPosts() { + return posts; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue55/JavaBeanListTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue55/JavaBeanListTest.java index 1e8966f7..6637b0f8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue55/JavaBeanListTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue55/JavaBeanListTest.java @@ -1,58 +1,55 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue55; import java.util.LinkedList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.BeanAccess; public class JavaBeanListTest extends TestCase { - public void testYaml() { - Yaml beanLoader = new Yaml(); - beanLoader.setBeanAccess(BeanAccess.FIELD); - BlogBean rehydrated = (BlogBean) beanLoader.loadAs( - Util.getLocalResource("issues/issue55_2.txt"), BlogBean.class); - assertEquals(4, rehydrated.getPosts().size()); + public void testYaml() { + Yaml beanLoader = new Yaml(); + beanLoader.setBeanAccess(BeanAccess.FIELD); + BlogBean rehydrated = + beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"), BlogBean.class); + assertEquals(4, rehydrated.getPosts().size()); + } + + public void testFailureWithoutFieldAccess() { + Yaml beanLoader = new Yaml(); + try { + beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"), BlogBean.class); + fail("Private field must not be available"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("No writable property 'posts'")); } + } - public void testFailureWithoutFieldAccess() { - Yaml beanLoader = new Yaml(); - try { - beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"), BlogBean.class); - fail("Private field must not be available"); - } catch (Exception e) { - assertTrue(e.getMessage().contains("Unable to find property 'posts'")); - } - } + public static class BlogBean { - public static class BlogBean { - private List<Integer> posts; + private final List<Integer> posts; - public BlogBean() { - posts = new LinkedList<Integer>(); - } + public BlogBean() { + posts = new LinkedList<Integer>(); + } - public List<Integer> getPosts() { - return posts; - } + public List<Integer> getPosts() { + return posts; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue55/Post.java b/src/test/java/org/yaml/snakeyaml/issues/issue55/Post.java index d9e60cf3..9f3e3055 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue55/Post.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue55/Post.java @@ -1,42 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue55; class Post { - private String title; - private String text; - public static String description; - public transient String cache; - // TODO empty constructor is required to support 2 step construction - protected Post() { - description = "I should not be dumped."; - cache = "Q34598723SDW234"; - } + private String title; + private String text; + public static String description; + public transient String cache; - public Post(String title, String text) { - this.title = title; - this.text = text; - } + // empty constructor is required to support 2 step construction + protected Post() { + description = "I should not be dumped."; + cache = "Q34598723SDW234"; + } - public String getTitle() { - return title; - } + public Post(String title, String text) { + this.title = title; + this.text = text; + } - public String getText() { - return text; - } -}
\ No newline at end of file + public String getTitle() { + return title; + } + + public String getText() { + return text; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue55/YamlFieldAccessCollectionTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue55/YamlFieldAccessCollectionTest.java index 64c24d48..470067ed 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue55/YamlFieldAccessCollectionTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue55/YamlFieldAccessCollectionTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue55; import java.util.Collection; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.BeanAccess; @@ -27,70 +23,69 @@ import org.yaml.snakeyaml.representer.Representer; public class YamlFieldAccessCollectionTest extends TestCase { - public void testYaml() { - Blog original = createTestBlog(); - Yaml yamlDumper = constructYamlDumper(); - String serialized = yamlDumper.dumpAsMap(original); - // System.out.println(serialized); - assertEquals(Util.getLocalResource("issues/issue55_1.txt"), serialized); - Yaml blogLoader = new Yaml(); - blogLoader.setBeanAccess(BeanAccess.FIELD); - Blog rehydrated = blogLoader.loadAs(serialized, Blog.class); - checkTestBlog(rehydrated); - } + public void testYaml() { + Blog original = createTestBlog(); + Yaml yamlDumper = constructYamlDumper(); + String serialized = yamlDumper.dumpAsMap(original); + // System.out.println(serialized); + assertEquals(Util.getLocalResource("issues/issue55_1.txt"), serialized); + Yaml blogLoader = new Yaml(); + blogLoader.setBeanAccess(BeanAccess.FIELD); + Blog rehydrated = blogLoader.loadAs(serialized, Blog.class); + checkTestBlog(rehydrated); + } - @SuppressWarnings("unchecked") - public void testYamlWithoutConfiguration() { - Yaml yaml = new Yaml(); - Map<String, Object> map = (Map<String, Object>) yaml.load(Util - .getLocalResource("issues/issue55_1.txt")); - assertEquals(1, map.size()); - } + @SuppressWarnings("unchecked") + public void testYamlWithoutConfiguration() { + Yaml yaml = new Yaml(); + Map<String, Object> map = yaml.load(Util.getLocalResource("issues/issue55_1.txt")); + assertEquals(1, map.size()); + } - public void testYamlFailure() { - Yaml beanLoader = new Yaml(); - try { - beanLoader.loadAs(Util.getLocalResource("issues/issue55_1.txt"), Blog.class); - fail("BeanAccess.FIELD is required."); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("Unable to find property 'posts'")); - } + public void testYamlFailure() { + Yaml beanLoader = new Yaml(); + try { + beanLoader.loadAs(Util.getLocalResource("issues/issue55_1.txt"), Blog.class); + fail("BeanAccess.FIELD is required."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("No writable property 'posts'")); } + } - public void testYamlDefaultWithFeildAccess() { - Yaml yaml = new Yaml(); - yaml.setBeanAccess(BeanAccess.FIELD); - Blog original = createTestBlog(); - String serialized = yaml.dump(original); - assertEquals(Util.getLocalResource("issues/issue55_1_rootTag.txt"), serialized); - Blog rehydrated = (Blog) yaml.load(serialized); - checkTestBlog(rehydrated); - } + public void testYamlDefaultWithFeildAccess() { + Yaml yaml = new Yaml(); + yaml.setBeanAccess(BeanAccess.FIELD); + Blog original = createTestBlog(); + String serialized = yaml.dump(original); + assertEquals(Util.getLocalResource("issues/issue55_1_rootTag.txt"), serialized); + Blog rehydrated = yaml.load(serialized); + checkTestBlog(rehydrated); + } - protected Yaml constructYamlDumper() { - Representer representer = new Representer(); - representer.getPropertyUtils().setBeanAccess(BeanAccess.FIELD); - Yaml yaml = new Yaml(representer); - return yaml; - } + protected Yaml constructYamlDumper() { + Representer representer = new Representer(); + representer.getPropertyUtils().setBeanAccess(BeanAccess.FIELD); + Yaml yaml = new Yaml(representer); + return yaml; + } - protected Yaml constructYamlParser() { - Yaml yaml = new Yaml(); - yaml.setBeanAccess(BeanAccess.FIELD); - return yaml; - } + protected Yaml constructYamlParser() { + Yaml yaml = new Yaml(); + yaml.setBeanAccess(BeanAccess.FIELD); + return yaml; + } - protected Blog createTestBlog() { - Post post1 = new Post("Test", "Dummy"); - Post post2 = new Post("Highly", "Creative"); - Blog blog = new Blog(); - blog.addPost(post1); - blog.addPost(post2); - return blog; - } + protected Blog createTestBlog() { + Post post1 = new Post("Test", "Dummy"); + Post post2 = new Post("Highly", "Creative"); + Blog blog = new Blog(); + blog.addPost(post1); + blog.addPost(post2); + return blog; + } - protected void checkTestBlog(Blog blog) { - Collection<Post> posts = blog.getPosts(); - assertEquals("Blog contains 2 posts", 2, posts.size()); - } + protected void checkTestBlog(Blog blog) { + Collection<Post> posts = blog.getPosts(); + assertEquals("Blog contains 2 posts", 2, posts.size()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue56/CodeBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue56/CodeBean.java index 00043633..b800b0b1 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue56/CodeBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue56/CodeBean.java @@ -1,56 +1,55 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue56; public class CodeBean { - private String country; - private String type; - private String value; - public static int counter; - - public CodeBean() { - counter++; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - public String toString() { - return "CodeBean: " + getValue(); - } -}
\ No newline at end of file + + private String country; + private String type; + private String value; + public static int counter; + + public CodeBean() { + counter++; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public String toString() { + return "CodeBean: " + getValue(); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue56/PerlTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue56/PerlTest.java index 1f04b843..3ea9f6d1 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue56/PerlTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue56/PerlTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue56; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -32,95 +28,97 @@ import org.yaml.snakeyaml.nodes.Tag; public class PerlTest extends TestCase { - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testMaps() { - Yaml yaml = new Yaml(new CustomConstructor()); - String input = Util.getLocalResource("issues/issue56-1.yaml"); - int counter = 0; - for (Object obj : yaml.loadAll(input)) { - // System.out.println(obj); - Map<String, Object> map = (Map<String, Object>) obj; - Integer oid = (Integer) map.get("oid"); - if (oid == 123058) { - ArrayList a = (ArrayList) map.get("sequences"); - LinkedHashMap b = (LinkedHashMap) a.get(0); - LinkedHashMap c = (LinkedHashMap) b.get("atc"); - LinkedHashMap d = (LinkedHashMap) c.get("name"); - LinkedHashMap e = (LinkedHashMap) d.get("canonical"); - String acidNameDe = e.entrySet().toArray()[1].toString(); - assertEquals("Unicode escaped sequence must be decoded.", - ":de=Acetylsalicylsรยคure", acidNameDe); - } - assertTrue(oid > 10000); - counter++; - } - assertEquals(4, counter); - assertEquals(0, CodeBean.counter); + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testMaps() { + Yaml yaml = new Yaml(new CustomConstructor()); + String input = Util.getLocalResource("issues/issue56-1.yaml"); + int counter = 0; + for (Object obj : yaml.loadAll(input)) { + // System.out.println(obj); + Map<String, Object> map = (Map<String, Object>) obj; + Integer oid = (Integer) map.get("oid"); + if (oid == 123058) { + ArrayList a = (ArrayList) map.get("sequences"); + LinkedHashMap b = (LinkedHashMap) a.get(0); + LinkedHashMap c = (LinkedHashMap) b.get("atc"); + LinkedHashMap d = (LinkedHashMap) c.get("name"); + LinkedHashMap e = (LinkedHashMap) d.get("canonical"); + String acidNameDe = e.entrySet().toArray()[1].toString(); + assertEquals("Unicode escaped sequence must be decoded.", ":de=Acetylsalicylsรยคure", + acidNameDe); + } + assertTrue(oid > 10000); + counter++; } + assertEquals(4, counter); + assertEquals(0, CodeBean.counter); + } - private class CustomConstructor extends SafeConstructor { - public CustomConstructor() { - // define tags which begin with !org.yaml. - String prefix = "!de.oddb.org,2007/ODDB"; - this.yamlMultiConstructors.put(prefix, new ConstructYamlMap()); - } + private class CustomConstructor extends SafeConstructor { + + public CustomConstructor() { + // define tags which begin with !org.yaml. + String prefix = "!de.oddb.org,2007/ODDB"; + this.yamlMultiConstructors.put(prefix, new ConstructYamlMap()); } + } - @SuppressWarnings("unchecked") - public void testJavaBeanWithTypeDescription() { - Constructor c = new CustomBeanConstructor(); - TypeDescription descr = new TypeDescription(CodeBean.class, new Tag( - "!de.oddb.org,2007/ODDB::Util::Code")); - c.addTypeDescription(descr); - Yaml yaml = new Yaml(c); - String input = Util.getLocalResource("issues/issue56-1.yaml"); - int counter = 0; - for (Object obj : yaml.loadAll(input)) { - // System.out.println(obj); - Map<String, Object> map = (Map<String, Object>) obj; - Integer oid = (Integer) map.get("oid"); - assertTrue(oid > 10000); - counter++; - } - assertEquals(4, counter); - assertEquals(55, CodeBean.counter); + @SuppressWarnings("unchecked") + public void testJavaBeanWithTypeDescription() { + Constructor c = new CustomBeanConstructor(); + TypeDescription descr = + new TypeDescription(CodeBean.class, new Tag("!de.oddb.org,2007/ODDB::Util::Code")); + c.addTypeDescription(descr); + Yaml yaml = new Yaml(c); + String input = Util.getLocalResource("issues/issue56-1.yaml"); + int counter = 0; + for (Object obj : yaml.loadAll(input)) { + // System.out.println(obj); + Map<String, Object> map = (Map<String, Object>) obj; + Integer oid = (Integer) map.get("oid"); + assertTrue(oid > 10000); + counter++; } + assertEquals(4, counter); + assertEquals(55, CodeBean.counter); + } - @SuppressWarnings("unchecked") - public void testJavaBean() { - Constructor c = new CustomBeanConstructor(); - Yaml yaml = new Yaml(c); - String input = Util.getLocalResource("issues/issue56-1.yaml"); - int counter = 0; - for (Object obj : yaml.loadAll(input)) { - // System.out.println(obj); - Map<String, Object> map = (Map<String, Object>) obj; - Integer oid = (Integer) map.get("oid"); - assertTrue(oid > 10000); - counter++; - } - assertEquals(4, counter); - assertEquals(55, CodeBean.counter); + @SuppressWarnings("unchecked") + public void testJavaBean() { + Constructor c = new CustomBeanConstructor(); + Yaml yaml = new Yaml(c); + String input = Util.getLocalResource("issues/issue56-1.yaml"); + int counter = 0; + for (Object obj : yaml.loadAll(input)) { + // System.out.println(obj); + Map<String, Object> map = (Map<String, Object>) obj; + Integer oid = (Integer) map.get("oid"); + assertTrue(oid > 10000); + counter++; } + assertEquals(4, counter); + assertEquals(55, CodeBean.counter); + } - private class CustomBeanConstructor extends Constructor { - public CustomBeanConstructor() { - // define tags which begin with !org.yaml. - String prefix = "!de.oddb.org,2007/ODDB"; - this.yamlMultiConstructors.put(prefix, new ConstructYamlMap()); - } + private class CustomBeanConstructor extends Constructor { - protected Construct getConstructor(Node node) { - if (node.getTag().equals(new Tag("!de.oddb.org,2007/ODDB::Util::Code"))) { - node.setUseClassConstructor(true); - node.setType(CodeBean.class); - } - return super.getConstructor(node); - } + public CustomBeanConstructor() { + // define tags which begin with !org.yaml. + String prefix = "!de.oddb.org,2007/ODDB"; + this.yamlMultiConstructors.put(prefix, new ConstructYamlMap()); } - @Override - protected void setUp() { - CodeBean.counter = 0; + protected Construct getConstructor(Node node) { + if (node.getTag().equals(new Tag("!de.oddb.org,2007/ODDB::Util::Code"))) { + node.setUseClassConstructor(true); + node.setType(CodeBean.class); + } + return super.getConstructor(node); } + } + + @Override + protected void setUp() { + CodeBean.counter = 0; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue58/NullValueDumperTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue58/NullValueDumperTest.java index 9321c020..5d2b561d 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue58/NullValueDumperTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue58/NullValueDumperTest.java @@ -1,60 +1,57 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue58; import java.util.ArrayList; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class NullValueDumperTest extends TestCase { - public static class Foo { - private ArrayList<Object> bar = new ArrayList<Object>(); + public static class Foo { - public ArrayList<Object> getBar() { - return bar; - } - - public void setBar(ArrayList<Object> bar) { - this.bar = bar; - } - } + private ArrayList<Object> bar = new ArrayList<Object>(); - public void testListElement() { - final Foo foo = new Foo(); - foo.bar.add(1); - foo.bar.add("A"); - foo.bar.add(3.14); - Yaml yaml = new Yaml(); - assertEquals("bar:\n- 1\n- A\n- 3.14\n", yaml.dumpAsMap(foo)); + public ArrayList<Object> getBar() { + return bar; } - public void testNullListElement() { - final Foo foo = new Foo(); - - foo.bar.add(1); - foo.bar.add("A"); - foo.bar.add(null); - foo.bar.add(3.14); - Yaml yaml = new Yaml(); - assertEquals("bar:\n- 1\n- A\n- null\n- 3.14\n", yaml.dumpAsMap(foo)); - assertEquals( - "!!org.yaml.snakeyaml.issues.issue58.NullValueDumperTest$Foo\nbar: [1, A, null, 3.14]\n", - new Yaml().dump(foo)); + public void setBar(ArrayList<Object> bar) { + this.bar = bar; } + } + + public void testListElement() { + final Foo foo = new Foo(); + foo.bar.add(1); + foo.bar.add("A"); + foo.bar.add(3.14); + Yaml yaml = new Yaml(); + assertEquals("bar:\n- 1\n- A\n- 3.14\n", yaml.dumpAsMap(foo)); + } + + public void testNullListElement() { + final Foo foo = new Foo(); + + foo.bar.add(1); + foo.bar.add("A"); + foo.bar.add(null); + foo.bar.add(3.14); + Yaml yaml = new Yaml(); + assertEquals("bar:\n- 1\n- A\n- null\n- 3.14\n", yaml.dumpAsMap(foo)); + assertEquals( + "!!org.yaml.snakeyaml.issues.issue58.NullValueDumperTest$Foo\nbar: [1, A, null, 3.14]\n", + new Yaml().dump(foo)); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue60/CustomOrderTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue60/CustomOrderTest.java index 0942b53d..6e93d057 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue60/CustomOrderTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue60/CustomOrderTest.java @@ -1,29 +1,24 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue60; -import java.beans.IntrospectionException; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.BeanAccess; @@ -31,54 +26,54 @@ import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.introspector.PropertyUtils; import org.yaml.snakeyaml.representer.Representer; -//issue 59 +// issue 59 public class CustomOrderTest extends TestCase { - public void testReversedOrder() { - Representer repr = new Representer(); - repr.setPropertyUtils(new ReversedPropertyUtils()); - Yaml yaml = new Yaml(repr); - String output = yaml.dump(getBean()); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue59-1.yaml"), output); - } + public void testReversedOrder() { + Representer repr = new Representer(); + repr.setPropertyUtils(new ReversedPropertyUtils()); + Yaml yaml = new Yaml(repr); + String output = yaml.dump(getBean()); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue59-1.yaml"), output); + } - private class ReversedPropertyUtils extends PropertyUtils { - @Override - protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) - throws IntrospectionException { - Set<Property> result = new TreeSet<Property>(Collections.reverseOrder()); - result.addAll(super.createPropertySet(type, bAccess)); - return result; - } - } + private class ReversedPropertyUtils extends PropertyUtils { - public void testUnsorted() { - Representer repr = new Representer(); - repr.setPropertyUtils(new UnsortedPropertyUtils()); - Yaml yaml = new Yaml(repr); - String output = yaml.dump(getBean()); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue59-2.yaml"), output); + @Override + protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) { + Set<Property> result = new TreeSet<Property>(Collections.reverseOrder()); + result.addAll(super.createPropertySet(type, bAccess)); + return result; } + } - private class UnsortedPropertyUtils extends PropertyUtils { - @Override - protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) - throws IntrospectionException { - Set<Property> result = new LinkedHashSet<Property>(getPropertiesMap(type, - BeanAccess.FIELD).values()); - result.remove(result.iterator().next());// drop 'listInt' property - return result; - } - } + public void testUnsorted() { + Representer repr = new Representer(); + repr.setPropertyUtils(new UnsortedPropertyUtils()); + Yaml yaml = new Yaml(repr); + String output = yaml.dump(getBean()); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue59-2.yaml"), output); + } + + private class UnsortedPropertyUtils extends PropertyUtils { - private SkipBean getBean() { - SkipBean bean = new SkipBean(); - bean.setText("foo"); - bean.setListDate(null); - bean.setListInt(Arrays.asList(new Integer[] { null, 1, 2, 3 })); - bean.setListStr(Arrays.asList(new String[] { "bar", null, "foo", null })); - return bean; + @Override + protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) { + Set<Property> result = + new LinkedHashSet<Property>(getPropertiesMap(type, BeanAccess.FIELD).values()); + result.remove(result.iterator().next());// drop 'listInt' property + return result; } + } + + private SkipBean getBean() { + SkipBean bean = new SkipBean(); + bean.setText("foo"); + bean.setListDate(null); + bean.setListInt(Arrays.asList(null, 1, 2, 3)); + bean.setListStr(Arrays.asList("bar", null, "foo", null)); + return bean; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBean.java b/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBean.java index 388feedb..6337afce 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBean.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBean.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue60; @@ -24,67 +22,67 @@ import java.util.Map; public class SkipBean { - private List<Integer> listInt; - private List<String> listStr; - private List<Date> listDate; - private List<File> empty = new ArrayList<File>(0); - private Map<String, Integer> map = new HashMap<String, Integer>(0); - private String text; - private Integer number; - - public List<Integer> getListInt() { - return listInt; - } - - public void setListInt(List<Integer> listInt) { - this.listInt = listInt; - } - - public List<String> getListStr() { - return listStr; - } - - public void setListStr(List<String> listStr) { - this.listStr = listStr; - } - - public List<Date> getListDate() { - return listDate; - } - - public void setListDate(List<Date> listDate) { - this.listDate = listDate; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public Integer getNumber() { - return number; - } - - public void setNumber(Integer number) { - this.number = number; - } - - public List<File> getEmpty() { - return empty; - } - - public void setEmpty(List<File> empty) { - this.empty = empty; - } - - public Map<String, Integer> getMap() { - return map; - } - - public void setMap(Map<String, Integer> map) { - this.map = map; - } + private List<Integer> listInt; + private List<String> listStr; + private List<Date> listDate; + private List<File> empty = new ArrayList<File>(0); + private Map<String, Integer> map = new HashMap<String, Integer>(0); + private String text; + private Integer number; + + public List<Integer> getListInt() { + return listInt; + } + + public void setListInt(List<Integer> listInt) { + this.listInt = listInt; + } + + public List<String> getListStr() { + return listStr; + } + + public void setListStr(List<String> listStr) { + this.listStr = listStr; + } + + public List<Date> getListDate() { + return listDate; + } + + public void setListDate(List<Date> listDate) { + this.listDate = listDate; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Integer getNumber() { + return number; + } + + public void setNumber(Integer number) { + this.number = number; + } + + public List<File> getEmpty() { + return empty; + } + + public void setEmpty(List<File> empty) { + this.empty = empty; + } + + public Map<String, Integer> getMap() { + return map; + } + + public void setMap(Map<String, Integer> map) { + this.map = map; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBeanTest.java index 8cb6e0ef..208dfc91 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBeanTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue60; import java.util.Arrays; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.Property; @@ -32,67 +28,68 @@ import org.yaml.snakeyaml.representer.Representer; public class SkipBeanTest extends TestCase { - public void testSkipNull() { - Yaml yaml = new Yaml(new SkipNullRepresenter()); - String output = yaml.dump(getBean()); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue60-1.yaml"), output); - } + public void testSkipNull() { + Yaml yaml = new Yaml(new SkipNullRepresenter()); + String output = yaml.dump(getBean()); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue60-1.yaml"), output); + } - private class SkipNullRepresenter extends Representer { - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, - Object propertyValue, Tag customTag) { - if (propertyValue == null) { - return null; - } else { - return super - .representJavaBeanProperty(javaBean, property, propertyValue, customTag); - } - } - } + private class SkipNullRepresenter extends Representer { - public void testSkipEmptyCollections() { - Yaml yaml = new Yaml(new SkipEmptyRepresenter()); - String output = yaml.dump(getBean()); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue60-2.yaml"), output); + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, + Object propertyValue, Tag customTag) { + if (propertyValue == null) { + return null; + } else { + return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + } } + } - private class SkipEmptyRepresenter extends Representer { - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, - Object propertyValue, Tag customTag) { - NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, propertyValue, - customTag); - Node valueNode = tuple.getValueNode(); - if (Tag.NULL.equals(valueNode.getTag())) { - return null;// skip 'null' values - } - if (valueNode instanceof CollectionNode) { - if (Tag.SEQ.equals(valueNode.getTag())) { - SequenceNode seq = (SequenceNode) valueNode; - if (seq.getValue().isEmpty()) { - return null;// skip empty lists - } - } - if (Tag.MAP.equals(valueNode.getTag())) { - MappingNode seq = (MappingNode) valueNode; - if (seq.getValue().isEmpty()) { - return null;// skip empty maps - } - } - } - return tuple; + public void testSkipEmptyCollections() { + Yaml yaml = new Yaml(new SkipEmptyRepresenter()); + String output = yaml.dump(getBean()); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue60-2.yaml"), output); + } + + private class SkipEmptyRepresenter extends Representer { + + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, + Object propertyValue, Tag customTag) { + NodeTuple tuple = + super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + Node valueNode = tuple.getValueNode(); + if (Tag.NULL.equals(valueNode.getTag())) { + return null;// skip 'null' values + } + if (valueNode instanceof CollectionNode) { + if (Tag.SEQ.equals(valueNode.getTag())) { + SequenceNode seq = (SequenceNode) valueNode; + if (seq.getValue().isEmpty()) { + return null;// skip empty lists + } } + if (Tag.MAP.equals(valueNode.getTag())) { + MappingNode seq = (MappingNode) valueNode; + if (seq.getValue().isEmpty()) { + return null;// skip empty maps + } + } + } + return tuple; } + } - private SkipBean getBean() { - SkipBean bean = new SkipBean(); - bean.setText("foo"); - bean.setListDate(null); - bean.setListInt(Arrays.asList(new Integer[] { null, 1, 2, 3 })); - bean.setListStr(Arrays.asList(new String[] { "bar", null, "foo", null })); - return bean; - } + private SkipBean getBean() { + SkipBean bean = new SkipBean(); + bean.setText("foo"); + bean.setListDate(null); + bean.setListInt(Arrays.asList(null, 1, 2, 3)); + bean.setListStr(Arrays.asList("bar", null, "foo", null)); + return bean; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericListBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericListBeanTest.java index f872aae6..97ae7624 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericListBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericListBeanTest.java @@ -1,117 +1,116 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue61; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class GenericListBeanTest extends TestCase { - @SuppressWarnings("unchecked") - public void testGenericList() { - Yaml yaml = new Yaml(); - ListProvider<String> listProvider = new ListProvider<String>(); - listProvider.getList().add("foo"); - listProvider.getList().add("bar"); - String s = yaml.dumpAsMap(listProvider); - // System.out.println(s); - assertEquals("list:\n- foo\n- bar\n", s); - // parse - Yaml loader = new Yaml(); - ListProvider<String> listProvider2 = loader.loadAs(s, ListProvider.class); - assertEquals("foo", listProvider2.getList().get(0)); - assertEquals("bar", listProvider2.getList().get(1)); - assertEquals(listProvider, listProvider2); + + @SuppressWarnings("unchecked") + public void testGenericList() { + Yaml yaml = new Yaml(); + ListProvider<String> listProvider = new ListProvider<String>(); + listProvider.getList().add("foo"); + listProvider.getList().add("bar"); + String s = yaml.dumpAsMap(listProvider); + // System.out.println(s); + assertEquals("list:\n- foo\n- bar\n", s); + // parse + Yaml loader = new Yaml(); + ListProvider<String> listProvider2 = loader.loadAs(s, ListProvider.class); + assertEquals("foo", listProvider2.getList().get(0)); + assertEquals("bar", listProvider2.getList().get(1)); + assertEquals(listProvider, listProvider2); + } + + @SuppressWarnings("rawtypes") + public void testGenericBean() { + Yaml yaml = new Yaml(); + ListProvider<Bean> listProvider = new ListProvider<Bean>(); + Bean foo = new Bean(); + foo.setName("foo"); + listProvider.getList().add(foo); + Bean bar = new Bean(); + bar.setName("bar"); + bar.setNumber(3); + listProvider.getList().add(bar); + String s = yaml.dumpAsMap(listProvider); + // System.out.println(s); + String etalon = Util.getLocalResource("issues/issue61-1.yaml"); + assertEquals(etalon, s); + // parse + Yaml loader = new Yaml(); + ListProvider listProvider2 = loader.loadAs(s, ListProvider.class); + Bean foo2 = (Bean) listProvider2.getList().get(0); + assertEquals("foo", foo2.getName()); + assertEquals(0, foo2.getNumber()); + Bean bar2 = (Bean) listProvider2.getList().get(1); + assertEquals("bar", bar2.getName()); + assertEquals(3, bar2.getNumber()); + } + + public static class ListProvider<T> { + + private List<T> list = new ArrayList<T>(); + + public List<T> getList() { + return list; + } + + public void setList(List<T> list) { + this.list = list; } @SuppressWarnings("rawtypes") - public void testGenericBean() { - Yaml yaml = new Yaml(); - ListProvider<Bean> listProvider = new ListProvider<Bean>(); - Bean foo = new Bean(); - foo.setName("foo"); - listProvider.getList().add(foo); - Bean bar = new Bean(); - bar.setName("bar"); - bar.setNumber(3); - listProvider.getList().add(bar); - String s = yaml.dumpAsMap(listProvider); - // System.out.println(s); - String etalon = Util.getLocalResource("issues/issue61-1.yaml"); - assertEquals(etalon, s); - // parse - Yaml loader = new Yaml(); - ListProvider listProvider2 = loader.loadAs(s, ListProvider.class); - Bean foo2 = (Bean) listProvider2.getList().get(0); - assertEquals("foo", foo2.getName()); - assertEquals(0, foo2.getNumber()); - Bean bar2 = (Bean) listProvider2.getList().get(1); - assertEquals("bar", bar2.getName()); - assertEquals(3, bar2.getNumber()); + @Override + public boolean equals(Object obj) { + if (obj instanceof ListProvider) { + return list.equals(((ListProvider) obj).getList()); + } else { + return false; + } } - public static class ListProvider<T> { - private List<T> list = new ArrayList<T>(); - - public List<T> getList() { - return list; - } - - public void setList(List<T> list) { - this.list = list; - } - - @SuppressWarnings("rawtypes") - @Override - public boolean equals(Object obj) { - if (obj instanceof ListProvider) { - return list.equals(((ListProvider) obj).getList()); - } else { - return false; - } - } - - @Override - public int hashCode() { - return list.hashCode(); - } + @Override + public int hashCode() { + return list.hashCode(); } + } + + public static class Bean { - public static class Bean { - private String name; - private int number; + private String name; + private int number; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public int getNumber() { - return number; - } + public int getNumber() { + return number; + } - public void setNumber(int number) { - this.number = number; - } + public void setNumber(int number) { + this.number = number; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericMapBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericMapBeanTest.java index fd1eff27..4fdca222 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericMapBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue61/GenericMapBeanTest.java @@ -1,118 +1,116 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue61; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class GenericMapBeanTest extends TestCase { - @SuppressWarnings("unchecked") - public void testGenericMap() { - Yaml yaml = new Yaml(); - MapProvider<String, Integer> listProvider = new MapProvider<String, Integer>(); - listProvider.getMap().put("foo", 17); - listProvider.getMap().put("bar", 19); - String s = yaml.dumpAsMap(listProvider); - // System.out.println(s); - assertEquals("map:\n foo: 17\n bar: 19\n", s); - // parse - Yaml loader = new Yaml(); - MapProvider<String, Integer> listProvider2 = loader.loadAs(s, MapProvider.class); - assertEquals(new Integer(17), listProvider2.getMap().get("foo")); - assertEquals(new Integer(19), listProvider2.getMap().get("bar")); - assertEquals(listProvider, listProvider2); + + @SuppressWarnings("unchecked") + public void testGenericMap() { + Yaml yaml = new Yaml(); + MapProvider<String, Integer> listProvider = new MapProvider<String, Integer>(); + listProvider.getMap().put("foo", 17); + listProvider.getMap().put("bar", 19); + String s = yaml.dumpAsMap(listProvider); + // System.out.println(s); + assertEquals("map:\n foo: 17\n bar: 19\n", s); + // parse + Yaml loader = new Yaml(); + MapProvider<String, Integer> listProvider2 = loader.loadAs(s, MapProvider.class); + assertEquals(Integer.valueOf(17), listProvider2.getMap().get("foo")); + assertEquals(Integer.valueOf(19), listProvider2.getMap().get("bar")); + assertEquals(listProvider, listProvider2); + } + + @SuppressWarnings("rawtypes") + public void testGenericBean() { + Yaml yaml = new Yaml(); + MapProvider<String, Bean> listProvider = new MapProvider<String, Bean>(); + Bean foo = new Bean(); + foo.setName("foo"); + listProvider.getMap().put("foo", foo); + Bean bar = new Bean(); + bar.setName("bar"); + bar.setNumber(3); + listProvider.getMap().put("bar", bar); + String s = yaml.dumpAsMap(listProvider); + // System.out.println(s); + String etalon = Util.getLocalResource("issues/issue61-2.yaml"); + assertEquals(etalon, s); + // parse + Yaml loader = new Yaml(); + MapProvider listProvider2 = loader.loadAs(s, MapProvider.class); + Bean foo2 = (Bean) listProvider2.getMap().get("foo"); + assertEquals("foo", foo2.getName()); + assertEquals(0, foo2.getNumber()); + Bean bar2 = (Bean) listProvider2.getMap().get("bar"); + assertEquals("bar", bar2.getName()); + assertEquals(3, bar2.getNumber()); + } + + public static class MapProvider<K, V> { + + private Map<K, V> map = new LinkedHashMap<K, V>(); + + public Map<K, V> getMap() { + return map; + } + + public void setMap(Map<K, V> map) { + this.map = map; } @SuppressWarnings("rawtypes") - public void testGenericBean() { - Yaml yaml = new Yaml(); - MapProvider<String, Bean> listProvider = new MapProvider<String, Bean>(); - Bean foo = new Bean(); - foo.setName("foo"); - listProvider.getMap().put("foo", foo); - Bean bar = new Bean(); - bar.setName("bar"); - bar.setNumber(3); - listProvider.getMap().put("bar", bar); - String s = yaml.dumpAsMap(listProvider); - // System.out.println(s); - String etalon = Util.getLocalResource("issues/issue61-2.yaml"); - assertEquals(etalon, s); - // parse - Yaml loader = new Yaml(); - MapProvider listProvider2 = loader.loadAs(s, MapProvider.class); - Bean foo2 = (Bean) listProvider2.getMap().get("foo"); - assertEquals("foo", foo2.getName()); - assertEquals(0, foo2.getNumber()); - Bean bar2 = (Bean) listProvider2.getMap().get("bar"); - assertEquals("bar", bar2.getName()); - assertEquals(3, bar2.getNumber()); + @Override + public boolean equals(Object obj) { + if (obj instanceof MapProvider) { + return map.equals(((MapProvider) obj).getMap()); + } else { + return false; + } } - public static class MapProvider<K, V> { - private Map<K, V> map = new LinkedHashMap<K, V>(); - - public Map<K, V> getMap() { - return map; - } - - public void setMap(Map<K, V> map) { - this.map = map; - } - - @SuppressWarnings("rawtypes") - @Override - public boolean equals(Object obj) { - if (obj instanceof MapProvider) { - return map.equals(((MapProvider) obj).getMap()); - } else { - return false; - } - } - - @Override - public int hashCode() { - return map.hashCode(); - } + @Override + public int hashCode() { + return map.hashCode(); } + } + + public static class Bean { - public static class Bean { - private String name; - private int number; + private String name; + private int number; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public int getNumber() { - return number; - } + public int getNumber() { + return number; + } - public void setNumber(int number) { - this.number = number; - } + public void setNumber(int number) { + this.number = number; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue64/MethodDesc.java b/src/test/java/org/yaml/snakeyaml/issues/issue64/MethodDesc.java index 74ea7f51..26e710cb 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue64/MethodDesc.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue64/MethodDesc.java @@ -1,47 +1,45 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue64; import java.util.List; public class MethodDesc { - private String name; - private List<Class<?>> argTypes; - public MethodDesc() { - } + private String name; + private List<Class<?>> argTypes; - public MethodDesc(String name, List<Class<?>> argTypes) { - this.name = name; - this.argTypes = argTypes; - } + public MethodDesc() {} - public String getName() { - return name; - } + public MethodDesc(String name, List<Class<?>> argTypes) { + this.name = name; + this.argTypes = argTypes; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public List<Class<?>> getArgTypes() { - return argTypes; - } + public void setName(String name) { + this.name = name; + } - public void setArgTypes(List<Class<?>> argTypes) { - this.argTypes = argTypes; - } + public List<Class<?>> getArgTypes() { + return argTypes; + } + + public void setArgTypes(List<Class<?>> argTypes) { + this.argTypes = argTypes; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue64/ParameterizedTypeTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue64/ParameterizedTypeTest.java index 50c7bc80..828e8c6d 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue64/ParameterizedTypeTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue64/ParameterizedTypeTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue64; import java.util.LinkedList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; @@ -31,56 +27,59 @@ import org.yaml.snakeyaml.representer.Representer; public class ParameterizedTypeTest extends TestCase { - public void testRepresenter() { - Yaml yaml = new Yaml(new ClassConstructor(), new ClassRepresenter()); + public void testRepresenter() { + Yaml yaml = new Yaml(new ClassConstructor(), new ClassRepresenter()); + + String methodName = "testMethod"; + List<Class<?>> argTypes = new LinkedList<Class<?>>(); + argTypes.add(String.class); + argTypes.add(Integer.class); + argTypes.add(Boolean.class); + MethodDesc methodDesc = new MethodDesc(methodName, argTypes); - String methodName = "testMethod"; - List<Class<?>> argTypes = new LinkedList<Class<?>>(); - argTypes.add(String.class); - argTypes.add(Integer.class); - argTypes.add(Boolean.class); - MethodDesc methodDesc = new MethodDesc(methodName, argTypes); + String out = yaml.dump(methodDesc); + // System.out.println(out); + assertEquals( + "!!org.yaml.snakeyaml.issues.issue64.MethodDesc\nargTypes: [!clazz 'String', !clazz 'Integer', !clazz 'Boolean']\nname: testMethod\n", + out); + MethodDesc parsed = yaml.load(out); + assertEquals(methodName, parsed.getName()); + List<Class<?>> argTypes2 = parsed.getArgTypes(); + assertEquals(3, argTypes2.size()); + assertEquals(argTypes, argTypes2); + } - String out = yaml.dump(methodDesc); - // System.out.println(out); - assertEquals( - "!!org.yaml.snakeyaml.issues.issue64.MethodDesc\nargTypes: [!clazz 'String', !clazz 'Integer', !clazz 'Boolean']\nname: testMethod\n", - out); - MethodDesc parsed = (MethodDesc) yaml.load(out); - assertEquals(methodName, parsed.getName()); - List<Class<?>> argTypes2 = parsed.getArgTypes(); - assertEquals(3, argTypes2.size()); - assertEquals(argTypes, argTypes2); + static class ClassRepresenter extends Representer { + + public ClassRepresenter() { + this.representers.put(Class.class, new RepresentClass()); } - static class ClassRepresenter extends Representer { - public ClassRepresenter() { - this.representers.put(Class.class, new RepresentClass()); - } + private class RepresentClass implements Represent { - private class RepresentClass implements Represent { - public Node representData(Object data) { - Class<?> clazz = (Class<?>) data; - return representScalar(new Tag("!clazz"), clazz.getSimpleName()); - } - } + public Node representData(Object data) { + Class<?> clazz = (Class<?>) data; + return representScalar(new Tag("!clazz"), clazz.getSimpleName()); + } } + } - static class ClassConstructor extends Constructor { - public ClassConstructor() { - this.yamlConstructors.put(new Tag("!clazz"), new ConstructClass()); - } + static class ClassConstructor extends Constructor { + + public ClassConstructor() { + this.yamlConstructors.put(new Tag("!clazz"), new ConstructClass()); + } - private class ConstructClass extends AbstractConstruct { + private class ConstructClass extends AbstractConstruct { - public Object construct(Node node) { - String clazz = (String) constructScalar((ScalarNode) node); - try { - return Class.forName("java.lang." + clazz); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } + public Object construct(Node node) { + String clazz = constructScalar((ScalarNode) node); + try { + return Class.forName("java.lang." + clazz); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); } + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue67/NonAsciiCharsInClassNameTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue67/NonAsciiCharsInClassNameTest.java index 12191736..b9321ebf 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue67/NonAsciiCharsInClassNameTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue67/NonAsciiCharsInClassNameTest.java @@ -1,110 +1,104 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue67; import junit.framework.TestCase; - -import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; -import org.yaml.snakeyaml.scanner.ScannerException; public class NonAsciiCharsInClassNameTest extends TestCase { - private String PREFIX = "!!org.yaml.snakeyaml.issues.issue67.NonAsciiCharsInClassNameTest$"; - - public void testDump() { - Acadรฉmico obj = new Acadรฉmico(); - obj.setId(1); - obj.setName("Foo bar baz"); - Yaml yaml = new Yaml(); - String result = yaml.dump(obj); - assertEquals(PREFIX + "Acad%C3%A9mico {\n id: 1, name: Foo bar baz}\n", result); - } - public void testLoad() { - Yaml yaml = new Yaml(); - Acadรฉmico obj = (Acadรฉmico) yaml.load(PREFIX + "Acad%C3%A9mico {id: 3, name: Foo bar}"); - assertEquals(3, obj.getId()); - assertEquals("Foo bar", obj.getName()); - } - - public void testLoadInvalidPattern() { - try { - Yaml yaml = new Yaml(); - yaml.load(PREFIX + "Acad%WZ%A9mico {id: 3, name: Foo bar}"); - fail("Illegal hex characters in escape (%) pattern must not be accepted."); - } catch (Exception e) { - assertEquals( - "while scanning a tag\n" - + " in 'string', line 1, column 1:\n" - + " !!org.yaml.snakeyaml.issues.issu ... \n" - + " ^\n" - + "expected URI escape sequence of 2 hexadecimal numbers, but found W(87) and Z(90)\n" - + " in 'string', line 1, column 71:\n" - + " ... nAsciiCharsInClassNameTest$Acad%WZ%A9mico {id: 3, name: Foo bar}\n" - + " ^\n", e.getMessage()); - } - } + private final String PREFIX = "!!org.yaml.snakeyaml.issues.issue67.NonAsciiCharsInClassNameTest$"; - public static class Acadรฉmico { - public int getId() { - return id; - } + public void testDump() { + Acadรฉmico obj = new Acadรฉmico(); + obj.setId(1); + obj.setName("Foo bar baz"); + Yaml yaml = new Yaml(); + String result = yaml.dump(obj); + assertEquals(PREFIX + "Acad%C3%A9mico {\n id: 1, name: Foo bar baz}\n", result); + } - public void setId(int id) { - this.id = id; - } + public void testLoad() { + Yaml yaml = new Yaml(); + Acadรฉmico obj = yaml.load(PREFIX + "Acad%C3%A9mico {id: 3, name: Foo bar}"); + assertEquals(3, obj.getId()); + assertEquals("Foo bar", obj.getName()); + } - public String getName() { - return name; - } + public void testLoadInvalidPattern() { + try { + Yaml yaml = new Yaml(); + yaml.load(PREFIX + "Acad%WZ%A9mico {id: 3, name: Foo bar}"); + fail("Illegal hex characters in escape (%) pattern must not be accepted."); + } catch (Exception e) { + assertEquals("while scanning a tag\n" + " in 'string', line 1, column 1:\n" + + " !!org.yaml.snakeyaml.issues.issu ... \n" + " ^\n" + + "expected URI escape sequence of 2 hexadecimal numbers, but found W(87) and Z(90)\n" + + " in 'string', line 1, column 71:\n" + + " ... nAsciiCharsInClassNameTest$Acad%WZ%A9mico {id: 3, name: Foo bar}\n" + + " ^\n", e.getMessage()); + } + } - public void setName(String name) { - this.name = name; - } + public static class Acadรฉmico { - private int id; - private String name; + public int getId() { + return id; } - public void testDumpCustomTag() { - Acadรฉmico obj = new Acadรฉmico(); - obj.setId(123); - obj.setName("Foo bar 123"); - Representer repr = new Representer(); - repr.addClassTag(Acadรฉmico.class, new Tag("!foo")); - Yaml yaml = new Yaml(repr); - String result = yaml.dump(obj); - assertEquals("!foo {id: 123, name: Foo bar 123}\n", result); + public void setId(int id) { + this.id = id; } - public void testDumpEscapedTag() { - Acadรฉmico obj = new Acadรฉmico(); - obj.setId(123); - obj.setName("Foo bar 123"); - Representer repr = new Representer(); - repr.addClassTag(Acadรฉmico.class, new Tag("!Acadรฉmico")); - Yaml yaml = new Yaml(repr); - String result = yaml.dump(obj); - assertEquals("!Acad%C3%A9mico {id: 123, name: Foo bar 123}\n", result); + public String getName() { + return name; } - public void testTag() { - Tag tag = new Tag("!java/javabean:foo.Bar"); - assertEquals("!java/javabean:foo.Bar", tag.getValue()); + public void setName(String name) { + this.name = name; } + + private int id; + private String name; + } + + public void testDumpCustomTag() { + Acadรฉmico obj = new Acadรฉmico(); + obj.setId(123); + obj.setName("Foo bar 123"); + Representer repr = new Representer(); + repr.addClassTag(Acadรฉmico.class, new Tag("!foo")); + Yaml yaml = new Yaml(repr); + String result = yaml.dump(obj); + assertEquals("!foo {id: 123, name: Foo bar 123}\n", result); + } + + public void testDumpEscapedTag() { + Acadรฉmico obj = new Acadรฉmico(); + obj.setId(123); + obj.setName("Foo bar 123"); + Representer repr = new Representer(); + repr.addClassTag(Acadรฉmico.class, new Tag("!Acadรฉmico")); + Yaml yaml = new Yaml(repr); + String result = yaml.dump(obj); + assertEquals("!Acad%C3%A9mico {id: 123, name: Foo bar 123}\n", result); + } + + public void testTag() { + Tag tag = new Tag("!java/javabean:foo.Bar"); + assertEquals("!java/javabean:foo.Bar", tag.getValue()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue68/NonAsciiCharacterTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue68/NonAsciiCharacterTest.java index 9915abc4..79e6ca45 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue68/NonAsciiCharacterTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue68/NonAsciiCharacterTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue68; @@ -24,54 +22,52 @@ import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.YamlDocument; public class NonAsciiCharacterTest extends TestCase { - @SuppressWarnings("unchecked") - public void testLoad() { - Yaml yaml = new Yaml(); - Map<String, Map<String, String>> obj = (Map<String, Map<String, String>>) yaml - .load("test.string: {en: ะ}"); - assertEquals(1, obj.size()); - assertEquals("Map: " + obj.toString(), "ะ", obj.get("test.string").get("en")); - } + @SuppressWarnings("unchecked") + public void testLoad() { + Yaml yaml = new Yaml(); + Map<String, Map<String, String>> obj = yaml.load("test.string: {en: ะ}"); + assertEquals(1, obj.size()); + assertEquals("Map: " + obj, "ะ", obj.get("test.string").get("en")); + } - public void testLoadFromFileWithWrongEncoding() { - try { - Yaml yaml = new Yaml(); - InputStream input = new FileInputStream("src/test/resources/issues/issue68.txt"); - CharsetDecoder decoder = Charset.forName("Cp1252").newDecoder(); - decoder.onUnmappableCharacter(CodingErrorAction.REPORT); - Object text = yaml.load(new InputStreamReader(input, decoder)); - input.close(); - fail("Invalid UTF-8 must not be accepted: " + text.toString()); - } catch (Exception e) { - assertTrue(e.getMessage().endsWith("Exception: Input length = 1")); - } + public void testLoadFromFileWithWrongEncoding() { + try { + Yaml yaml = new Yaml(); + InputStream input = new FileInputStream("src/test/resources/issues/issue68.txt"); + CharsetDecoder decoder = Charset.forName("Cp1252").newDecoder(); + decoder.onUnmappableCharacter(CodingErrorAction.REPORT); + Object text = yaml.load(new InputStreamReader(input, decoder)); + input.close(); + fail("Invalid UTF-8 must not be accepted: " + text.toString()); + } catch (Exception e) { + assertTrue(e.getMessage().endsWith("Exception: Input length = 1")); } + } - public void testLoadFromFile() throws UnsupportedEncodingException, FileNotFoundException { - Yaml yaml = new Yaml(); - InputStream input = new FileInputStream("src/test/resources/issues/issue68.txt"); - String text = (String) yaml.load(new InputStreamReader(input, "UTF-8")); - assertEquals("ะ ะถะธัั ัะพัะพะฟะธััั ะธ ััะฒััะฒะพะฒะฐัั ัะฟะตัะธั...", text); - } + public void testLoadFromFile() throws UnsupportedEncodingException, FileNotFoundException { + Yaml yaml = new Yaml(); + InputStream input = new FileInputStream("src/test/resources/issues/issue68.txt"); + String text = yaml.load(new InputStreamReader(input, StandardCharsets.UTF_8)); + assertEquals("ะ ะถะธัั ัะพัะพะฟะธััั ะธ ััะฒััะฒะพะฒะฐัั ัะฟะตัะธั...", text); + } - public void testLoadFromInputStream() throws IOException { - InputStream input; - input = YamlDocument.class.getClassLoader().getResourceAsStream("issues/issue68.txt"); - if (input == null) { - throw new RuntimeException("Can not find issues/issue68.txt"); - } - Yaml yaml = new Yaml(); - String text = (String) yaml.load(input);// UTF-8 by default - assertEquals("ะ ะถะธัั ัะพัะพะฟะธััั ะธ ััะฒััะฒะพะฒะฐัั ัะฟะตัะธั...", text); - input.close(); + public void testLoadFromInputStream() throws IOException { + InputStream input; + input = YamlDocument.class.getClassLoader().getResourceAsStream("issues/issue68.txt"); + if (input == null) { + throw new RuntimeException("Can not find issues/issue68.txt"); } + Yaml yaml = new Yaml(); + String text = yaml.load(input);// UTF-8 by default + assertEquals("ะ ะถะธัั ัะพัะพะฟะธััั ะธ ััะฒััะฒะพะฒะฐัั ัะฟะตัะธั...", text); + input.close(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue72/CollectionTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue72/CollectionTest.java index ca817e2e..92ee6909 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue72/CollectionTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue72/CollectionTest.java @@ -1,87 +1,85 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue72; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class CollectionTest extends TestCase { - public void testCollectionList() { - CollectionList bean = new CollectionList(); - Yaml yaml = new Yaml(); - String doc = yaml.dumpAsMap(bean); - // System.out.println(doc); - Yaml beanLoader = new Yaml(); - CollectionList parsed = beanLoader.loadAs(doc, CollectionList.class); - assertTrue(parsed.getNames().contains("aaa")); - assertTrue(parsed.getNames().contains("bbb")); - assertEquals(2, parsed.getNames().size()); - } + public void testCollectionList() { + CollectionList bean = new CollectionList(); + Yaml yaml = new Yaml(); + String doc = yaml.dumpAsMap(bean); + // System.out.println(doc); + Yaml beanLoader = new Yaml(); + CollectionList parsed = beanLoader.loadAs(doc, CollectionList.class); + assertTrue(parsed.getNames().contains("aaa")); + assertTrue(parsed.getNames().contains("bbb")); + assertEquals(2, parsed.getNames().size()); + } - public static class CollectionList { - private Collection<String> names; + public static class CollectionList { - public CollectionList() { - names = new ArrayList<String>(); - names.add("aaa"); - names.add("bbb"); - } + private Collection<String> names; - public Collection<String> getNames() { - return names; - } + public CollectionList() { + names = new ArrayList<String>(); + names.add("aaa"); + names.add("bbb"); + } - public void setNames(Collection<String> names) { - this.names = names; - } + public Collection<String> getNames() { + return names; } - public void testCollectionSet() { - CollectionSet bean = new CollectionSet(); - Yaml yaml = new Yaml(); - String doc = yaml.dumpAsMap(bean); - // System.out.println(doc); - Yaml beanLoader = new Yaml(); - CollectionSet parsed = beanLoader.loadAs(doc, CollectionSet.class); - assertTrue(parsed.getRoles().contains(11)); - assertTrue(parsed.getRoles().contains(13)); - assertEquals(2, parsed.getRoles().size()); + public void setNames(Collection<String> names) { + this.names = names; } + } - public static class CollectionSet { - private Collection<Integer> roles; + public void testCollectionSet() { + CollectionSet bean = new CollectionSet(); + Yaml yaml = new Yaml(); + String doc = yaml.dumpAsMap(bean); + // System.out.println(doc); + Yaml beanLoader = new Yaml(); + CollectionSet parsed = beanLoader.loadAs(doc, CollectionSet.class); + assertTrue(parsed.getRoles().contains(11)); + assertTrue(parsed.getRoles().contains(13)); + assertEquals(2, parsed.getRoles().size()); + } - public CollectionSet() { - roles = new HashSet<Integer>(); - roles.add(11); - roles.add(13); - } + public static class CollectionSet { - public Collection<Integer> getRoles() { - return roles; - } + private Collection<Integer> roles; + + public CollectionSet() { + roles = new HashSet<Integer>(); + roles.add(11); + roles.add(13); + } + + public Collection<Integer> getRoles() { + return roles; + } - public void setRoles(Collection<Integer> roles) { - this.roles = roles; - } + public void setRoles(Collection<Integer> roles) { + this.roles = roles; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/ArrayListTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/ArrayListTest.java index b86c6b43..9fed36f3 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/ArrayListTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/ArrayListTest.java @@ -1,65 +1,62 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; import java.util.ArrayList; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; /** - * Test bean when the implementation is defined: ArrayList instead of just the - * interface List + * Test bean when the implementation is defined: ArrayList instead of just the interface List */ public class ArrayListTest extends TestCase { - public void testListImplementation() { - Bean1 bean = new Bean1(); - bean.setId("ID123"); - ArrayList<String> list = new ArrayList<String>(3); - list.add("zzz"); - list.add("xxx"); - list.add("ccc"); - bean.setList(list); - Yaml yaml = new Yaml(); - String doc = yaml.dump(bean); - // System.out.println(doc); - Bean1 loaded = (Bean1) yaml.load(doc); - assertEquals(3, loaded.getList().size()); - assertEquals(ArrayList.class, loaded.getList().getClass()); - } - - public static class Bean1 { - private ArrayList<String> list; - private String id; - public ArrayList<String> getList() { - return list; - } + public void testListImplementation() { + Bean1 bean = new Bean1(); + bean.setId("ID123"); + ArrayList<String> list = new ArrayList<String>(3); + list.add("zzz"); + list.add("xxx"); + list.add("ccc"); + bean.setList(list); + Yaml yaml = new Yaml(); + String doc = yaml.dump(bean); + // System.out.println(doc); + Bean1 loaded = yaml.load(doc); + assertEquals(3, loaded.getList().size()); + assertEquals(ArrayList.class, loaded.getList().getClass()); + } + + public static class Bean1 { + + private ArrayList<String> list; + private String id; + + public ArrayList<String> getList() { + return list; + } - public void setList(ArrayList<String> list) { - this.list = list; - } + public void setList(ArrayList<String> list) { + this.list = list; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/Blog.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/Blog.java index 1e0be237..e7b80627 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/Blog.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/Blog.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; @@ -21,59 +19,59 @@ import java.util.TreeSet; public class Blog { - private String name; - private Set<Post> posts = new TreeSet<Post>(); - public Set<Integer> numbers = new LinkedHashSet<Integer>(); - private TreeSet<String> labels = new TreeSet<String>(); + private String name; + private Set<Post> posts = new TreeSet<Post>(); + public Set<Integer> numbers = new LinkedHashSet<Integer>(); + private TreeSet<String> labels = new TreeSet<String>(); - public Blog() { - name = "SuperBlog"; - } + public Blog() { + name = "SuperBlog"; + } - public Blog(String name) { - this.name = name; - } + public Blog(String name) { + this.name = name; + } - public void addPost(Post p) { - posts.add(p); - } + public void addPost(Post p) { + posts.add(p); + } - public Set<Post> getPosts() { - return posts; - } + public Set<Post> getPosts() { + return posts; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public void setPosts(Set<Post> posts) { - this.posts = posts; - } + public void setPosts(Set<Post> posts) { + this.posts = posts; + } - public TreeSet<String> getLabels() { - return labels; - } + public TreeSet<String> getLabels() { + return labels; + } - public void setLabels(TreeSet<String> labels) { - this.labels = labels; - } + public void setLabels(TreeSet<String> labels) { + this.labels = labels; + } - @Override - public boolean equals(Object obj) { - return name.equals(obj.toString()); - } + @Override + public boolean equals(Object obj) { + return name.equals(obj.toString()); + } - @Override - public int hashCode() { - return name.hashCode(); - } + @Override + public int hashCode() { + return name.hashCode(); + } - @Override - public String toString() { - return "Blog '" + name + "'"; - } -}
\ No newline at end of file + @Override + public String toString() { + return "Blog '" + name + "'"; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/DumpSetAsSequenceExampleTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/DumpSetAsSequenceExampleTest.java index a656a68b..cf465a81 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/DumpSetAsSequenceExampleTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/DumpSetAsSequenceExampleTest.java @@ -1,25 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; import java.util.Set; import java.util.TreeSet; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Util; @@ -32,67 +28,69 @@ import org.yaml.snakeyaml.representer.Representer; public class DumpSetAsSequenceExampleTest extends TestCase { - public void testDumpFlow() { - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(new SetRepresenter(), options); - String output = yaml.dump(createBlog()); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue73-dump7.txt"), output); - // - check(output); - } + public void testDumpFlow() { + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(new SetRepresenter(), options); + String output = yaml.dump(createBlog()); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue73-dump7.txt"), output); + // + check(output); + } - public void testDumpBlock() { - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(new SetRepresenter(), options); - String output = yaml.dump(createBlog()); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue73-dump8.txt"), output); - // - check(output); + public void testDumpBlock() { + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(new SetRepresenter(), options); + String output = yaml.dump(createBlog()); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue73-dump8.txt"), output); + // + check(output); + } + + private class SetRepresenter extends Representer { + + public SetRepresenter() { + this.multiRepresenters.put(Set.class, new RepresentIterable()); } - private class SetRepresenter extends Representer { - public SetRepresenter() { - this.multiRepresenters.put(Set.class, new RepresentIterable()); - } + private class RepresentIterable implements Represent { - private class RepresentIterable implements Represent { - @SuppressWarnings("unchecked") - public Node representData(Object data) { - return representSequence(getTag(data.getClass(), Tag.SEQ), (Iterable<Object>) data, - null); + @SuppressWarnings("unchecked") + public Node representData(Object data) { + return representSequence(getTag(data.getClass(), Tag.SEQ), (Iterable<Object>) data, + DumperOptions.FlowStyle.AUTO); - } - } + } } + } - private Blog createBlog() { - Blog blog = new Blog("Test Me!"); - blog.addPost(new Post("Title1", "text 1")); - blog.addPost(new Post("Title2", "text text 2")); - blog.numbers.add(19); - blog.numbers.add(17); - TreeSet<String> labels = new TreeSet<String>(); - labels.add("Java"); - labels.add("YAML"); - labels.add("SnakeYAML"); - blog.setLabels(labels); - return blog; - } + private Blog createBlog() { + Blog blog = new Blog("Test Me!"); + blog.addPost(new Post("Title1", "text 1")); + blog.addPost(new Post("Title2", "text text 2")); + blog.numbers.add(19); + blog.numbers.add(17); + TreeSet<String> labels = new TreeSet<String>(); + labels.add("Java"); + labels.add("YAML"); + labels.add("SnakeYAML"); + blog.setLabels(labels); + return blog; + } - private void check(String doc) { - Yaml yamlLoader = new Yaml(); - yamlLoader.setBeanAccess(BeanAccess.FIELD); - Blog blog = (Blog) yamlLoader.load(doc); - assertEquals("Test Me!", blog.getName()); - assertEquals(2, blog.numbers.size()); - assertEquals(2, blog.getPosts().size()); - for (Post post : blog.getPosts()) { - assertEquals(Post.class, post.getClass()); - } + private void check(String doc) { + Yaml yamlLoader = new Yaml(); + yamlLoader.setBeanAccess(BeanAccess.FIELD); + Blog blog = yamlLoader.load(doc); + assertEquals("Test Me!", blog.getName()); + assertEquals(2, blog.numbers.size()); + assertEquals(2, blog.getPosts().size()); + for (Post post : blog.getPosts()) { + assertEquals(Post.class, post.getClass()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/Post.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/Post.java index 17395495..9204d39e 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/Post.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/Post.java @@ -1,62 +1,59 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; class Post implements Comparable<Post> { - private String title; - private String text; + private String title; + private String text; - protected Post() { - } + protected Post() {} - public Post(String title, String text) { - super(); - this.title = title; - this.text = text; - } + public Post(String title, String text) { + super(); + this.title = title; + this.text = text; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public int compareTo(Post o) { - return title.compareTo(o.title); - } + public int compareTo(Post o) { + return title.compareTo(o.title); + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Post) { - return toString().equals(obj.toString()); - } else { - return false; - } + @Override + public boolean equals(Object obj) { + if (obj instanceof Post) { + return toString().equals(obj.toString()); + } else { + return false; } + } - @Override - public int hashCode() { - return toString().hashCode(); - } + @Override + public int hashCode() { + return toString().hashCode(); + } - @Override - public String toString() { - return "Post " + title + " " + text; - } -}
\ No newline at end of file + @Override + public String toString() { + return "Post " + title + " " + text; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSetTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSetTest.java index ef8b01fe..48aedff9 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSetTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSetTest.java @@ -1,119 +1,120 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class RecursiveSetTest extends TestCase { - public void testDumpException() { - Set<Object> set1 = new HashSet<Object>(); - Set<Object> set2 = new HashSet<Object>(); - set1.add(set2); - set2.add(set1); - Yaml yaml = new Yaml(); - try { - yaml.dump(set1); - fail("Recursive sets are not supported."); - } catch (StackOverflowError e) { - assertEquals(null, e.getMessage()); - } + + public void testDumpException() { + Set<Object> set1 = new HashSet<Object>(); + Set<Object> set2 = new HashSet<Object>(); + set1.add(set2); + set2.add(set1); + Yaml yaml = new Yaml(); + try { + yaml.dump(set1); + fail("Recursive sets are not supported."); + } catch (StackOverflowError e) { + assertNull(e.getMessage()); } + } - public void testLoadException() { - String doc = Util.getLocalResource("issues/issue73-recursive4.txt"); - // System.out.println(doc); - Yaml yaml = new Yaml(); - try { - yaml.load(doc); - fail("Recursive sets are not supported."); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("Set cannot be recursive.")); - } + public void testLoadException() { + String doc = Util.getLocalResource("issues/issue73-recursive4.txt"); + // System.out.println(doc); + Yaml yaml = new Yaml(); + try { + yaml.load(doc); + fail("Recursive sets are not supported."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("Set cannot be recursive.")); } + } - /** - * XXX: sets can be recursive - */ - @SuppressWarnings("unchecked") - public void testLoadRecursiveTest() { - String doc = Util.getLocalResource("issues/issue73-recursive5.txt"); - // System.out.println(doc); - Yaml yaml = new Yaml(); - Bean1 obj = (Bean1) yaml.load(doc); - Set<Object> set = obj.getSet(); - // System.out.println(set); - assertEquals(LinkedHashSet.class, set.getClass()); - assertEquals("ID123", obj.getId()); - assertEquals(3, set.size()); - assertTrue(set.remove("zzz")); - assertTrue(set.remove("ccc")); - assertFalse(set.contains("111")); - try { - set.contains(set); - fail("Recursive set fails to provide a hashcode."); - } catch (StackOverflowError e) { - // ignore - } - // - Set<Object> self = (Set<Object>) set.iterator().next(); - assertEquals(LinkedHashSet.class, self.getClass()); - assertEquals(set, self); - assertSame(set, self); - assertEquals(1, set.size()); - assertEquals(1, self.size()); - set.add("111"); - assertEquals(2, set.size()); - assertEquals(2, self.size()); - // - self.clear(); - assertTrue(self.isEmpty()); - assertTrue(set.isEmpty()); - assertFalse("Now it should not be recursive any longer (no StackOverflowError).", - set.contains(set)); - // - set.add("jjj"); - assertEquals(1, set.size()); - assertEquals(1, self.size()); + /** + * XXX: sets can be recursive + */ + @SuppressWarnings("unchecked") + public void testLoadRecursiveTest() { + String doc = Util.getLocalResource("issues/issue73-recursive5.txt"); + // System.out.println(doc); + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Yaml yaml = new Yaml(options); + Bean1 obj = yaml.load(doc); + Set<Object> set = obj.getSet(); + // System.out.println(set); + assertEquals(LinkedHashSet.class, set.getClass()); + assertEquals("ID123", obj.getId()); + assertEquals(3, set.size()); + assertTrue(set.remove("zzz")); + assertTrue(set.remove("ccc")); + assertFalse(set.contains("111")); + try { + set.contains(set); + fail("Recursive set fails to provide a hashcode."); + } catch (StackOverflowError e) { + // ignore } + // + Set<Object> self = (Set<Object>) set.iterator().next(); + assertEquals(LinkedHashSet.class, self.getClass()); + assertEquals(set, self); + assertSame(set, self); + assertEquals(1, set.size()); + assertEquals(1, self.size()); + set.add("111"); + assertEquals(2, set.size()); + assertEquals(2, self.size()); + // + self.clear(); + assertTrue(self.isEmpty()); + assertTrue(set.isEmpty()); + assertFalse("Now it should not be recursive any longer (no StackOverflowError).", + set.contains(set)); + // + set.add("jjj"); + assertEquals(1, set.size()); + assertEquals(1, self.size()); + } - public static class Bean1 { - private Set<Object> set; - private String id; + public static class Bean1 { - public Set<Object> getSet() { - return set; - } + private Set<Object> set; + private String id; - public void setSet(Set<Object> set) { - this.set = set; - } + public Set<Object> getSet() { + return set; + } - public String getId() { - return id; - } + public void setSet(Set<Object> set) { + this.set = set; + } + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSortedSetTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSortedSetTest.java index 52244298..6229f897 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSortedSetTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/RecursiveSortedSetTest.java @@ -1,127 +1,128 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class RecursiveSortedSetTest extends TestCase { - public void testDumpException() { - SortedSet<Object> set = new TreeSet<Object>(); - Bean11 bean = new Bean11(); - bean.setId("ID555"); - bean.setSet(set); - set.add("ggg"); - set.add("hhh"); - set.add(bean); - Yaml yaml = new Yaml(); - String doc = yaml.dump(bean); - // System.out.println(doc); - assertEquals(Util.getLocalResource("issues/issue73-recursive9.txt"), doc); - } - public void testLoadException() { - String doc = Util.getLocalResource("issues/issue73-recursive10.txt"); - // System.out.println(doc); - Yaml yaml = new Yaml(); - try { - yaml.load(doc); - fail("Recursive sets are not supported."); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("Set cannot be recursive.")); - } - } + public void testDumpException() { + SortedSet<Object> set = new TreeSet<Object>(); + Bean11 bean = new Bean11(); + bean.setId("ID555"); + bean.setSet(set); + set.add("ggg"); + set.add("hhh"); + set.add(bean); + Yaml yaml = new Yaml(); + String doc = yaml.dump(bean); + // System.out.println(doc); + assertEquals(Util.getLocalResource("issues/issue73-recursive9.txt"), doc); + } - /** - * set and JavaBean refer to each other - */ - public void testLoadRecursiveTest() { - String doc = Util.getLocalResource("issues/issue73-recursive9.txt"); - // System.out.println(doc); - Yaml yaml = new Yaml(); - Bean11 beanWithSet = (Bean11) yaml.load(doc); - Set<Object> set = beanWithSet.getSet(); - assertEquals(TreeSet.class, set.getClass()); - assertEquals("ID555", beanWithSet.getId()); - assertEquals(3, set.size()); - assertTrue(set.remove("ggg")); - // assertFalse(set.remove("ggg"));??? - assertTrue(set.remove("hhh")); - assertEquals(1, set.size()); - // - Bean11 beanRef = (Bean11) set.iterator().next(); - assertEquals(beanWithSet, beanRef); - assertSame(beanWithSet, beanRef); - // - assertFalse(set.isEmpty()); - assertTrue(set.contains(beanWithSet)); - assertFalse(set.add(beanWithSet)); - assertTrue(set.remove(beanWithSet)); - assertFalse(set.remove(beanWithSet)); - assertTrue(set.isEmpty()); + public void testLoadException() { + String doc = Util.getLocalResource("issues/issue73-recursive10.txt"); + // System.out.println(doc); + Yaml yaml = new Yaml(); + try { + yaml.load(doc); + fail("Recursive sets are not supported."); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("Set cannot be recursive.")); } + } - public static class Bean11 implements Comparable<Object> { - private SortedSet<Object> set; - private String id; + /** + * set and JavaBean refer to each other + */ + public void testLoadRecursiveTest() { + String doc = Util.getLocalResource("issues/issue73-recursive9.txt"); + // System.out.println(doc); + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Yaml yaml = new Yaml(options); + Bean11 beanWithSet = yaml.load(doc); + Set<Object> set = beanWithSet.getSet(); + assertEquals(TreeSet.class, set.getClass()); + assertEquals("ID555", beanWithSet.getId()); + assertEquals(3, set.size()); + assertTrue(set.remove("ggg")); + // assertFalse(set.remove("ggg"));??? + assertTrue(set.remove("hhh")); + assertEquals(1, set.size()); + // + Bean11 beanRef = (Bean11) set.iterator().next(); + assertEquals(beanWithSet, beanRef); + assertSame(beanWithSet, beanRef); + // + assertFalse(set.isEmpty()); + assertTrue(set.contains(beanWithSet)); + assertFalse(set.add(beanWithSet)); + assertTrue(set.remove(beanWithSet)); + assertFalse(set.remove(beanWithSet)); + assertTrue(set.isEmpty()); + } - public SortedSet<Object> getSet() { - return set; - } + public static class Bean11 implements Comparable<Object> { - public void setSet(SortedSet<Object> set) { - this.set = set; - } + private SortedSet<Object> set; + private String id; - public String getId() { - return id; - } + public SortedSet<Object> getSet() { + return set; + } - public void setId(String id) { - this.id = id; - } + public void setSet(SortedSet<Object> set) { + this.set = set; + } - public int compareTo(Object o) { - return toString().compareTo(o.toString()); - } + public String getId() { + return id; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Bean11) { - Bean11 b = (Bean11) obj; - return id.equals(b.id); - } else { - return false; - } - } + public void setId(String id) { + this.id = id; + } + + public int compareTo(Object o) { + return toString().compareTo(o.toString()); + } - @Override - public int hashCode() { - return toString().hashCode(); - } + @Override + public boolean equals(Object obj) { + if (obj instanceof Bean11) { + Bean11 b = (Bean11) obj; + return id.equals(b.id); + } else { + return false; + } + } + + @Override + public int hashCode() { + return toString().hashCode(); + } - @Override - public String toString() { - return "Bean id=" + id + "set=" + System.identityHashCode(set); - } + @Override + public String toString() { + return "Bean id=" + id + "set=" + System.identityHashCode(set); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/SetAsSequenceTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/SetAsSequenceTest.java index 7d3b4afe..74f6a92e 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/SetAsSequenceTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/SetAsSequenceTest.java @@ -1,27 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -29,106 +24,106 @@ import org.yaml.snakeyaml.introspector.BeanAccess; public class SetAsSequenceTest extends TestCase { - public void testDump() { - Blog blog = new Blog("Test Me!"); - blog.addPost(new Post("Title1", "text 1")); - blog.addPost(new Post("Title2", "text text 2")); - blog.numbers.add(19); - blog.numbers.add(17); - TreeSet<String> labels = new TreeSet<String>(); - labels.add("Java"); - labels.add("YAML"); - labels.add("SnakeYAML"); - blog.setLabels(labels); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - String output = yaml.dump(blog); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue73-1.txt"), output); - } + public void testDump() { + Blog blog = new Blog("Test Me!"); + blog.addPost(new Post("Title1", "text 1")); + blog.addPost(new Post("Title2", "text text 2")); + blog.numbers.add(19); + blog.numbers.add(17); + TreeSet<String> labels = new TreeSet<String>(); + labels.add("Java"); + labels.add("YAML"); + labels.add("SnakeYAML"); + blog.setLabels(labels); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + String output = yaml.dump(blog); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue73-1.txt"), output); + } - public void testLoad() { - Yaml yaml = new Yaml(); - yaml.setBeanAccess(BeanAccess.FIELD); - String doc = Util.getLocalResource("issues/issue73-1.txt"); - Blog blog = (Blog) yaml.load(doc); - // System.out.println(blog); - assertEquals("Test Me!", blog.getName()); - assertEquals(2, blog.numbers.size()); - assertEquals(2, blog.getPosts().size()); - for (Post post : blog.getPosts()) { - assertEquals(Post.class, post.getClass()); - } + public void testLoad() { + Yaml yaml = new Yaml(); + yaml.setBeanAccess(BeanAccess.FIELD); + String doc = Util.getLocalResource("issues/issue73-1.txt"); + Blog blog = yaml.load(doc); + // System.out.println(blog); + assertEquals("Test Me!", blog.getName()); + assertEquals(2, blog.numbers.size()); + assertEquals(2, blog.getPosts().size()); + for (Post post : blog.getPosts()) { + assertEquals(Post.class, post.getClass()); } + } - public void testYaml() { - String serialized = Util.getLocalResource("issues/issue73-2.txt"); - // System.out.println(serialized); - Yaml beanLoader = new Yaml(); - beanLoader.setBeanAccess(BeanAccess.FIELD); - Blog rehydrated = beanLoader.loadAs(serialized, Blog.class); - checkTestBlog(rehydrated); - } + public void testYaml() { + String serialized = Util.getLocalResource("issues/issue73-2.txt"); + // System.out.println(serialized); + Yaml beanLoader = new Yaml(); + beanLoader.setBeanAccess(BeanAccess.FIELD); + Blog rehydrated = beanLoader.loadAs(serialized, Blog.class); + checkTestBlog(rehydrated); + } - protected void checkTestBlog(Blog blog) { - Set<Post> posts = blog.getPosts(); - assertEquals("Blog contains 2 posts", 2, posts.size()); - assertTrue(posts.contains(new Post("Test", "Dummy"))); - assertTrue(posts.contains(new Post("Highly", "Creative"))); - assertEquals("No tags!", blog.getName()); - assertEquals(0, blog.numbers.size()); - } + protected void checkTestBlog(Blog blog) { + Set<Post> posts = blog.getPosts(); + assertEquals("Blog contains 2 posts", 2, posts.size()); + assertTrue(posts.contains(new Post("Test", "Dummy"))); + assertTrue(posts.contains(new Post("Highly", "Creative"))); + assertEquals("No tags!", blog.getName()); + assertEquals(0, blog.numbers.size()); + } - @SuppressWarnings("unchecked") - public void testLoadRootSet() { - Yaml yaml = new Yaml(); - String doc = Util.getLocalResource("issues/issue73-3.txt"); - Set<String> strings = (Set<String>) yaml.load(doc); - // System.out.println(strings); - assertEquals(3, strings.size()); - assertEquals(HashSet.class, strings.getClass()); - assertTrue(strings.contains("aaa")); - assertTrue(strings.contains("bbb")); - assertTrue(strings.contains("ccc")); - } + @SuppressWarnings("unchecked") + public void testLoadRootSet() { + Yaml yaml = new Yaml(); + String doc = Util.getLocalResource("issues/issue73-3.txt"); + Set<String> strings = yaml.load(doc); + // System.out.println(strings); + assertEquals(3, strings.size()); + assertEquals(HashSet.class, strings.getClass()); + assertTrue(strings.contains("aaa")); + assertTrue(strings.contains("bbb")); + assertTrue(strings.contains("ccc")); + } - @SuppressWarnings("unchecked") - public void testLoadRootSet2() { - Yaml yaml = new Yaml(); - String doc = "!!java.util.HashSet {aaa: null, bbb: null, ccc: null}"; - Set<String> strings = (Set<String>) yaml.load(doc); - // System.out.println(strings); - assertEquals(3, strings.size()); - assertEquals(LinkedHashSet.class, strings.getClass()); - assertTrue(strings.contains("aaa")); - assertTrue(strings.contains("bbb")); - assertTrue(strings.contains("ccc")); - } + @SuppressWarnings("unchecked") + public void testLoadRootSet2() { + Yaml yaml = new Yaml(); + String doc = "!!java.util.HashSet {aaa: null, bbb: null, ccc: null}"; + Set<String> strings = yaml.load(doc); + // System.out.println(strings); + assertEquals(3, strings.size()); + assertEquals(HashSet.class, strings.getClass()); + assertTrue(strings.contains("aaa")); + assertTrue(strings.contains("bbb")); + assertTrue(strings.contains("ccc")); + } - @SuppressWarnings("unchecked") - public void testLoadRootSet3() { - Yaml yaml = new Yaml(); - String doc = "!!java.util.TreeSet {aaa: null, bbb: null, ccc: null}"; - Set<String> strings = (Set<String>) yaml.load(doc); - // System.out.println(strings); - assertEquals(3, strings.size()); - assertEquals(TreeSet.class, strings.getClass()); - assertTrue(strings.contains("aaa")); - assertTrue(strings.contains("bbb")); - assertTrue(strings.contains("ccc")); - } + @SuppressWarnings("unchecked") + public void testLoadRootSet3() { + Yaml yaml = new Yaml(); + String doc = "!!java.util.TreeSet {aaa: null, bbb: null, ccc: null}"; + Set<String> strings = yaml.load(doc); + // System.out.println(strings); + assertEquals(3, strings.size()); + assertEquals(TreeSet.class, strings.getClass()); + assertTrue(strings.contains("aaa")); + assertTrue(strings.contains("bbb")); + assertTrue(strings.contains("ccc")); + } - @SuppressWarnings("unchecked") - public void testLoadRootSet6() { - Yaml yaml = new Yaml(); - String doc = Util.getLocalResource("issues/issue73-6.txt"); - Set<String> strings = (Set<String>) yaml.load(doc); - // System.out.println(strings); - assertEquals(3, strings.size()); - assertEquals(TreeSet.class, strings.getClass()); - assertTrue(strings.contains("aaa")); - assertTrue(strings.contains("bbb")); - assertTrue(strings.contains("ccc")); - } + @SuppressWarnings("unchecked") + public void testLoadRootSet6() { + Yaml yaml = new Yaml(); + String doc = Util.getLocalResource("issues/issue73-6.txt"); + Set<String> strings = yaml.load(doc); + // System.out.println(strings); + assertEquals(3, strings.size()); + assertEquals(TreeSet.class, strings.getClass()); + assertTrue(strings.contains("aaa")); + assertTrue(strings.contains("bbb")); + assertTrue(strings.contains("ccc")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue73/TreeSetTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue73/TreeSetTest.java index 7d4a3e08..924de3ef 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue73/TreeSetTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue73/TreeSetTest.java @@ -1,69 +1,66 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue73; import java.util.TreeSet; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; /** - * Test bean when the implementation is defined: TreeSet instead of just the - * interface Set + * Test bean when the implementation is defined: TreeSet instead of just the interface Set */ public class TreeSetTest extends TestCase { - public void testSetImplementation() { - Bean1 bean = new Bean1(); - bean.setId("ID123"); - TreeSet<String> list = new TreeSet<String>(); - list.add("zzz"); - list.add("xxx"); - list.add("ccc"); - bean.setSet(list); - Yaml yaml = new Yaml(); - String doc = yaml.dump(bean); - // System.out.println(doc); - // - Bean1 loaded = (Bean1) yaml.load(doc); - assertEquals(3, loaded.getSet().size()); - assertEquals(TreeSet.class, loaded.getSet().getClass()); - assertTrue(loaded.getSet().contains("zzz")); - assertTrue(loaded.getSet().contains("xxx")); - assertTrue(loaded.getSet().contains("ccc")); - } - public static class Bean1 { - private TreeSet<String> set; - private String id; + public void testSetImplementation() { + Bean1 bean = new Bean1(); + bean.setId("ID123"); + TreeSet<String> list = new TreeSet<String>(); + list.add("zzz"); + list.add("xxx"); + list.add("ccc"); + bean.setSet(list); + Yaml yaml = new Yaml(); + String doc = yaml.dump(bean); + // System.out.println(doc); + // + Bean1 loaded = yaml.load(doc); + assertEquals(3, loaded.getSet().size()); + assertEquals(TreeSet.class, loaded.getSet().getClass()); + assertTrue(loaded.getSet().contains("zzz")); + assertTrue(loaded.getSet().contains("xxx")); + assertTrue(loaded.getSet().contains("ccc")); + } + + public static class Bean1 { - public TreeSet<String> getSet() { - return set; - } + private TreeSet<String> set; + private String id; - public void setSet(TreeSet<String> set) { - this.set = set; - } + public TreeSet<String> getSet() { + return set; + } + + public void setSet(TreeSet<String> set) { + this.set = set; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue74/ArrayBeanTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue74/ArrayBeanTest.java index 716294e4..3fc91912 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue74/ArrayBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue74/ArrayBeanTest.java @@ -1,150 +1,148 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue74; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class ArrayBeanTest extends TestCase { - public void testArrayProperty() { - ArrayMember[] members = new ArrayMember[3]; - members[0] = new ArrayMember("Foo", 21); - members[1] = new ArrayMember("Bar", 23); - members[2] = new ArrayMember("Hue Long Hair", 25); - ArrayBean bean = new ArrayBean(); - bean.setId("ID123"); - bean.setNumber(7); - bean.setMembers(members); - bean.openMembers = new ArrayMember[] { new ArrayMember("OpenFoo", 1000), - new ArrayMember("OpenBar", 2000) }; - List<ArrayMember> list = new ArrayList<ArrayMember>(2); - list.add(new ArrayMember("John", 111)); - list.add(new ArrayMember("Tony", 222)); - bean.setList(list); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(bean); - // System.out.println(output); - assertEquals(Util.getLocalResource("issues/issue74-array1.txt"), output); - Yaml beanLoader = new Yaml(); - ArrayBean parsed = beanLoader.loadAs(output, ArrayBean.class); - // System.out.println(parsed); - assertEquals(3, parsed.getMembers().length); - assertEquals(2, parsed.openMembers.length); - assertEquals(2, parsed.getList().size()); - assertEquals("ID123", parsed.getId()); - assertEquals(7, parsed.getNumber()); - for (ArrayMember member : parsed.getMembers()) { - assertTrue((member.getAge() >= 21) && (member.getAge() <= 25)); - } - } - - public static class ArrayBean { - private String id; - private int number; - private ArrayMember[] members; - public ArrayMember[] openMembers; - private List<ArrayMember> list; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public int getNumber() { - return number; - } - - public void setNumber(int number) { - this.number = number; - } - - public ArrayMember[] getMembers() { - return members; - } - - public void setMembers(ArrayMember[] members) { - this.members = members; - } - - public List<ArrayMember> getList() { - return list; - } - - public void setList(List<ArrayMember> list) { - this.list = list; - } - } - - public static class ArrayMember { - private String name; - private int age; - - public ArrayMember(String name, int age) { - this.name = name; - this.age = age; - } - - public ArrayMember() { - this.name = "NoName"; - this.age = 0; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof ArrayMember) { - ArrayMember m = (ArrayMember) obj; - return age == m.age; - } else { - return false; - } - } - - @Override - public int hashCode() { - return age; - } - - @Override - public String toString() { - return "ArrayMember age=" + age; - } + public void testArrayProperty() { + ArrayMember[] members = new ArrayMember[3]; + members[0] = new ArrayMember("Foo", 21); + members[1] = new ArrayMember("Bar", 23); + members[2] = new ArrayMember("Hue Long Hair", 25); + ArrayBean bean = new ArrayBean(); + bean.setId("ID123"); + bean.setNumber(7); + bean.setMembers(members); + bean.openMembers = + new ArrayMember[] {new ArrayMember("OpenFoo", 1000), new ArrayMember("OpenBar", 2000)}; + List<ArrayMember> list = new ArrayList<ArrayMember>(2); + list.add(new ArrayMember("John", 111)); + list.add(new ArrayMember("Tony", 222)); + bean.setList(list); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(bean); + // System.out.println(output); + assertEquals(Util.getLocalResource("issues/issue74-array1.txt"), output); + Yaml beanLoader = new Yaml(); + ArrayBean parsed = beanLoader.loadAs(output, ArrayBean.class); + // System.out.println(parsed); + assertEquals(3, parsed.getMembers().length); + assertEquals(2, parsed.openMembers.length); + assertEquals(2, parsed.getList().size()); + assertEquals("ID123", parsed.getId()); + assertEquals(7, parsed.getNumber()); + for (ArrayMember member : parsed.getMembers()) { + assertTrue((member.getAge() >= 21) && (member.getAge() <= 25)); + } + } + + public static class ArrayBean { + + private String id; + private int number; + private ArrayMember[] members; + public ArrayMember[] openMembers; + private List<ArrayMember> list; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getNumber() { + return number; + } + + public void setNumber(int number) { + this.number = number; + } + + public ArrayMember[] getMembers() { + return members; + } + + public void setMembers(ArrayMember[] members) { + this.members = members; + } + + public List<ArrayMember> getList() { + return list; + } + + public void setList(List<ArrayMember> list) { + this.list = list; + } + } + + public static class ArrayMember { + + private String name; + private int age; + + public ArrayMember(String name, int age) { + this.name = name; + this.age = age; + } + + public ArrayMember() { + this.name = "NoName"; + this.age = 0; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof ArrayMember) { + ArrayMember m = (ArrayMember) obj; + return age == m.age; + } else { + return false; + } + } + + @Override + public int hashCode() { + return age; + } + + @Override + public String toString() { + return "ArrayMember age=" + age; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue8/Person.java b/src/test/java/org/yaml/snakeyaml/issues/issue8/Person.java index 1714a918..ae58fb35 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue8/Person.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue8/Person.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue8; @@ -21,56 +19,56 @@ import java.io.Serializable; * to test http://code.google.com/p/snakeyaml/issues/detail?id=8 */ public class Person implements Serializable { - private static final long serialVersionUID = 1L; - private String firstName; - private String lastName; - private int hatSize; - public Person() { - } + private static final long serialVersionUID = 1L; + private String firstName; + private String lastName; + private int hatSize; - public Person(String firstName, String lastName, int hatSize) { - this.firstName = firstName; - this.lastName = lastName; - this.hatSize = hatSize; - } + public Person() {} - public String getFirstName() { - return firstName; - } + public Person(String firstName, String lastName, int hatSize) { + this.firstName = firstName; + this.lastName = lastName; + this.hatSize = hatSize; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public String getFirstName() { + return firstName; + } - public String getLastName() { - return lastName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public String getLastName() { + return lastName; + } - public int getHatSize() { - return hatSize; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public void setHatSize(int hatSize) { - this.hatSize = hatSize; - } + public int getHatSize() { + return hatSize; + } - @Override - public boolean equals(Object object) { - if (object instanceof Person) { - Person person = (Person) object; - return firstName.equals(person.firstName) && lastName.equals(person.lastName) - && hatSize == person.hatSize; - } - return false; - } + public void setHatSize(int hatSize) { + this.hatSize = hatSize; + } - @Override - public int hashCode() { - return 1; + @Override + public boolean equals(Object object) { + if (object instanceof Person) { + Person person = (Person) object; + return firstName.equals(person.firstName) && lastName.equals(person.lastName) + && hatSize == person.hatSize; } + return false; + } + + @Override + public int hashCode() { + return 1; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue8/PrattleRepresenterTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue8/PrattleRepresenterTest.java index b51ebb45..01b378c9 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue8/PrattleRepresenterTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue8/PrattleRepresenterTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue8; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; @@ -24,43 +21,48 @@ import org.yaml.snakeyaml.Yaml; * to test http://code.google.com/p/snakeyaml/issues/detail?id=8 */ public class PrattleRepresenterTest extends TestCase { - public void test() { - Yaml yaml = new Yaml(); - Person person = new Person("Alan", "Gutierrez", 9); - String etalon = "!!org.yaml.snakeyaml.issues.issue8.Person {firstName: Alan, hatSize: 9, lastName: Gutierrez}\n"; - assertEquals(etalon, yaml.dump(person)); - assertEquals(etalon, yaml.dump(person)); - } - public void test2beans() { - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - Person person = new Person("Alan", "Gutierrez", 9); - String etalon = "!!org.yaml.snakeyaml.issues.issue8.Person {firstName: Alan, hatSize: 9, lastName: Gutierrez}\n"; - assertEquals(etalon, yaml.dump(person)); - Horse horse = new Horse("Tom", person); - String etalon2 = "!!org.yaml.snakeyaml.issues.issue8.PrattleRepresenterTest$Horse\nname: Tom\nowner: {firstName: Alan, hatSize: 9, lastName: Gutierrez}\n"; - assertEquals(etalon2, yaml.dump(horse)); - } + public void test() { + Yaml yaml = new Yaml(); + Person person = new Person("Alan", "Gutierrez", 9); + String etalon = + "!!org.yaml.snakeyaml.issues.issue8.Person {firstName: Alan, hatSize: 9, lastName: Gutierrez}\n"; + assertEquals(etalon, yaml.dump(person)); + assertEquals(etalon, yaml.dump(person)); + } - public static class Horse { - private String name; - private Person owner; + public void test2beans() { + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + Person person = new Person("Alan", "Gutierrez", 9); + String etalon = + "!!org.yaml.snakeyaml.issues.issue8.Person {firstName: Alan, hatSize: 9, lastName: Gutierrez}\n"; + assertEquals(etalon, yaml.dump(person)); + Horse horse = new Horse("Tom", person); + String etalon2 = + "!!org.yaml.snakeyaml.issues.issue8.PrattleRepresenterTest$Horse\nname: Tom\nowner: {firstName: Alan, hatSize: 9, lastName: Gutierrez}\n"; + assertEquals(etalon2, yaml.dump(horse)); + } - public Horse(String name, Person owner) { - super(); - this.name = name; - this.owner = owner; - } + public static class Horse { - public String getName() { - return name; - } + private final String name; + private final Person owner; - public Person getOwner() { - return owner; - } + public Horse(String name, Person owner) { + super(); + this.name = name; + this.owner = owner; + } + public String getName() { + return name; } + + public Person getOwner() { + return owner; + } + + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue82/PropOrderInfluenceWhenAliasedInGenericCollectionTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue82/PropOrderInfluenceWhenAliasedInGenericCollectionTest.java index fb07b909..b608776c 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue82/PropOrderInfluenceWhenAliasedInGenericCollectionTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue82/PropOrderInfluenceWhenAliasedInGenericCollectionTest.java @@ -1,29 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue82; +import static org.junit.Assert.assertNotEquals; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; @@ -35,286 +33,291 @@ import org.yaml.snakeyaml.representer.Representer; */ public class PropOrderInfluenceWhenAliasedInGenericCollectionTest extends TestCase { - public static interface Account { - } + public interface Account { - public static class GeneralAccount implements Account { - public String name = "General"; - } + } - public static class SuperSaverAccount extends GeneralAccount { + public static class GeneralAccount implements Account { - public SuperSaverAccount() { - name = "SuperSaver"; - } - } + public String name = "General"; + } - public static class CustomerAB { - public Collection<Account> aAll; - public Collection<GeneralAccount> bGeneral; + public static class SuperSaverAccount extends GeneralAccount { - @Override - public String toString() { - return "CustomerAB"; - } + public SuperSaverAccount() { + name = "SuperSaver"; } + } - public static class CustomerBA { - public Collection<GeneralAccount> aGeneral; - public Collection<Account> bAll; - } + public static class CustomerAB { - public static class CustomerAB_MapValue { - public Collection<Account> aAll; - public Map<String, GeneralAccount> bGeneralMap; + public Collection<Account> aAll; + public Collection<GeneralAccount> bGeneral; - @Override - public String toString() { - return "CustomerAB_MapValue"; - } + @Override + public String toString() { + return "CustomerAB"; } + } - public static class CustomerAB_MapKey { - public Collection<Account> aAll; - public Map<GeneralAccount, String> bGeneralMap; + public static class CustomerBA { - @Override - public String toString() { - return "CustomerAB_MapKey"; - } - } + public Collection<GeneralAccount> aGeneral; + public Collection<Account> bAll; + } - public static class CustomerAB_Property { - public Account acc; - public Collection<GeneralAccount> bGeneral; + public static class CustomerAB_MapValue { - @Override - public String toString() { - return "CustomerAB_Property"; - } - } + public Collection<Account> aAll; + public Map<String, GeneralAccount> bGeneralMap; - public void testAB() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB customerAB = new CustomerAB(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); - general.add(generalAccount); - general.add(supersaver); - - customerAB.aAll = all; - customerAB.bGeneral = general; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(customerAB); - // System.out.println(dump); - CustomerAB parsed = (CustomerAB) yaml.load(dump); - assertNotNull(parsed); + @Override + public String toString() { + return "CustomerAB_MapValue"; } + } - public void testAB_Set() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB customerAB = new CustomerAB(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - Set<GeneralAccount> general = new HashSet<GeneralAccount>(); - general.add(generalAccount); - general.add(supersaver); - - customerAB.aAll = all; - customerAB.bGeneral = general; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(customerAB); - // System.out.println(dump); - CustomerAB parsed = (CustomerAB) yaml.load(dump); - assertNotNull(parsed); - } - - public void testABWithCustomTag() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB customerAB = new CustomerAB(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); - general.add(generalAccount); - general.add(supersaver); - - customerAB.aAll = all; - customerAB.bGeneral = general; - - Constructor constructor = new Constructor(); - Representer representer = new Representer(); - Tag generalAccountTag = new Tag("!GA"); - constructor - .addTypeDescription(new TypeDescription(GeneralAccount.class, generalAccountTag)); - representer.addClassTag(GeneralAccount.class, generalAccountTag); - - Yaml yaml = new Yaml(constructor, representer); - String dump = yaml.dump(customerAB); - // System.out.println(dump); - CustomerAB parsed = (CustomerAB) yaml.load(dump); - assertNotNull(parsed); - } - - public void testABProperty() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB_Property customerAB_property = new CustomerAB_Property(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); - general.add(generalAccount); - general.add(supersaver); - - customerAB_property.acc = generalAccount; - customerAB_property.bGeneral = general; - - Constructor constructor = new Constructor(); - Representer representer = new Representer(); - - Yaml yaml = new Yaml(constructor, representer); - String dump = yaml.dump(customerAB_property); - // System.out.println(dump); - CustomerAB_Property parsed = (CustomerAB_Property) yaml.load(dump); - assertNotNull(parsed); - } + public static class CustomerAB_MapKey { - public void testABPropertyWithCustomTag() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB_Property customerAB_property = new CustomerAB_Property(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); - general.add(generalAccount); - general.add(supersaver); - - customerAB_property.acc = generalAccount; - customerAB_property.bGeneral = general; - - Constructor constructor = new Constructor(); - Representer representer = new Representer(); - - Tag generalAccountTag = new Tag("!GA"); - constructor - .addTypeDescription(new TypeDescription(GeneralAccount.class, generalAccountTag)); - representer.addClassTag(GeneralAccount.class, generalAccountTag); - - Yaml yaml = new Yaml(constructor, representer); - String dump = yaml.dump(customerAB_property); - // System.out.println(dump); - CustomerAB_Property parsed = (CustomerAB_Property) yaml.load(dump); - assertNotNull(parsed); - } + public Collection<Account> aAll; + public Map<GeneralAccount, String> bGeneralMap; - public void testABwithJavaBeanHelpers() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB customerAB = new CustomerAB(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); - general.add(generalAccount); - general.add(supersaver); - - customerAB.aAll = all; - customerAB.bGeneral = general; - - Yaml yaml = new Yaml(); - String dump2 = yaml.dumpAsMap(customerAB); - // System.out.println(dump2); - Yaml loader = new Yaml(); - CustomerAB parsed = loader.loadAs(dump2, CustomerAB.class); - assertNotNull(parsed); + @Override + public String toString() { + return "CustomerAB_MapKey"; } + } - public void testAB_asMapValue() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB_MapValue customerAB_mapValue = new CustomerAB_MapValue(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - Map<String, GeneralAccount> generalMap = new HashMap<String, GeneralAccount>(); - generalMap.put(generalAccount.name, generalAccount); - generalMap.put(supersaver.name, supersaver); - - customerAB_mapValue.aAll = all; - customerAB_mapValue.bGeneralMap = generalMap; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(customerAB_mapValue); - // System.out.println(dump); - CustomerAB_MapValue parsed = (CustomerAB_MapValue) yaml.load(dump); - assertNotNull(parsed); - } + public static class CustomerAB_Property { - public void testAB_asMapKey() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerAB_MapKey customerAB_mapKey = new CustomerAB_MapKey(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - Map<GeneralAccount, String> generalMap = new HashMap<GeneralAccount, String>(); - generalMap.put(generalAccount, generalAccount.name); - generalMap.put(supersaver, supersaver.name); - - customerAB_mapKey.aAll = all; - customerAB_mapKey.bGeneralMap = generalMap; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(customerAB_mapKey); - // System.out.println(dump); - CustomerAB_MapKey parsed = (CustomerAB_MapKey) yaml.load(dump); - assertNotNull(parsed); - } + public Account acc; + public Collection<GeneralAccount> bGeneral; - public void testBA() { - SuperSaverAccount supersaver = new SuperSaverAccount(); - GeneralAccount generalAccount = new GeneralAccount(); - - CustomerBA customerBA = new CustomerBA(); - ArrayList<Account> all = new ArrayList<Account>(); - all.add(supersaver); - all.add(generalAccount); - ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); - general.add(generalAccount); - general.add(supersaver); - - customerBA.aGeneral = general; - customerBA.bAll = all; - - Yaml yaml = new Yaml(); - String dump = yaml.dump(customerBA); - // System.out.println(dump); - // - CustomerBA parsed = (CustomerBA) yaml.load(dump); - assertEquals(2, parsed.bAll.size()); - assertEquals(2, parsed.aGeneral.size()); - assertFalse(parsed.bAll.equals(parsed.aGeneral)); - GeneralAccount[] array = parsed.aGeneral.toArray(new GeneralAccount[2]); - assertEquals(GeneralAccount.class, array[0].getClass()); - assertEquals(SuperSaverAccount.class, array[1].getClass()); - assertEquals("SuperSaver", array[1].name); + @Override + public String toString() { + return "CustomerAB_Property"; } + } + + public void testAB() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB customerAB = new CustomerAB(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); + general.add(generalAccount); + general.add(supersaver); + + customerAB.aAll = all; + customerAB.bGeneral = general; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(customerAB); + // System.out.println(dump); + CustomerAB parsed = yaml.load(dump); + assertNotNull(parsed); + } + + public void testAB_Set() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB customerAB = new CustomerAB(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + Set<GeneralAccount> general = new HashSet<GeneralAccount>(); + general.add(generalAccount); + general.add(supersaver); + + customerAB.aAll = all; + customerAB.bGeneral = general; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(customerAB); + // System.out.println(dump); + CustomerAB parsed = yaml.load(dump); + assertNotNull(parsed); + } + + public void testABWithCustomTag() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB customerAB = new CustomerAB(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); + general.add(generalAccount); + general.add(supersaver); + + customerAB.aAll = all; + customerAB.bGeneral = general; + + Constructor constructor = new Constructor(); + Representer representer = new Representer(); + Tag generalAccountTag = new Tag("!GA"); + constructor.addTypeDescription(new TypeDescription(GeneralAccount.class, generalAccountTag)); + representer.addClassTag(GeneralAccount.class, generalAccountTag); + + Yaml yaml = new Yaml(constructor, representer); + String dump = yaml.dump(customerAB); + // System.out.println(dump); + CustomerAB parsed = yaml.load(dump); + assertNotNull(parsed); + } + + public void testABProperty() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB_Property customerAB_property = new CustomerAB_Property(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); + general.add(generalAccount); + general.add(supersaver); + + customerAB_property.acc = generalAccount; + customerAB_property.bGeneral = general; + + Constructor constructor = new Constructor(); + Representer representer = new Representer(); + + Yaml yaml = new Yaml(constructor, representer); + String dump = yaml.dump(customerAB_property); + // System.out.println(dump); + CustomerAB_Property parsed = yaml.load(dump); + assertNotNull(parsed); + } + + public void testABPropertyWithCustomTag() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB_Property customerAB_property = new CustomerAB_Property(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); + general.add(generalAccount); + general.add(supersaver); + + customerAB_property.acc = generalAccount; + customerAB_property.bGeneral = general; + + Constructor constructor = new Constructor(); + Representer representer = new Representer(); + + Tag generalAccountTag = new Tag("!GA"); + constructor.addTypeDescription(new TypeDescription(GeneralAccount.class, generalAccountTag)); + representer.addClassTag(GeneralAccount.class, generalAccountTag); + + Yaml yaml = new Yaml(constructor, representer); + String dump = yaml.dump(customerAB_property); + // System.out.println(dump); + CustomerAB_Property parsed = yaml.load(dump); + assertNotNull(parsed); + } + + public void testABwithJavaBeanHelpers() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB customerAB = new CustomerAB(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); + general.add(generalAccount); + general.add(supersaver); + + customerAB.aAll = all; + customerAB.bGeneral = general; + + Yaml yaml = new Yaml(); + String dump2 = yaml.dumpAsMap(customerAB); + // System.out.println(dump2); + Yaml loader = new Yaml(); + CustomerAB parsed = loader.loadAs(dump2, CustomerAB.class); + assertNotNull(parsed); + } + + public void testAB_asMapValue() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB_MapValue customerAB_mapValue = new CustomerAB_MapValue(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + Map<String, GeneralAccount> generalMap = new HashMap<String, GeneralAccount>(); + generalMap.put(generalAccount.name, generalAccount); + generalMap.put(supersaver.name, supersaver); + + customerAB_mapValue.aAll = all; + customerAB_mapValue.bGeneralMap = generalMap; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(customerAB_mapValue); + // System.out.println(dump); + CustomerAB_MapValue parsed = yaml.load(dump); + assertNotNull(parsed); + } + + public void testAB_asMapKey() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerAB_MapKey customerAB_mapKey = new CustomerAB_MapKey(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + Map<GeneralAccount, String> generalMap = new HashMap<GeneralAccount, String>(); + generalMap.put(generalAccount, generalAccount.name); + generalMap.put(supersaver, supersaver.name); + + customerAB_mapKey.aAll = all; + customerAB_mapKey.bGeneralMap = generalMap; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(customerAB_mapKey); + // System.out.println(dump); + CustomerAB_MapKey parsed = yaml.load(dump); + assertNotNull(parsed); + } + + public void testBA() { + SuperSaverAccount supersaver = new SuperSaverAccount(); + GeneralAccount generalAccount = new GeneralAccount(); + + CustomerBA customerBA = new CustomerBA(); + ArrayList<Account> all = new ArrayList<Account>(); + all.add(supersaver); + all.add(generalAccount); + ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>(); + general.add(generalAccount); + general.add(supersaver); + + customerBA.aGeneral = general; + customerBA.bAll = all; + + Yaml yaml = new Yaml(); + String dump = yaml.dump(customerBA); + // System.out.println(dump); + // + CustomerBA parsed = yaml.load(dump); + assertEquals(2, parsed.bAll.size()); + assertEquals(2, parsed.aGeneral.size()); + assertNotEquals(parsed.bAll, parsed.aGeneral); + GeneralAccount[] array = parsed.aGeneral.toArray(new GeneralAccount[2]); + assertEquals(GeneralAccount.class, array[0].getClass()); + assertEquals(SuperSaverAccount.class, array[1].getClass()); + assertEquals("SuperSaver", array[1].name); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue94/ChangeRuntimeClassTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue94/ChangeRuntimeClassTest.java index b9823a01..27a04d5a 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue94/ChangeRuntimeClassTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue94/ChangeRuntimeClassTest.java @@ -1,23 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue94; import static org.junit.Assert.assertEquals; import org.junit.Test; +import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Construct; @@ -26,71 +25,104 @@ import org.yaml.snakeyaml.nodes.Node; public class ChangeRuntimeClassTest { - @Test - public void testWithGlobalTag() { - String yamlText = "!!org.yaml.snakeyaml.issues.issue94.Entity\n" + "name: Matt\n" - + "nickName: Java\n"; + @Test + public void testWithGlobalTag() { + String yamlText = + "!!org.yaml.snakeyaml.issues.issue94.Entity\n" + "name: Matt\n" + "nickName: Java\n"; - // Now here that I would like to somehow intercept the constructor of - // SnakeYaml and give it - // an fresh instance of EntityLoadingProxy(); based on today's - // temperature, so to speak... - // that is un-preditable statically which proxy I will give it. + // Now here that I would like to somehow intercept the constructor of + // SnakeYaml and give it + // an fresh instance of EntityLoadingProxy(); based on today's + // temperature, so to speak... + // that is un-preditable statically which proxy I will give it. - Yaml yaml = new Yaml(new MyConstructor()); + Yaml yaml = new Yaml(new MyConstructor()); - Entity loadedEntity = null; - loadedEntity = (Entity) yaml.load(yamlText); + Entity loadedEntity = null; + loadedEntity = yaml.load(yamlText); - assertEquals("Matt", loadedEntity.getName()); + assertEquals("Matt", loadedEntity.getName()); - // The expectation below is from having intercepted setNickName() with - // the artifical subclass and - // performed the calculation. - assertEquals("JJ-Java", loadedEntity.getNickName()); - assertEquals(EntityLoadingProxy.class, loadedEntity.getClass()); + // The expectation below is from having intercepted setNickName() with + // the artifical subclass and + // performed the calculation. + assertEquals("JJ-Java", loadedEntity.getNickName()); + assertEquals(EntityLoadingProxy.class, loadedEntity.getClass()); + } + + @Test + public void testWithGlobalTagUsingTypeDescription() { + String yamlText = + "!!org.yaml.snakeyaml.issues.issue94.Entity\n" + "name: Matt\n" + "nickName: Java\n"; + + Yaml yaml = new Yaml(); + yaml.addTypeDescription(new TypeDescription(Entity.class, EntityLoadingProxy.class)); + + Entity loadedEntity = null; + loadedEntity = yaml.load(yamlText); + + assertEquals("Matt", loadedEntity.getName()); + + // The expectation below is from having intercepted setNickName() with + // the artifical subclass and + // performed the calculation. + assertEquals("JJ-Java", loadedEntity.getNickName()); + assertEquals(EntityLoadingProxy.class, loadedEntity.getClass()); + } + + @Test + public void testNoTag() { + String yamlText = "name: Matt\n" + "nickName: Java\n"; + Yaml yaml = new Yaml(new MyConstructor(Entity.class)); + Entity loadedEntity = null; + loadedEntity = yaml.load(yamlText); + assertEquals("Matt", loadedEntity.getName()); + assertEquals("JJ-Java", loadedEntity.getNickName()); + } + + @Test + public void testNoTagWithTypeDescription() { + String yamlText = "name: Matt\n" + "nickName: Java\n"; + Yaml yaml = new Yaml(); + yaml.addTypeDescription(new TypeDescription(Entity.class, EntityLoadingProxy.class)); + Entity loadedEntity = null; + loadedEntity = yaml.loadAs(yamlText, Entity.class); + assertEquals("Matt", loadedEntity.getName()); + assertEquals("JJ-Java", loadedEntity.getNickName()); + } + + /** + * @see Constructor.ConstructYamlObject + */ + private class MyConstructor extends Constructor { + + public MyConstructor() { + super(); + this.yamlConstructors.put(null, new ConstructProxy()); } - @Test - public void testNoTag() { - String yamlText = "name: Matt\n" + "nickName: Java\n"; - Yaml yaml = new Yaml(new MyConstructor(Entity.class)); - Entity loadedEntity = null; - loadedEntity = (Entity) yaml.load(yamlText); - assertEquals("Matt", loadedEntity.getName()); - assertEquals("JJ-Java", loadedEntity.getNickName()); + public MyConstructor(Class<?> clazz) { + super(clazz); + this.yamlConstructors.put(null, new ConstructProxy()); } - /** - * @see Constructor.ConstructYamlObject - */ - private class MyConstructor extends Constructor { - public MyConstructor() { - super(); - this.yamlConstructors.put(null, new ConstructProxy()); - } + private class ConstructProxy extends AbstractConstruct { - public MyConstructor(Class<?> clazz) { - super(clazz); - this.yamlConstructors.put(null, new ConstructProxy()); + private Construct getConstructor(Node node) { + Class<?> cl = getClassForNode(node); + if (cl.equals(Entity.class)) { + // today's temperature is high :) + cl = EntityLoadingProxy.class; } + node.setType(cl); + // call the constructor as if the runtime class is defined + Construct constructor = yamlClassConstructors.get(node.getNodeId()); + return constructor; + } - private class ConstructProxy extends AbstractConstruct { - private Construct getConstructor(Node node) { - Class<?> cl = getClassForNode(node); - if (cl.equals(Entity.class) && true) { - // today's temperature is high :) - cl = EntityLoadingProxy.class; - } - node.setType(cl); - // call the constructor as if the runtime class is defined - Construct constructor = yamlClassConstructors.get(node.getNodeId()); - return constructor; - } - - public Object construct(Node node) { - return getConstructor(node).construct(node); - } - } + public Object construct(Node node) { + return getConstructor(node).construct(node); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue94/Entity.java b/src/test/java/org/yaml/snakeyaml/issues/issue94/Entity.java index eb3f7ebb..63562c08 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue94/Entity.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue94/Entity.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue94; public class Entity { - private String name; - private String nickName; - public String getName() { - return name; - } + private String name; + private String nickName; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getNickName() { - return nickName; - } + public void setName(String name) { + this.name = name; + } - public void setNickName(String nickName) { - this.nickName = nickName; - } + public String getNickName() { + return nickName; + } + + public void setNickName(String nickName) { + this.nickName = nickName; + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue94/EntityLoadingProxy.java b/src/test/java/org/yaml/snakeyaml/issues/issue94/EntityLoadingProxy.java index e8129a1e..e5d2571b 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue94/EntityLoadingProxy.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue94/EntityLoadingProxy.java @@ -1,26 +1,25 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue94; public class EntityLoadingProxy extends Entity { - @Override - public void setNickName(String nickName) { - if (nickName.startsWith("J")) - nickName = "JJ-" + nickName; - super.setNickName(nickName); + @Override + public void setNickName(String nickName) { + if (nickName.startsWith("J")) { + nickName = "JJ-" + nickName; } + super.setNickName(nickName); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue95/ArrayInGenericCollectionTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue95/ArrayInGenericCollectionTest.java index b454953a..6415e708 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue95/ArrayInGenericCollectionTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue95/ArrayInGenericCollectionTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue95; @@ -21,9 +19,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import junit.framework.TestCase; - import org.junit.Assert; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.TypeDescription; @@ -34,119 +30,121 @@ import org.yaml.snakeyaml.nodes.Tag; public class ArrayInGenericCollectionTest extends TestCase { - public static class A { - private Map<String, String[]> meta = new HashMap<String, String[]>(); - } - - public static class B { - private List<String[]> meta = new ArrayList<String[]>(); - } - - private A createA() { - A a = new A(); - a.meta.put("met1", new String[] { "whatever" }); - a.meta.put("met2", new String[] { "something", "something else" }); - return a; - } - - private B createB() { - B b = new B(); - b.meta.add(new String[] { "whatever" }); - b.meta.add(new String[] { "something", "something else" }); - return b; - } - - public void testArrayAsMapValue() { - Yaml yaml2dump = new Yaml(); - yaml2dump.setBeanAccess(BeanAccess.FIELD); - A data = createA(); - String dump = yaml2dump.dump(data); - // System.out.println(dump); - - Yaml yaml2load = new Yaml(); - yaml2load.setBeanAccess(BeanAccess.FIELD); - A loaded = (A) yaml2load.load(dump); - - assertEquals(data.meta.size(), loaded.meta.size()); - Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet(); - for (Entry<String, String[]> entry : loadedMeta) { - assertTrue(data.meta.containsKey(entry.getKey())); - Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue()); - } - } - - public void testArrayAsMapValueWithTypeDespriptor() { - Yaml yaml2dump = new Yaml(); - yaml2dump.setBeanAccess(BeanAccess.FIELD); - A data = createA(); - String dump = yaml2dump.dump(data); - // System.out.println(dump); - - TypeDescription aTypeDescr = new TypeDescription(A.class); - aTypeDescr.putMapPropertyType("meta", String.class, String[].class); - - Constructor c = new Constructor(); - c.addTypeDescription(aTypeDescr); - Yaml yaml2load = new Yaml(c); - yaml2load.setBeanAccess(BeanAccess.FIELD); - - A loaded = (A) yaml2load.load(dump); - - assertEquals(data.meta.size(), loaded.meta.size()); - Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet(); - for (Entry<String, String[]> entry : loadedMeta) { - assertTrue(data.meta.containsKey(entry.getKey())); - Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue()); - } + public static class A { + + private final Map<String, String[]> meta = new HashMap<String, String[]>(); + } + + public static class B { + + private final List<String[]> meta = new ArrayList<String[]>(); + } + + private A createA() { + A a = new A(); + a.meta.put("met1", new String[] {"whatever"}); + a.meta.put("met2", new String[] {"something", "something else"}); + return a; + } + + private B createB() { + B b = new B(); + b.meta.add(new String[] {"whatever"}); + b.meta.add(new String[] {"something", "something else"}); + return b; + } + + public void testArrayAsMapValue() { + Yaml yaml2dump = new Yaml(); + yaml2dump.setBeanAccess(BeanAccess.FIELD); + A data = createA(); + String dump = yaml2dump.dump(data); + // System.out.println(dump); + + Yaml yaml2load = new Yaml(); + yaml2load.setBeanAccess(BeanAccess.FIELD); + A loaded = yaml2load.load(dump); + + assertEquals(data.meta.size(), loaded.meta.size()); + Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet(); + for (Entry<String, String[]> entry : loadedMeta) { + assertTrue(data.meta.containsKey(entry.getKey())); + Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue()); } - - public void testArrayAsListValue() { - Yaml yaml2dump = new Yaml(); - yaml2dump.setBeanAccess(BeanAccess.FIELD); - B data = createB(); - String dump = yaml2dump.dump(data); - // System.out.println(dump); - - Yaml yaml2load = new Yaml(); - yaml2load.setBeanAccess(BeanAccess.FIELD); - B loaded = (B) yaml2load.load(dump); - - Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray()); - } - - public void testArrayAsListValueWithTypeDespriptor() { - Yaml yaml2dump = new Yaml(); - yaml2dump.setBeanAccess(BeanAccess.FIELD); - B data = createB(); - String dump = yaml2dump.dump(data); - // System.out.println(dump); - - TypeDescription aTypeDescr = new TypeDescription(B.class); - aTypeDescr.putListPropertyType("meta", String[].class); - - Constructor c = new Constructor(); - c.addTypeDescription(aTypeDescr); - Yaml yaml2load = new Yaml(c); - yaml2load.setBeanAccess(BeanAccess.FIELD); - - B loaded = (B) yaml2load.load(dump); - - Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray()); - } - - public void testNoTags() { - Yaml yaml2dump = new Yaml(); - yaml2dump.setBeanAccess(BeanAccess.FIELD); - B data = createB(); - String dump = yaml2dump.dumpAs(data, Tag.MAP, FlowStyle.AUTO); - // System.out.println(dump); - assertEquals("meta:\n- [whatever]\n- [something, something else]\n", dump); - // - Constructor constr = new Constructor(B.class); - Yaml yaml2load = new Yaml(constr); - yaml2load.setBeanAccess(BeanAccess.FIELD); - B loaded = (B) yaml2load.load(dump); - - Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray()); + } + + public void testArrayAsMapValueWithTypeDespriptor() { + Yaml yaml2dump = new Yaml(); + yaml2dump.setBeanAccess(BeanAccess.FIELD); + A data = createA(); + String dump = yaml2dump.dump(data); + // System.out.println(dump); + + TypeDescription aTypeDescr = new TypeDescription(A.class); + aTypeDescr.putMapPropertyType("meta", String.class, String[].class); + + Constructor c = new Constructor(); + c.addTypeDescription(aTypeDescr); + Yaml yaml2load = new Yaml(c); + yaml2load.setBeanAccess(BeanAccess.FIELD); + + A loaded = yaml2load.load(dump); + + assertEquals(data.meta.size(), loaded.meta.size()); + Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet(); + for (Entry<String, String[]> entry : loadedMeta) { + assertTrue(data.meta.containsKey(entry.getKey())); + Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue()); } + } + + public void testArrayAsListValue() { + Yaml yaml2dump = new Yaml(); + yaml2dump.setBeanAccess(BeanAccess.FIELD); + B data = createB(); + String dump = yaml2dump.dump(data); + // System.out.println(dump); + + Yaml yaml2load = new Yaml(); + yaml2load.setBeanAccess(BeanAccess.FIELD); + B loaded = yaml2load.load(dump); + + Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray()); + } + + public void testArrayAsListValueWithTypeDespriptor() { + Yaml yaml2dump = new Yaml(); + yaml2dump.setBeanAccess(BeanAccess.FIELD); + B data = createB(); + String dump = yaml2dump.dump(data); + // System.out.println(dump); + + TypeDescription aTypeDescr = new TypeDescription(B.class); + aTypeDescr.putListPropertyType("meta", String[].class); + + Constructor c = new Constructor(); + c.addTypeDescription(aTypeDescr); + Yaml yaml2load = new Yaml(c); + yaml2load.setBeanAccess(BeanAccess.FIELD); + + B loaded = yaml2load.load(dump); + + Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray()); + } + + public void testNoTags() { + Yaml yaml2dump = new Yaml(); + yaml2dump.setBeanAccess(BeanAccess.FIELD); + B data = createB(); + String dump = yaml2dump.dumpAs(data, Tag.MAP, FlowStyle.AUTO); + // System.out.println(dump); + assertEquals("meta:\n- [whatever]\n- [something, something else]\n", dump); + // + Constructor constr = new Constructor(B.class); + Yaml yaml2load = new Yaml(constr); + yaml2load.setBeanAccess(BeanAccess.FIELD); + B loaded = yaml2load.load(dump); + + Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue97/Blog.java b/src/test/java/org/yaml/snakeyaml/issues/issue97/Blog.java index 8da4dc71..ddb4d7c7 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue97/Blog.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue97/Blog.java @@ -1,30 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue97; import java.util.SortedSet; public class Blog { - private SortedSet<Post> posts; - public void addPost(Post p) { - posts.add(p); - } + private SortedSet<Post> posts; - public SortedSet<Post> getPosts() { - return posts; - } -}
\ No newline at end of file + public void addPost(Post p) { + posts.add(p); + } + + public SortedSet<Post> getPosts() { + return posts; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue97/Post.java b/src/test/java/org/yaml/snakeyaml/issues/issue97/Post.java index 479055de..015f38c8 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue97/Post.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue97/Post.java @@ -1,34 +1,32 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue97; public class Post implements Comparable<Post> { - private String title; - private String text; + private String title; + private String text; - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public int compareTo(Post o) { - return title.compareTo(o.title); - } -}
\ No newline at end of file + public int compareTo(Post o) { + return title.compareTo(o.title); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue97/YamlSortedSetTest.java b/src/test/java/org/yaml/snakeyaml/issues/issue97/YamlSortedSetTest.java index 1b4d3a1d..d6175c56 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue97/YamlSortedSetTest.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue97/YamlSortedSetTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue97; @@ -19,9 +17,9 @@ import java.util.Collection; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; - import org.junit.Assert; import org.junit.Test; +import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.error.YAMLException; @@ -32,48 +30,101 @@ import org.yaml.snakeyaml.nodes.SequenceNode; public class YamlSortedSetTest { - @Test - public void testYaml() { - String serialized = "!!org.yaml.snakeyaml.issues.issue97.Blog\n" + "posts:\n" - + " - text: Dummy\n" + " title: Test\n" + " - text: Creative\n" - + " title: Highly\n"; - // System.out.println(serialized); - Yaml yaml2 = constructYamlParser(); - Blog rehydrated = (Blog) yaml2.load(serialized); - checkTestBlog(rehydrated); - } + @Test + public void testYaml() { + String serialized = + "!!org.yaml.snakeyaml.issues.issue97.Blog\n" + "posts:\n" + " - text: Dummy\n" + + " title: Test\n" + " - text: Creative\n" + " title: Highly\n"; + // System.out.println(serialized); + Yaml yaml2 = constructYamlParser(); + Blog rehydrated = yaml2.load(serialized); + checkTestBlog(rehydrated); + } - protected Yaml constructYamlParser() { - Yaml yaml = new Yaml(new SetContructor()); - yaml.setBeanAccess(BeanAccess.FIELD); - return yaml; - } + public void testYaml2() { + String serialized = + "!!org.yaml.snakeyaml.issues.issue97.Blog\n" + "posts:\n" + " - text: Dummy\n" + + " title: Test\n" + " - text: Creative\n" + " title: Highly\n"; + // System.out.println(serialized); + Yaml yaml2 = constructYamlParser2(); + Blog rehydrated = yaml2.load(serialized); + checkTestBlog(rehydrated); + } + + public void testYaml3() { + String serialized = + "!!org.yaml.snakeyaml.issues.issue97.Blog\n" + "posts:\n" + " - text: Dummy\n" + + " title: Test\n" + " - text: Creative\n" + " title: Highly\n"; + // System.out.println(serialized); + Yaml yaml3 = constructYamlParser3(); + Blog rehydrated = yaml3.loadAs(serialized, Blog.class); + checkTestBlog(rehydrated); + } + + public void testYamlDefault() { + String serialized = + "!!org.yaml.snakeyaml.issues.issue97.Blog\n" + "posts:\n" + " - text: Dummy\n" + + " title: Test\n" + " - text: Creative\n" + " title: Highly\n"; + // System.out.println(serialized); + Yaml yaml = new Yaml(); + yaml.setBeanAccess(BeanAccess.FIELD); + Blog rehydrated = yaml.loadAs(serialized, Blog.class); + checkTestBlog(rehydrated); + } + + protected Yaml constructYamlParser2() { + Yaml yaml = new Yaml(); + yaml.addTypeDescription(new TypeDescription(SortedSet.class) { + @Override + public Object newInstance(Node node) { + return new TreeSet<Object>(); + } + }); + yaml.setBeanAccess(BeanAccess.FIELD); + return yaml; + } - protected void checkTestBlog(Blog blog) { - Set<Post> posts = blog.getPosts(); - Assert.assertEquals("Blog contains 2 posts", 2, posts.size()); + protected Yaml constructYamlParser3() { + Yaml yaml = new Yaml(); + yaml.setBeanAccess(BeanAccess.FIELD); + yaml.addTypeDescription(new TypeDescription(SortedSet.class, TreeSet.class)); + return yaml; + } + + protected Yaml constructYamlParser() { + Yaml yaml = new Yaml(new SetContructor()); + yaml.setBeanAccess(BeanAccess.FIELD); + return yaml; + } + + protected void checkTestBlog(Blog blog) { + Set<Post> posts = blog.getPosts(); + Assert.assertTrue("posts should be SortedSet", (posts instanceof SortedSet)); + Assert.assertEquals("Blog contains 2 posts", 2, posts.size()); + } + + private class SetContructor extends Constructor { + + public SetContructor() { + yamlClassConstructors.put(NodeId.sequence, new ConstructSetFromSequence()); } - private class SetContructor extends Constructor { - public SetContructor() { - yamlClassConstructors.put(NodeId.sequence, new ConstructSetFromSequence()); - } + private class ConstructSetFromSequence extends ConstructSequence { - private class ConstructSetFromSequence extends ConstructSequence { - @Override - public Object construct(Node node) { - if (SortedSet.class.isAssignableFrom(node.getType())) { - if (node.isTwoStepsConstruction()) { - throw new YAMLException("Set cannot be recursive."); - } else { - Collection<Object> result = new TreeSet<Object>(); - SetContructor.this.constructSequenceStep2((SequenceNode) node, result); - return result; - } - } else { - return super.construct(node); - } - } + @Override + public Object construct(Node node) { + if (SortedSet.class.isAssignableFrom(node.getType())) { + if (node.isTwoStepsConstruction()) { + throw new YAMLException("Set cannot be recursive."); + } else { + Collection<Object> result = new TreeSet<Object>(); + SetContructor.this.constructSequenceStep2((SequenceNode) node, result); + return result; + } + } else { + return super.construct(node); } + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/issues/issue99/YamlBase64Test.java b/src/test/java/org/yaml/snakeyaml/issues/issue99/YamlBase64Test.java index 32e7eefd..c1a742d3 100644 --- a/src/test/java/org/yaml/snakeyaml/issues/issue99/YamlBase64Test.java +++ b/src/test/java/org/yaml/snakeyaml/issues/issue99/YamlBase64Test.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.issues.issue99; @@ -19,9 +17,7 @@ import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.YamlDocument; @@ -34,117 +30,113 @@ import org.yaml.snakeyaml.nodes.Tag; /** * Example for issue 99 - * - * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=99"></a> + * + * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=99">issue 99</a> */ public class YamlBase64Test extends TestCase { - /** - * test base64 decoding - */ - public void testBase64() throws IOException { - String text = Util.getLocalResource("issues/issue99-base64_literal.yaml"); - String[] lines = text.split("\n"); - String all = ""; - for (int i = 1; i < lines.length; i++) {// skip first line - all = all + lines[i].trim(); - } - // System.out.println(all); - byte[] decoded = Base64Coder.decode(all.toCharArray()); - assertEquals(3737, decoded.length); - checkBytes(decoded); + /** + * test base64 decoding + */ + public void testBase64() throws IOException { + String text = Util.getLocalResource("issues/issue99-base64_literal.yaml"); + String[] lines = text.split("\n"); + String all = ""; + for (int i = 1; i < lines.length; i++) {// skip first line + all = all + lines[i].trim(); } + // System.out.println(all); + byte[] decoded = Base64Coder.decode(all.toCharArray()); + assertEquals(3737, decoded.length); + checkBytes(decoded); + } - @SuppressWarnings("unchecked") - public void testYamlBase64Loading() throws IOException { - Yaml yaml = new Yaml(); - InputStream inputStream = YamlBase64Test.class - .getResourceAsStream("/issues/issue99-base64_double_quoted.yaml"); - Map<String, Object> bean = (Map<String, Object>) yaml.load(inputStream); - byte[] jpeg = (byte[]) bean.get("jpegPhoto"); - checkBytes(jpeg); - inputStream.close(); - } + @SuppressWarnings("unchecked") + public void testYamlBase64Loading() throws IOException { + Yaml yaml = new Yaml(); + InputStream inputStream = + YamlBase64Test.class.getResourceAsStream("/issues/issue99-base64_double_quoted.yaml"); + Map<String, Object> bean = yaml.load(inputStream); + byte[] jpeg = (byte[]) bean.get("jpegPhoto"); + checkBytes(jpeg); + inputStream.close(); + } - private void checkBytes(byte[] jpeg) throws IOException { - InputStream input; - input = YamlDocument.class.getClassLoader().getResourceAsStream("issues/issue99.jpeg"); - BufferedInputStream is = new BufferedInputStream(input); - int i = 0; - while (i < jpeg.length) { - int etalon = is.read(); - if (jpeg[i] < 0) { - assertEquals(etalon, jpeg[i] + 256); - } else { - assertEquals(etalon, jpeg[i]); - } - i++; - } - is.close(); + private void checkBytes(byte[] jpeg) throws IOException { + InputStream input; + input = YamlDocument.class.getClassLoader().getResourceAsStream("issues/issue99.jpeg"); + BufferedInputStream is = new BufferedInputStream(input); + int i = 0; + while (i < jpeg.length) { + int etalon = is.read(); + if (jpeg[i] < 0) { + assertEquals(etalon, jpeg[i] + 256); + } else { + assertEquals(etalon, jpeg[i]); + } + i++; } + is.close(); + } - /** - * In the literal scalar all the line breaks are significant - * - * @throws IOException - */ - public void testYamlBase64LoadingLiteral() throws IOException { - Yaml yaml = new Yaml(); - InputStream inputStream = YamlBase64Test.class - .getResourceAsStream("/issues/issue99-base64_literal.yaml"); - try { - yaml.load(inputStream); - fail("In the literal scalar all the line breaks are significant"); - } catch (Exception e) { - assertEquals("Length of Base64 encoded input string is not a multiple of 4.", - e.getMessage()); - } finally { - inputStream.close(); - } - } + /** + * In the literal scalar all the line breaks are significant + * + * @throws IOException + */ + public void testYamlBase64LoadingLiteral() throws IOException { + Yaml yaml = new Yaml(); + InputStream inputStream = + YamlBase64Test.class.getResourceAsStream("/issues/issue99-base64_literal.yaml"); + Map<String, Object> bean = yaml.load(inputStream); + byte[] jpeg = (byte[]) bean.get("jpegPhoto"); + checkBytes(jpeg); + inputStream.close(); + } - /** - * Redefine the !!binary global tag in a way that it ignores all the white - * spaces to be able to use literal scalar - */ - @SuppressWarnings("unchecked") - public void testRedefineBinaryTag() throws IOException { - Yaml yaml = new Yaml(new SpecialContructor(Tag.BINARY)); - InputStream inputStream = YamlBase64Test.class - .getResourceAsStream("/issues/issue99-base64_literal.yaml"); - Map<String, Object> bean = (Map<String, Object>) yaml.load(inputStream); - byte[] jpeg = (byte[]) bean.get("jpegPhoto"); - checkBytes(jpeg); - inputStream.close(); - } + /** + * Redefine the !!binary global tag in a way that it ignores all the white spaces to be able to + * use literal scalar + */ + @SuppressWarnings("unchecked") + public void testRedefineBinaryTag() throws IOException { + Yaml yaml = new Yaml(new SpecialContructor(Tag.BINARY)); + InputStream inputStream = + YamlBase64Test.class.getResourceAsStream("/issues/issue99-base64_literal.yaml"); + Map<String, Object> bean = yaml.load(inputStream); + byte[] jpeg = (byte[]) bean.get("jpegPhoto"); + checkBytes(jpeg); + inputStream.close(); + } - private class SpecialContructor extends Constructor { - public SpecialContructor(Tag tag) { - this.yamlConstructors.put(tag, new MyBinaryConstructor()); - } + private class SpecialContructor extends Constructor { - private class MyBinaryConstructor extends AbstractConstruct { - public Object construct(Node node) { - String contentWithNewLines = constructScalar((ScalarNode) node).toString(); - String noNewLines = contentWithNewLines.replaceAll("\\s", ""); - byte[] decoded = Base64Coder.decode(noNewLines.toCharArray()); - return decoded; - } - } + public SpecialContructor(Tag tag) { + this.yamlConstructors.put(tag, new MyBinaryConstructor()); } - /** - * Define a local tag to ignore all the white spaces to be able to use - * literal scalar - */ - @SuppressWarnings("unchecked") - public void testLocalBinaryTag() throws IOException { - Yaml yaml = new Yaml(new SpecialContructor(new Tag("!beautiful"))); - InputStream inputStream = YamlBase64Test.class - .getResourceAsStream("/issues/issue99-base64_literal_custom_tag.yaml"); - Map<String, Object> bean = (Map<String, Object>) yaml.load(inputStream); - byte[] jpeg = (byte[]) bean.get("jpegPhoto"); - checkBytes(jpeg); - inputStream.close(); + private class MyBinaryConstructor extends AbstractConstruct { + + public Object construct(Node node) { + String contentWithNewLines = constructScalar((ScalarNode) node); + String noNewLines = contentWithNewLines.replaceAll("\\s", ""); + byte[] decoded = Base64Coder.decode(noNewLines.toCharArray()); + return decoded; + } } + } + + /** + * Define a local tag to ignore all the white spaces to be able to use literal scalar + */ + @SuppressWarnings("unchecked") + public void testLocalBinaryTag() throws IOException { + Yaml yaml = new Yaml(new SpecialContructor(new Tag("!beautiful"))); + InputStream inputStream = + YamlBase64Test.class.getResourceAsStream("/issues/issue99-base64_literal_custom_tag.yaml"); + Map<String, Object> bean = yaml.load(inputStream); + byte[] jpeg = (byte[]) bean.get("jpegPhoto"); + checkBytes(jpeg); + inputStream.close(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/ConstructEmptyBeanTest.java b/src/test/java/org/yaml/snakeyaml/javabeans/ConstructEmptyBeanTest.java index 8dea2315..68306426 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/ConstructEmptyBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/ConstructEmptyBeanTest.java @@ -1,131 +1,127 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; import java.io.Serializable; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class ConstructEmptyBeanTest extends TestCase { - /** - * standard Yaml - */ - public void testEmptyBean() { - Yaml yaml = new Yaml(); - EmptyBean bean = (EmptyBean) yaml - .load("!!org.yaml.snakeyaml.javabeans.ConstructEmptyBeanTest$EmptyBean {}"); - assertNotNull(bean); - assertNull(bean.getFirstName()); - assertEquals(5, bean.getHatSize()); - } - /** - * global tag is correct (but ignored) - */ - public void testEmptyBean1() { - Yaml beanLoader = new Yaml(); - EmptyBean bean = beanLoader.loadAs( - "!!org.yaml.snakeyaml.javabeans.ConstructEmptyBeanTest$EmptyBean {}", - EmptyBean.class); - assertNotNull(bean); - assertNull(bean.getFirstName()); - assertEquals(5, bean.getHatSize()); + /** + * standard Yaml + */ + public void testEmptyBean() { + Yaml yaml = new Yaml(); + EmptyBean bean = + yaml.load("!!org.yaml.snakeyaml.javabeans.ConstructEmptyBeanTest$EmptyBean {}"); + assertNotNull(bean); + assertNull(bean.getFirstName()); + assertEquals(5, bean.getHatSize()); + } + + /** + * global tag is correct (but ignored) + */ + public void testEmptyBean1() { + Yaml beanLoader = new Yaml(); + EmptyBean bean = beanLoader.loadAs( + "!!org.yaml.snakeyaml.javabeans.ConstructEmptyBeanTest$EmptyBean {}", EmptyBean.class); + assertNotNull(bean); + assertNull(bean.getFirstName()); + assertEquals(5, bean.getHatSize()); + } + + /** + * global tag is ignored + */ + public void testEmptyBean2() { + Yaml beanLoader = new Yaml(); + EmptyBean bean = beanLoader.loadAs("!!Bla-bla-bla {}", EmptyBean.class); + assertNotNull(bean); + assertNull(bean.getFirstName()); + assertEquals(5, bean.getHatSize()); + } + + /** + * no tag + */ + public void testEmptyBean3() { + Yaml beanLoader = new Yaml(); + EmptyBean bean = beanLoader.loadAs("{ }", EmptyBean.class); + assertNotNull(bean); + assertNull(bean.getFirstName()); + assertEquals(5, bean.getHatSize()); + } + + /** + * empty document + */ + public void testEmptyBean4() { + Yaml beanLoader = new Yaml(); + EmptyBean bean = beanLoader.loadAs("", EmptyBean.class); + assertNull(bean); + } + + /** + * local tag is ignored + */ + public void testEmptyBean5() { + Yaml beanLoader = new Yaml(); + EmptyBean bean = beanLoader.loadAs("!Bla-bla-bla {}", EmptyBean.class); + assertNotNull(bean); + assertNull(bean.getFirstName()); + assertEquals(5, bean.getHatSize()); + } + + /** + * invalid document + */ + public void testEmptyBean6() { + Yaml beanLoader = new Yaml(); + try { + beanLoader.loadAs("{", EmptyBean.class); + fail("Invalid document provided."); + } catch (Exception e) { + assertEquals("while parsing a flow node\n" + " in 'string', line 1, column 2:\n" + " {\n" + + " ^\n" + "expected the node content, but found '<stream end>'\n" + + " in 'string', line 1, column 2:\n" + " {\n" + " ^\n", e.getMessage()); } + } - /** - * global tag is ignored - */ - public void testEmptyBean2() { - Yaml beanLoader = new Yaml(); - EmptyBean bean = beanLoader.loadAs("!!Bla-bla-bla {}", EmptyBean.class); - assertNotNull(bean); - assertNull(bean.getFirstName()); - assertEquals(5, bean.getHatSize()); - } + public static class EmptyBean implements Serializable { - /** - * no tag - */ - public void testEmptyBean3() { - Yaml beanLoader = new Yaml(); - EmptyBean bean = beanLoader.loadAs("{ }", EmptyBean.class); - assertNotNull(bean); - assertNull(bean.getFirstName()); - assertEquals(5, bean.getHatSize()); - } + private static final long serialVersionUID = -8001155967276657180L; + private String firstName; + private int hatSize = 5; - /** - * empty document - */ - public void testEmptyBean4() { - Yaml beanLoader = new Yaml(); - EmptyBean bean = beanLoader.loadAs("", EmptyBean.class); - assertNull(bean); - } + public EmptyBean() {} - /** - * local tag is ignored - */ - public void testEmptyBean5() { - Yaml beanLoader = new Yaml(); - EmptyBean bean = beanLoader.loadAs("!Bla-bla-bla {}", EmptyBean.class); - assertNotNull(bean); - assertNull(bean.getFirstName()); - assertEquals(5, bean.getHatSize()); + public String getFirstName() { + return firstName; } - /** - * invalid document - */ - public void testEmptyBean6() { - Yaml beanLoader = new Yaml(); - try { - beanLoader.loadAs("{", EmptyBean.class); - fail("Invalid document provided."); - } catch (Exception e) { - assertEquals("while parsing a flow node\n" + " in 'string', line 1, column 2:\n" - + " {\n" + " ^\n" + "expected the node content, but found StreamEnd\n" - + " in 'string', line 1, column 2:\n" + " {\n" + " ^\n", e.getMessage()); - } + public void setFirstName(String firstName) { + this.firstName = firstName; } - public static class EmptyBean implements Serializable { - private static final long serialVersionUID = -8001155967276657180L; - private String firstName; - private int hatSize = 5; - - public EmptyBean() { - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public int getHatSize() { - return hatSize; - } + public int getHatSize() { + return hatSize; + } - public void setHatSize(int hatSize) { - this.hatSize = hatSize; - } + public void setHatSize(int hatSize) { + this.hatSize = hatSize; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/Door.java b/src/test/java/org/yaml/snakeyaml/javabeans/Door.java index 7e3ad133..68b61ac0 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/Door.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/Door.java @@ -1,67 +1,66 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; public class Door { - private String id; - private int height; - public Door(String id, int height) { - this.id = id; - this.height = height; - } + private String id; + private int height; - public Door() { - this.height = 3; - } + public Door(String id, int height) { + this.id = id; + this.height = height; + } - public int getHeight() { - return height; - } + public Door() { + this.height = 3; + } - public void setHeight(int height) { - this.height = height; - } + public int getHeight() { + return height; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Door) { - Door door = (Door) obj; - return id.equals(door.id); - } else { - return false; - } - } + public void setHeight(int height) { + this.height = height; + } - @Override - public int hashCode() { - return id.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Door) { + Door door = (Door) obj; + return id.equals(door.id); + } else { + return false; } + } - public String getId() { - return id; - } + @Override + public int hashCode() { + return id.hashCode(); + } - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - @Override - public String toString() { - return "Door id=" + id; - } + public void setId(String id) { + this.id = id; + } + + @Override + public String toString() { + return "Door id=" + id; + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/FrontDoor.java b/src/test/java/org/yaml/snakeyaml/javabeans/FrontDoor.java index 2b958da7..0bf99b7b 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/FrontDoor.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/FrontDoor.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; public class FrontDoor extends Door { - private String keytype; - public FrontDoor() { - super(); - } + private String keytype; - public FrontDoor(String id, int height) { - super(id, height); - } + public FrontDoor() { + super(); + } - public String getKeytype() { - return keytype; - } + public FrontDoor(String id, int height) { + super(id, height); + } - public void setKeytype(String keytype) { - this.keytype = keytype; - } + public String getKeytype() { + return keytype; + } + + public void setKeytype(String keytype) { + this.keytype = keytype; + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/House.java b/src/test/java/org/yaml/snakeyaml/javabeans/House.java index 41ba335a..81190bde 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/House.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/House.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; @@ -19,50 +17,51 @@ import java.util.List; import java.util.Map; public class House { - private String street; - private int number; - private List<Room> rooms; - private FrontDoor frontDoor; - private Map<String, String> reminders; - public String getStreet() { - return street; - } + private String street; + private int number; + private List<Room> rooms; + private FrontDoor frontDoor; + private Map<String, String> reminders; - public void setStreet(String street) { - this.street = street; - } + public String getStreet() { + return street; + } - public int getNumber() { - return number; - } + public void setStreet(String street) { + this.street = street; + } - public void setNumber(int number) { - this.number = number; - } + public int getNumber() { + return number; + } - public List<Room> getRooms() { - return rooms; - } + public void setNumber(int number) { + this.number = number; + } - public void setRooms(List<Room> rooms) { - this.rooms = rooms; - } + public List<Room> getRooms() { + return rooms; + } - public FrontDoor getFrontDoor() { - return frontDoor; - } + public void setRooms(List<Room> rooms) { + this.rooms = rooms; + } - public void setFrontDoor(FrontDoor frontDoor) { - this.frontDoor = frontDoor; - } + public FrontDoor getFrontDoor() { + return frontDoor; + } - public Map<String, String> getReminders() { - return reminders; - } + public void setFrontDoor(FrontDoor frontDoor) { + this.frontDoor = frontDoor; + } - public void setReminders(Map<String, String> reminders) { - this.reminders = reminders; - } + public Map<String, String> getReminders() { + return reminders; + } + + public void setReminders(Map<String, String> reminders) { + this.reminders = reminders; + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/HouseTest.java b/src/test/java/org/yaml/snakeyaml/javabeans/HouseTest.java index 97c69338..367493c7 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/HouseTest.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/HouseTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; @@ -19,9 +17,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.TypeDescription; @@ -30,115 +26,116 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class HouseTest extends TestCase { - /** - * no root global tag - */ - public void testDump1() { - House house = new House(); - FrontDoor frontDoor = new FrontDoor("qaz1", 5); - frontDoor.setKeytype("qwerty123"); - house.setFrontDoor(frontDoor); - List<Room> rooms = new ArrayList<Room>(); - rooms.add(new Room("Hall")); - rooms.add(new Room("Kitchen")); - house.setRooms(rooms); - Map<String, String> reminders = new TreeMap<String, String>(); - reminders.put("today", "do nothig"); - reminders.put("tomorrow", "go shoping"); - house.setReminders(reminders); - house.setNumber(1); - house.setStreet("Wall Street"); - Yaml beanDumper = new Yaml(); - String yaml = beanDumper.dumpAsMap(house); - String etalon = Util.getLocalResource("javabeans/house-dump1.yaml"); - assertEquals(etalon, yaml); - // load - Yaml beanLoader = new Yaml(); - House loadedHouse = beanLoader.loadAs(yaml, House.class); - assertNotNull(loadedHouse); - assertEquals("Wall Street", loadedHouse.getStreet()); - // dump again - String yaml3 = beanDumper.dumpAsMap(loadedHouse); - assertEquals(yaml, yaml3); - } - /** - * with global root class tag (global tag should be avoided) - */ - public void testDump3() { - House house = new House(); - FrontDoor frontDoor = new FrontDoor("qaz1", 5); - frontDoor.setKeytype("qwerty123"); - house.setFrontDoor(frontDoor); - List<Room> rooms = new ArrayList<Room>(); - rooms.add(new Room("Hall")); - rooms.add(new Room("Kitchen")); - house.setRooms(rooms); - Map<String, String> reminders = new TreeMap<String, String>(); - reminders.put("today", "do nothig"); - reminders.put("tomorrow", "go shoping"); - house.setReminders(reminders); - house.setNumber(1); - house.setStreet("Wall Street"); - Yaml beanDumper = new Yaml(); - String yaml = beanDumper.dumpAsMap(house); - String etalon = Util.getLocalResource("javabeans/house-dump3.yaml"); - assertEquals(etalon, yaml); - // load - TypeDescription description = new TypeDescription(House.class); - description.putListPropertyType("rooms", Room.class); - Yaml beanLoader = new Yaml(new Constructor(description)); - House loadedHouse = (House) beanLoader.load(yaml); - House loadedHouse2 = (House) beanLoader.loadAs(yaml, House.class); - assertNotNull(loadedHouse); - assertFalse(loadedHouse == loadedHouse2); - assertEquals("Wall Street", loadedHouse.getStreet()); - assertEquals(1, loadedHouse.getNumber()); - assertEquals(1, loadedHouse2.getNumber()); - FrontDoor fdoor = loadedHouse.getFrontDoor(); - assertEquals(frontDoor.getId(), fdoor.getId()); - assertEquals(frontDoor.getHeight(), fdoor.getHeight()); - assertEquals(frontDoor.getKeytype(), fdoor.getKeytype()); - assertEquals(frontDoor, fdoor); - assertEquals(reminders, loadedHouse.getReminders()); - List<Room> loadedRooms = loadedHouse.getRooms(); - assertEquals(rooms, loadedRooms); - // dump again - String yaml3 = beanDumper.dumpAsMap(loadedHouse); - assertEquals(yaml, yaml3); - } + /** + * no root global tag + */ + public void testDump1() { + House house = new House(); + FrontDoor frontDoor = new FrontDoor("qaz1", 5); + frontDoor.setKeytype("qwerty123"); + house.setFrontDoor(frontDoor); + List<Room> rooms = new ArrayList<Room>(); + rooms.add(new Room("Hall")); + rooms.add(new Room("Kitchen")); + house.setRooms(rooms); + Map<String, String> reminders = new TreeMap<String, String>(); + reminders.put("today", "do nothig"); + reminders.put("tomorrow", "go shoping"); + house.setReminders(reminders); + house.setNumber(1); + house.setStreet("Wall Street"); + Yaml beanDumper = new Yaml(); + String yaml = beanDumper.dumpAsMap(house); + String etalon = Util.getLocalResource("javabeans/house-dump1.yaml"); + assertEquals(etalon, yaml); + // load + Yaml beanLoader = new Yaml(); + House loadedHouse = beanLoader.loadAs(yaml, House.class); + assertNotNull(loadedHouse); + assertEquals("Wall Street", loadedHouse.getStreet()); + // dump again + String yaml3 = beanDumper.dumpAsMap(loadedHouse); + assertEquals(yaml, yaml3); + } + + /** + * with global root class tag (global tag should be avoided) + */ + public void testDump3() { + House house = new House(); + FrontDoor frontDoor = new FrontDoor("qaz1", 5); + frontDoor.setKeytype("qwerty123"); + house.setFrontDoor(frontDoor); + List<Room> rooms = new ArrayList<Room>(); + rooms.add(new Room("Hall")); + rooms.add(new Room("Kitchen")); + house.setRooms(rooms); + Map<String, String> reminders = new TreeMap<String, String>(); + reminders.put("today", "do nothig"); + reminders.put("tomorrow", "go shoping"); + house.setReminders(reminders); + house.setNumber(1); + house.setStreet("Wall Street"); + Yaml beanDumper = new Yaml(); + String yaml = beanDumper.dumpAsMap(house); + String etalon = Util.getLocalResource("javabeans/house-dump3.yaml"); + assertEquals(etalon, yaml); + // load + TypeDescription description = new TypeDescription(House.class); + description.putListPropertyType("rooms", Room.class); + Yaml beanLoader = new Yaml(new Constructor(description)); + House loadedHouse = beanLoader.load(yaml); + House loadedHouse2 = beanLoader.loadAs(yaml, House.class); + assertNotNull(loadedHouse); + assertNotSame(loadedHouse, loadedHouse2); + assertEquals("Wall Street", loadedHouse.getStreet()); + assertEquals(1, loadedHouse.getNumber()); + assertEquals(1, loadedHouse2.getNumber()); + FrontDoor fdoor = loadedHouse.getFrontDoor(); + assertEquals(frontDoor.getId(), fdoor.getId()); + assertEquals(frontDoor.getHeight(), fdoor.getHeight()); + assertEquals(frontDoor.getKeytype(), fdoor.getKeytype()); + assertEquals(frontDoor, fdoor); + assertEquals(reminders, loadedHouse.getReminders()); + List<Room> loadedRooms = loadedHouse.getRooms(); + assertEquals(rooms, loadedRooms); + // dump again + String yaml3 = beanDumper.dumpAsMap(loadedHouse); + assertEquals(yaml, yaml3); + } - /** - * with global root class tag (global tag should be avoided) - */ - public void testDump2() { - House house = new House(); - FrontDoor frontDoor = new FrontDoor("qaz1", 5); - frontDoor.setKeytype("qwerty123"); - house.setFrontDoor(frontDoor); - List<Room> rooms = new ArrayList<Room>(); - rooms.add(new Room("Hall")); - rooms.add(new Room("Kitchen")); - house.setRooms(rooms); - Map<String, String> reminders = new TreeMap<String, String>(); - reminders.put("today", "do nothig"); - reminders.put("tomorrow", "go shoping"); - house.setReminders(reminders); - house.setNumber(1); - house.setStreet("Wall Street"); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml beanDumper = new Yaml(options); - String yaml = beanDumper.dump(house); - String etalon = Util.getLocalResource("javabeans/house-dump2.yaml"); - assertEquals(etalon, yaml); - // load - Yaml beanLoader = new Yaml(); - House loadedHouse = beanLoader.loadAs(yaml, House.class); - assertNotNull(loadedHouse); - assertEquals("Wall Street", loadedHouse.getStreet()); - // dump again - String yaml3 = beanDumper.dump(loadedHouse); - assertEquals(yaml, yaml3); - } + /** + * with global root class tag (global tag should be avoided) + */ + public void testDump2() { + House house = new House(); + FrontDoor frontDoor = new FrontDoor("qaz1", 5); + frontDoor.setKeytype("qwerty123"); + house.setFrontDoor(frontDoor); + List<Room> rooms = new ArrayList<Room>(); + rooms.add(new Room("Hall")); + rooms.add(new Room("Kitchen")); + house.setRooms(rooms); + Map<String, String> reminders = new TreeMap<String, String>(); + reminders.put("today", "do nothig"); + reminders.put("tomorrow", "go shoping"); + house.setReminders(reminders); + house.setNumber(1); + house.setStreet("Wall Street"); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml beanDumper = new Yaml(options); + String yaml = beanDumper.dump(house); + String etalon = Util.getLocalResource("javabeans/house-dump2.yaml"); + assertEquals(etalon, yaml); + // load + Yaml beanLoader = new Yaml(); + House loadedHouse = beanLoader.loadAs(yaml, House.class); + assertNotNull(loadedHouse); + assertEquals("Wall Street", loadedHouse.getStreet()); + // dump again + String yaml3 = beanDumper.dump(loadedHouse); + assertEquals(yaml, yaml3); + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/LongTest.java b/src/test/java/org/yaml/snakeyaml/javabeans/LongTest.java index 7b7deaf3..16d2cc84 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/LongTest.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/LongTest.java @@ -1,73 +1,72 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; public class LongTest extends TestCase { - public void testLongFail() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - Yaml yaml = new Yaml(options); - Foo foo = new Foo(); - String output = yaml.dump(foo); - // System.out.println(output); - try { - yaml.load(output); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("argument type mismatch")); - } + + public void testLongFail() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + Yaml yaml = new Yaml(options); + Foo foo = new Foo(); + String output = yaml.dump(foo); + // System.out.println(output); + try { + yaml.load(output); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("argument type mismatch")); } + } - public static class Foo { - private Long bar = Long.valueOf(42L); + public static class Foo { - public Long getBar() { - return bar; - } + private Long bar = Long.valueOf(42L); - public void setBar(Long bar) { - this.bar = bar; - } + public Long getBar() { + return bar; } - public void testLongRepresenter() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - Representer repr = new Representer(); - repr.addClassTag(Long.class, new Tag("!!java.lang.Long")); - Yaml yaml = new Yaml(repr, options); - - Foo foo = new Foo(); - String output = yaml.dump(foo); - // System.out.println(output); - Foo foo2 = (Foo) yaml.load(output); - assertEquals(new Long(42L), foo2.getBar()); + public void setBar(Long bar) { + this.bar = bar; } + } - public void testLongConstructor() { - String doc = "!!org.yaml.snakeyaml.javabeans.LongTest$Foo\n\"bar\": !!int \"42\""; - // System.out.println(doc); - Yaml yaml = new Yaml(); - Foo foo2 = (Foo) yaml.load(doc); - assertEquals(new Long(42L), foo2.getBar()); - } + public void testLongRepresenter() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + Representer repr = new Representer(); + repr.addClassTag(Long.class, new Tag("!!java.lang.Long")); + Yaml yaml = new Yaml(repr, options); + + Foo foo = new Foo(); + String output = yaml.dump(foo); + // System.out.println(output); + Foo foo2 = yaml.load(output); + assertEquals(Long.valueOf(42L), foo2.getBar()); + } + + public void testLongConstructor() { + String doc = "!!org.yaml.snakeyaml.javabeans.LongTest$Foo\n\"bar\": !!int \"42\""; + // System.out.println(doc); + Yaml yaml = new Yaml(); + Foo foo2 = yaml.load(doc); + assertEquals(Long.valueOf(42L), foo2.getBar()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/Room.java b/src/test/java/org/yaml/snakeyaml/javabeans/Room.java index 31e0ebde..4332d9a5 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/Room.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/Room.java @@ -1,57 +1,56 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; public class Room { - private String name; - public Room() { - this.name = "Bedroom"; - } + private String name; - public Room(String name) { - this.name = name; - } + public Room() { + this.name = "Bedroom"; + } - public String getName() { - return name; - } + public Room(String name) { + this.name = name; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof Room) { - Room room = (Room) obj; - return name.equals(room.name); - } else { - return false; - } - } + public void setName(String name) { + this.name = name; + } - @Override - public int hashCode() { - return name.hashCode(); + @Override + public boolean equals(Object obj) { + if (obj instanceof Room) { + Room room = (Room) obj; + return name.equals(room.name); + } else { + return false; } + } - @Override - public String toString() { - return "Room name=" + name; - } + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public String toString() { + return "Room name=" + name; + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/Shape.java b/src/test/java/org/yaml/snakeyaml/javabeans/Shape.java index ec086e48..29e7ad13 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/Shape.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/Shape.java @@ -1,21 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; public interface Shape { - public int process(); + int process(); } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/StringArrayTest.java b/src/test/java/org/yaml/snakeyaml/javabeans/StringArrayTest.java index 5a380491..4fcb1afb 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/StringArrayTest.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/StringArrayTest.java @@ -1,70 +1,69 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; -import java.util.Arrays; +import static org.junit.Assert.assertArrayEquals; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class StringArrayTest extends TestCase { - public void testStrings() { - A a = new A(); - a.setNames(new String[] { "aaa", "bbb", "ccc" }); - Yaml yaml = new Yaml(); - String output = yaml.dump(a); - assertEquals("!!org.yaml.snakeyaml.javabeans.StringArrayTest$A\nnames: [aaa, bbb, ccc]\n", - output); - A b = (A) yaml.load(output); - assertTrue(Arrays.equals(a.getNames(), b.getNames())); - } - public void testStringsPretty() { - A a = new A(); - a.setNames(new String[] { "aaa", "bbb", "ccc" }); - DumperOptions options = new DumperOptions(); - options.setPrettyFlow(true); - Yaml yaml = new Yaml(options); - String output = yaml.dump(a); - assertEquals( - "!!org.yaml.snakeyaml.javabeans.StringArrayTest$A\nnames: [\n aaa,\n bbb,\n ccc]\n", - output); - A b = (A) yaml.load(output); - assertTrue(Arrays.equals(a.getNames(), b.getNames())); - } + public void testStrings() { + A a = new A(); + a.setNames(new String[] {"aaa", "bbb", "ccc"}); + Yaml yaml = new Yaml(); + String output = yaml.dump(a); + assertEquals("!!org.yaml.snakeyaml.javabeans.StringArrayTest$A\nnames: [aaa, bbb, ccc]\n", + output); + A b = yaml.load(output); + assertArrayEquals(a.getNames(), b.getNames()); + } + + public void testStringsPretty() { + A a = new A(); + a.setNames(new String[] {"aaa", "bbb", "ccc"}); + DumperOptions options = new DumperOptions(); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String output = yaml.dump(a); + assertEquals( + "!!org.yaml.snakeyaml.javabeans.StringArrayTest$A\nnames: [\n aaa,\n bbb,\n ccc\n]\n", + output); + A b = yaml.load(output); + assertArrayEquals(a.getNames(), b.getNames()); + } - public static class A { - String[] names; + public static class A { - public String[] getNames() { - return names; - } + String[] names; - public void setNames(String[] names) { - this.names = names; - } + public String[] getNames() { + return names; + } + + public void setNames(String[] names) { + this.names = names; + } - public String getName(int index) { - return names[index]; - } + public String getName(int index) { + return names[index]; + } - public void setName(int index, String name) { - this.names[index] = name; - } + public void setName(int index, String name) { + this.names[index] = name; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/Triangle.java b/src/test/java/org/yaml/snakeyaml/javabeans/Triangle.java index 10acc6dc..6476dbc9 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/Triangle.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/Triangle.java @@ -1,32 +1,31 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; public class Triangle implements Shape { - private String name; - public String getName() { - return name; - } + private String name; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public int process() { - return 7; - } + public void setName(String name) { + this.name = name; + } + + public int process() { + return 7; + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBean.java b/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBean.java index 68930902..9f459047 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBean.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBean.java @@ -1,42 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; public class TriangleBean { - private String name; - private Shape shape; - public String getName() { - return name; - } + private String name; + private Shape shape; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public Shape getShape() { - return shape; - } + public void setName(String name) { + this.name = name; + } - public void setShape(Shape shape) { - this.shape = shape; - } + public Shape getShape() { + return shape; + } - @Override - public String toString() { - return "TriangleBean name=" + name; - } + public void setShape(Shape shape) { + this.shape = shape; + } + + @Override + public String toString() { + return "TriangleBean name=" + name; + } } diff --git a/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBeanTest.java b/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBeanTest.java index 8e84e753..a5448eb8 100644 --- a/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBeanTest.java +++ b/src/test/java/org/yaml/snakeyaml/javabeans/TriangleBeanTest.java @@ -1,69 +1,66 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.javabeans; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class TriangleBeanTest extends TestCase { - public void testGetTriangle() { - Triangle triangle = new Triangle(); - triangle.setName("Triangle25"); - TriangleBean bean = new TriangleBean(); - bean.setShape(triangle); - bean.setName("Bean25"); - Yaml beanDumper = new Yaml(); - String output = beanDumper.dumpAsMap(bean); - assertEquals( - "name: Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle\n name: Triangle25\n", - output); - Yaml beanLoader = new Yaml(); - TriangleBean loadedBean = beanLoader.loadAs(output, TriangleBean.class); - assertNotNull(loadedBean); - assertEquals("Bean25", loadedBean.getName()); - assertEquals(7, loadedBean.getShape().process()); - } + public void testGetTriangle() { + Triangle triangle = new Triangle(); + triangle.setName("Triangle25"); + TriangleBean bean = new TriangleBean(); + bean.setShape(triangle); + bean.setName("Bean25"); + Yaml beanDumper = new Yaml(); + String output = beanDumper.dumpAsMap(bean); + assertEquals( + "name: Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle\n name: Triangle25\n", + output); + Yaml beanLoader = new Yaml(); + TriangleBean loadedBean = beanLoader.loadAs(output, TriangleBean.class); + assertNotNull(loadedBean); + assertEquals("Bean25", loadedBean.getName()); + assertEquals(7, loadedBean.getShape().process()); + } - public void testClassNotFound() { - String output = "name: Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle777\n name: Triangle25\n"; - Yaml beanLoader = new Yaml(); - try { - beanLoader.loadAs(output, TriangleBean.class); - fail("Class not found expected."); - } catch (Exception e) { - assertTrue( - e.getMessage(), - e.getMessage().contains( - "Class not found: org.yaml.snakeyaml.javabeans.Triangle777")); - } + public void testClassNotFound() { + String output = + "name: Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle777\n name: Triangle25\n"; + Yaml beanLoader = new Yaml(); + try { + beanLoader.loadAs(output, TriangleBean.class); + fail("Class not found expected."); + } catch (Exception e) { + assertTrue(e.getMessage(), + e.getMessage().contains("Class not found: org.yaml.snakeyaml.javabeans.Triangle777")); } + } - /** - * Runtime class has less priority then an explicit tag - */ - public void testClassAndTag() { - String output = "name: !!whatever Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle\n name: Triangle25\n"; - Yaml beanLoader = new Yaml(); - try { - beanLoader.loadAs(output, TriangleBean.class); - fail("Runtime class has less priority then an explicit tag"); - } catch (Exception e) { - assertTrue(e.getMessage(), e.getMessage().contains("Class not found: whatever")); - } + /** + * Runtime class has less priority then an explicit tag + */ + public void testClassAndTag() { + String output = + "name: !!whatever Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle\n name: Triangle25\n"; + Yaml beanLoader = new Yaml(); + try { + beanLoader.loadAs(output, TriangleBean.class); + fail("Runtime class has less priority then an explicit tag"); + } catch (Exception e) { + assertTrue(e.getMessage(), e.getMessage().contains("Class not found: whatever")); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/json/JsonTest.java b/src/test/java/org/yaml/snakeyaml/json/JsonTest.java index 4ba2119f..19390e3e 100644 --- a/src/test/java/org/yaml/snakeyaml/json/JsonTest.java +++ b/src/test/java/org/yaml/snakeyaml/json/JsonTest.java @@ -1,88 +1,75 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.json; +import java.util.Map; import junit.framework.TestCase; import org.yaml.snakeyaml.Yaml; - -import java.util.Map; - public class JsonTest extends TestCase { - private Yaml loader = new Yaml(); - - - public void testLooksLikeJson() { - Map<String, Integer> map = (Map<String, Integer>) loader.load("{a: 1}"); - assertEquals(new Integer(1), map.get("a")); - } - - public void testSpaceAfterColon() { - Map<String, Integer> map = (Map<String, Integer>) loader.load("{\"a\": 1}"); - assertEquals(new Integer(1), map.get("a")); - } - - public void testCounterintuitiveColon() { - try { - loader.load("{a:1}"); - fail("We agree with libyaml and PyYAML."); - } catch (Exception e) { - assertTrue("':' in the flow context is a mess.", e.getMessage().contains("Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.")); - } - } - - public void testNoSpace() { - Map<String, Integer> map = (Map<String, Integer>) loader.load("{\"a\":1}"); - assertEquals(new Integer(1), map.get("a")); - } - - public void testNoSpaceBothDoubleQuoted() { - Map<String, Integer> map = (Map<String, Integer>) loader.load("{\"a\":\"1\"}"); - assertEquals("1", map.get("a")); - } - - public void testNoSpaceSingleQouted() { - Map<String, Integer> map = (Map<String, Integer>) loader.load("{'a':1}"); - assertEquals(new Integer(1), map.get("a")); - } - - public void testManyValues() { - Map<String, Object> map = (Map<String, Object>) loader.load("{\"a\":1,\"b\":true,\"c\":\"foo\"}"); - assertEquals(3, map.size()); - assertEquals(new Integer(1), map.get("a")); - assertTrue((Boolean) map.get("b")); - assertEquals("foo", map.get("c")); - } - - public void testConstructNull() { - Map<String, Object> map = (Map<String, Object>) loader.load("{a: null}"); - assertEquals(1, map.size()); - assertNull(map.get("a")); - } - - public void testConstructNullFromEmpty() { - Map<String, Object> map = (Map<String, Object>) loader.load("{a: }"); - assertEquals(1, map.size()); - assertNull(map.get("a")); - } - - public void testConstructBoolean() { - Map<String, Object> map = (Map<String, Object>) loader.load("{a: true}"); - assertEquals(1, map.size()); - assertEquals(Boolean.TRUE, map.get("a")); - } + private final Yaml loader = new Yaml(); + + + public void testLooksLikeJson() { + Map<String, Integer> map = loader.load("{a: 1}"); + assertEquals(Integer.valueOf(1), map.get("a")); + } + + public void testSpaceAfterColon() { + Map<String, Integer> map = loader.load("{\"a\": 1}"); + assertEquals(Integer.valueOf(1), map.get("a")); + } + + public void testNoSpace() { + Map<String, Integer> map = loader.load("{\"a\":1}"); + assertEquals(Integer.valueOf(1), map.get("a")); + } + + public void testNoSpaceBothDoubleQuoted() { + Map<String, Integer> map = loader.load("{\"a\":\"1\"}"); + assertEquals("1", map.get("a")); + } + + public void testNoSpaceSingleQouted() { + Map<String, Integer> map = loader.load("{'a':1}"); + assertEquals(Integer.valueOf(1), map.get("a")); + } + + public void testManyValues() { + Map<String, Object> map = loader.load("{\"a\":1,\"b\":true,\"c\":\"foo\"}"); + assertEquals(3, map.size()); + assertEquals(Integer.valueOf(1), map.get("a")); + assertTrue((Boolean) map.get("b")); + assertEquals("foo", map.get("c")); + } + + public void testConstructNull() { + Map<String, Object> map = loader.load("{a: null}"); + assertEquals(1, map.size()); + assertNull(map.get("a")); + } + + public void testConstructNullFromEmpty() { + Map<String, Object> map = loader.load("{a: }"); + assertEquals(1, map.size()); + assertNull(map.get("a")); + } + + public void testConstructBoolean() { + Map<String, Object> map = loader.load("{a: true}"); + assertEquals(1, map.size()); + assertEquals(Boolean.TRUE, map.get("a")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/lowlevel/LowLevelApiTest.java b/src/test/java/org/yaml/snakeyaml/lowlevel/LowLevelApiTest.java index 12d7f3a0..a92c4c90 100644 --- a/src/test/java/org/yaml/snakeyaml/lowlevel/LowLevelApiTest.java +++ b/src/test/java/org/yaml/snakeyaml/lowlevel/LowLevelApiTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.lowlevel; @@ -20,9 +18,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.events.ScalarEvent; @@ -30,36 +26,35 @@ import org.yaml.snakeyaml.nodes.Node; public class LowLevelApiTest extends TestCase { - public void testLowLevel() { - List<Object> list = new ArrayList<Object>(); - list.add(1); - list.add("abc"); - Map<String, String> map = new HashMap<String, String>(); - map.put("name", "Tolstoy"); - map.put("book", "War and People"); - list.add(map); - Yaml yaml = new Yaml(); - String etalon = yaml.dump(list); - // System.out.println(etalon); - // - Node node = yaml.represent(list); - // System.out.println(node); - assertEquals( - "Representation tree from an object and from its YAML document must be the same.", - yaml.compose(new StringReader(etalon)).toString(), node.toString()); - // - List<Event> events = yaml.serialize(node); - int i = 0; - for (Event etalonEvent : yaml.parse(new StringReader(etalon))) { - Event ev1 = events.get(i++); - assertEquals(etalonEvent.getClass(), ev1.getClass()); - if (etalonEvent instanceof ScalarEvent) { - ScalarEvent scalar1 = (ScalarEvent) etalonEvent; - ScalarEvent scalar2 = (ScalarEvent) ev1; - assertEquals(scalar1.getAnchor(), scalar2.getAnchor()); - assertEquals(scalar1.getValue(), scalar2.getValue()); - } - } - assertEquals(i, events.size()); + public void testLowLevel() { + List<Object> list = new ArrayList<Object>(); + list.add(1); + list.add("abc"); + Map<String, String> map = new HashMap<String, String>(); + map.put("name", "Tolstoy"); + map.put("book", "War and People"); + list.add(map); + Yaml yaml = new Yaml(); + String etalon = yaml.dump(list); + // System.out.println(etalon); + // + Node node = yaml.represent(list); + // System.out.println(node); + assertEquals("Representation tree from an object and from its YAML document must be the same.", + yaml.compose(new StringReader(etalon)).toString(), node.toString()); + // + List<Event> events = yaml.serialize(node); + int i = 0; + for (Event etalonEvent : yaml.parse(new StringReader(etalon))) { + Event ev1 = events.get(i++); + assertEquals(etalonEvent.getClass(), ev1.getClass()); + if (etalonEvent instanceof ScalarEvent) { + ScalarEvent scalar1 = (ScalarEvent) etalonEvent; + ScalarEvent scalar2 = (ScalarEvent) ev1; + assertEquals(scalar1.getAnchor(), scalar2.getAnchor()); + assertEquals(scalar1.getValue(), scalar2.getValue()); + } } + assertEquals(i, events.size()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/nodes/MappingNodeTest.java b/src/test/java/org/yaml/snakeyaml/nodes/MappingNodeTest.java index a17afbbe..c466581e 100644 --- a/src/test/java/org/yaml/snakeyaml/nodes/MappingNodeTest.java +++ b/src/test/java/org/yaml/snakeyaml/nodes/MappingNodeTest.java @@ -1,30 +1,29 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; public class MappingNodeTest extends TestCase { - public void testNullValue() { - try { - new MappingNode(new Tag("!tag"), true, null, null, null, false); - fail("Value is required."); - } catch (Exception e) { - assertEquals("value in a Node is required.", e.getMessage()); - } + public void testNullValue() { + try { + new MappingNode(new Tag("!tag"), true, null, null, null, DumperOptions.FlowStyle.BLOCK); + fail("Value is required."); + } catch (Exception e) { + assertEquals("value in a Node is required.", e.getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/nodes/NodeTest.java b/src/test/java/org/yaml/snakeyaml/nodes/NodeTest.java index ab7c6ca9..ec734953 100644 --- a/src/test/java/org/yaml/snakeyaml/nodes/NodeTest.java +++ b/src/test/java/org/yaml/snakeyaml/nodes/NodeTest.java @@ -1,51 +1,51 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import junit.framework.TestCase; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; public class NodeTest extends TestCase { - public void testNode() { - try { - new ScalarNode(new Tag("!foo"), null, null, null, '"'); - fail("Value must be required."); - } catch (Exception e) { - assertEquals("value in a Node is required.", e.getMessage()); - } + public void testNode() { + try { + new ScalarNode(new Tag("!foo"), null, null, null, DumperOptions.ScalarStyle.DOUBLE_QUOTED); + fail("Value must be required."); + } catch (Exception e) { + assertEquals("value in a Node is required.", e.getMessage()); } + } - public void testSetTag() { - try { - ScalarNode node = new ScalarNode(new Tag("!foo"), "Value1", null, null, '"'); - node.setTag((Tag) null); - fail("Value must be required."); - } catch (Exception e) { - assertEquals("tag in a Node is required.", e.getMessage()); - } + public void testSetTag() { + try { + ScalarNode node = new ScalarNode(new Tag("!foo"), "Value1", null, null, + DumperOptions.ScalarStyle.DOUBLE_QUOTED); + node.setTag(null); + fail("Value must be required."); + } catch (Exception e) { + assertEquals("tag in a Node is required.", e.getMessage()); } + } - public void testGetEndMark() { - Mark mark1 = new Mark("name", 5, 2, 12, "afd asd asd", 7); - Mark mark2 = new Mark("name", 6, 3, 13, "afd asd asd", 8); - Node node = new ScalarNode(new Tag("!foo"), "bla-bla", mark1, mark2, '"'); - assertEquals(mark1, node.getStartMark()); - assertEquals(mark2, node.getEndMark()); - } + public void testGetEndMark() { + Mark mark1 = new Mark("name", 0, 2, 12, "afd asd asd".toCharArray(), 7); + Mark mark2 = new Mark("name", 0, 3, 13, "afd asd asd".toCharArray(), 8); + Node node = new ScalarNode(new Tag("!foo"), "bla-bla", mark1, mark2, + DumperOptions.ScalarStyle.DOUBLE_QUOTED); + assertEquals(mark1, node.getStartMark()); + assertEquals(mark2, node.getEndMark()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/nodes/NodeTupleTest.java b/src/test/java/org/yaml/snakeyaml/nodes/NodeTupleTest.java index 70d0d3aa..c6dd611a 100644 --- a/src/test/java/org/yaml/snakeyaml/nodes/NodeTupleTest.java +++ b/src/test/java/org/yaml/snakeyaml/nodes/NodeTupleTest.java @@ -1,51 +1,52 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; public class NodeTupleTest extends TestCase { - public void testNodeTuple1() { - Node node = new ScalarNode(new Tag("!tag"), "value1", null, null, null); - try { - new NodeTuple(null, node); - fail("Node must be provided."); - } catch (Exception e) { - assertEquals("Nodes must be provided.", e.getMessage()); - } + public void testNodeTuple1() { + Node node = + new ScalarNode(new Tag("!tag"), "value1", null, null, DumperOptions.ScalarStyle.PLAIN); + try { + new NodeTuple(null, node); + fail("Node must be provided."); + } catch (Exception e) { + assertEquals("Nodes must be provided.", e.getMessage()); } + } - public void testNodeTuple2() { - Node node = new ScalarNode(new Tag("!tag"), "value1", null, null, null); - try { - new NodeTuple(node, null); - fail("Node must be provided."); - } catch (Exception e) { - assertEquals("Nodes must be provided.", e.getMessage()); - } + public void testNodeTuple2() { + Node node = + new ScalarNode(new Tag("!tag"), "value1", null, null, DumperOptions.ScalarStyle.PLAIN); + try { + new NodeTuple(node, null); + fail("Node must be provided."); + } catch (Exception e) { + assertEquals("Nodes must be provided.", e.getMessage()); } + } - public void testToString() { - Node key = new ScalarNode(Tag.STR, "key1", null, null, null); - Node value = new ScalarNode(Tag.STR, "value1", null, null, null); - NodeTuple tuple = new NodeTuple(key, value); - assertEquals( - "<NodeTuple keyNode=<org.yaml.snakeyaml.nodes.ScalarNode (tag=tag:yaml.org,2002:str, value=key1)>; valueNode=<org.yaml.snakeyaml.nodes.ScalarNode (tag=tag:yaml.org,2002:str, value=value1)>>", - tuple.toString()); - } + public void testToString() { + Node key = new ScalarNode(Tag.STR, "key1", null, null, DumperOptions.ScalarStyle.PLAIN); + Node value = new ScalarNode(Tag.STR, "value1", null, null, DumperOptions.ScalarStyle.PLAIN); + NodeTuple tuple = new NodeTuple(key, value); + assertEquals( + "<NodeTuple keyNode=<org.yaml.snakeyaml.nodes.ScalarNode (tag=tag:yaml.org,2002:str, value=key1)>; valueNode=<org.yaml.snakeyaml.nodes.ScalarNode (tag=tag:yaml.org,2002:str, value=value1)>>", + tuple.toString()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/nodes/ScalarNodeTest.java b/src/test/java/org/yaml/snakeyaml/nodes/ScalarNodeTest.java index 501115d9..df591945 100644 --- a/src/test/java/org/yaml/snakeyaml/nodes/ScalarNodeTest.java +++ b/src/test/java/org/yaml/snakeyaml/nodes/ScalarNodeTest.java @@ -1,37 +1,38 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; public class ScalarNodeTest extends TestCase { - protected void setUp() throws Exception { - super.setUp(); - } + protected void setUp() throws Exception { + super.setUp(); + } - public void testGetNodeId() { - Node node = new ScalarNode(new Tag("str"), "text", null, null, '>'); - assertEquals(NodeId.scalar, node.getNodeId()); - } + public void testGetNodeId() { + Node node = + new ScalarNode(new Tag("str"), "text", null, null, DumperOptions.ScalarStyle.FOLDED); + assertEquals(NodeId.scalar, node.getNodeId()); + } - public void testToString() { - Node node = new ScalarNode(new Tag("str"), "text", null, null, '>'); - assertTrue(node.toString().contains("ScalarNode")); - assertTrue(node.toString().contains("tag=")); - assertTrue(node.toString().contains("value=")); - } + public void testToString() { + Node node = + new ScalarNode(new Tag("str"), "text", null, null, DumperOptions.ScalarStyle.FOLDED); + assertTrue(node.toString().contains("ScalarNode")); + assertTrue(node.toString().contains("tag=")); + assertTrue(node.toString().contains("value=")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/nodes/SequenceNodeTest.java b/src/test/java/org/yaml/snakeyaml/nodes/SequenceNodeTest.java index 4ab1ce14..817f2616 100644 --- a/src/test/java/org/yaml/snakeyaml/nodes/SequenceNodeTest.java +++ b/src/test/java/org/yaml/snakeyaml/nodes/SequenceNodeTest.java @@ -1,38 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import java.util.ArrayList; - import junit.framework.TestCase; +import org.yaml.snakeyaml.DumperOptions; public class SequenceNodeTest extends TestCase { - public void testGetNodeId() { - SequenceNode node = new SequenceNode(new Tag("!foo"), true, new ArrayList<Node>(), null, - null, true); - assertEquals(NodeId.sequence, node.getNodeId()); - } + public void testGetNodeId() { + SequenceNode node = new SequenceNode(new Tag("!foo"), true, new ArrayList<Node>(), null, null, + DumperOptions.FlowStyle.FLOW); + assertEquals(NodeId.sequence, node.getNodeId()); + } - public void testNullValue() { - try { - new SequenceNode(new Tag("!foo"), true, null, null, null, true); - fail("Value is required."); - } catch (Exception e) { - assertEquals("value in a Node is required.", e.getMessage()); - } + public void testNullValue() { + try { + new SequenceNode(new Tag("!foo"), true, null, null, null, DumperOptions.FlowStyle.FLOW); + fail("Value is required."); + } catch (Exception e) { + assertEquals("value in a Node is required.", e.getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/nodes/TagTest.java b/src/test/java/org/yaml/snakeyaml/nodes/TagTest.java index 467d3354..5943c0ba 100644 --- a/src/test/java/org/yaml/snakeyaml/nodes/TagTest.java +++ b/src/test/java/org/yaml/snakeyaml/nodes/TagTest.java @@ -1,106 +1,92 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; -import java.net.URI; -import java.net.URISyntaxException; +import static org.junit.Assert.assertNotEquals; import junit.framework.TestCase; public class TagTest extends TestCase { - public void testCreate() { - try { - new Tag((String) null); - fail(); - } catch (Exception e) { - assertEquals("Tag must be provided.", e.getMessage()); - } - try { - new Tag(""); - fail(); - } catch (Exception e) { - assertEquals("Tag must not be empty.", e.getMessage()); - } - try { - new Tag("!Dice "); - fail(); - } catch (Exception e) { - assertEquals("Tag must not contain leading or trailing spaces.", e.getMessage()); - } - Tag tag = new Tag(TagTest.class); - assertEquals(Tag.PREFIX + "org.yaml.snakeyaml.nodes.TagTest", tag.getValue()); + public void testCreate() { + try { + new Tag((String) null); + fail(); + } catch (Exception e) { + assertEquals("Tag must be provided.", e.getMessage()); } - - public void testCreate2() { - try { - new Tag((Class<?>) null); - fail(); - } catch (Exception e) { - assertEquals("Class for tag must be provided.", e.getMessage()); - } + try { + new Tag(""); + fail(); + } catch (Exception e) { + assertEquals("Tag must not be empty.", e.getMessage()); } - - public void testGetClassName() { - Tag tag = new Tag(Tag.PREFIX + "org.yaml.snakeyaml.nodes.TagTest"); - assertEquals("org.yaml.snakeyaml.nodes.TagTest", tag.getClassName()); + try { + new Tag("!Dice "); + fail(); + } catch (Exception e) { + assertEquals("Tag must not contain leading or trailing spaces.", e.getMessage()); } + Tag tag = new Tag(TagTest.class); + assertEquals(Tag.PREFIX + "org.yaml.snakeyaml.nodes.TagTest", tag.getValue()); + } - public void testGetClassNameError() { - try { - Tag tag = new Tag("!TagTest"); - tag.getClassName(); - fail("Class name is only available for global tag"); - } catch (Exception e) { - assertEquals("Invalid tag: !TagTest", e.getMessage()); - } + public void testCreate2() { + try { + new Tag((Class<?>) null); + fail(); + } catch (Exception e) { + assertEquals("Class for tag must be provided.", e.getMessage()); } + } - public void testLength() { - String t = Tag.PREFIX + "org.yaml.snakeyaml.nodes.TagTest"; - Tag tag = new Tag(t); - assertEquals(t.length(), tag.getLength()); - } + public void testGetClassName() { + Tag tag = new Tag(Tag.PREFIX + "org.yaml.snakeyaml.nodes.TagTest"); + assertEquals("org.yaml.snakeyaml.nodes.TagTest", tag.getClassName()); + } - public void testToString() { - Tag tag = new Tag("!car"); - assertEquals("!car", tag.toString()); + public void testGetClassNameError() { + try { + Tag tag = new Tag("!TagTest"); + tag.getClassName(); + fail("Class name is only available for global tag"); + } catch (Exception e) { + assertEquals("Invalid tag: !TagTest", e.getMessage()); } + } - public void testUri1() { - Tag tag = new Tag("!Acadรฉmico"); - assertEquals("!Acad%C3%A9mico", tag.toString()); - } + public void testToString() { + Tag tag = new Tag("!car"); + assertEquals("!car", tag.toString()); + } - public void testUri2() { - Tag tag = new Tag("!ruby/object:Test::Module::Sub2"); - assertEquals("!ruby/object:Test::Module::Sub2", tag.getValue()); - } + public void testUri1() { + Tag tag = new Tag("!Acadรฉmico"); + assertEquals("!Acad%C3%A9mico", tag.toString()); + } - public void testCompare() { - Tag tag = new Tag("!car"); - assertEquals(0, tag.compareTo(new Tag("!car"))); - } + public void testUri2() { + Tag tag = new Tag("!ruby/object:Test::Module::Sub2"); + assertEquals("!ruby/object:Test::Module::Sub2", tag.getValue()); + } - public void testEqualsObject() { - Tag tag = new Tag("!car"); - assertEquals(tag, tag); - assertEquals(tag, new Tag("!car")); - assertFalse(tag.equals(new Tag("!!str"))); - assertFalse(tag.equals(null)); - assertFalse(tag.equals(25)); - } + public void testEqualsObject() { + Tag tag = new Tag("!car"); + assertEquals(tag, tag); + assertEquals(tag, new Tag("!car")); + assertNotEquals(tag, new Tag("!!str")); + assertNotEquals(null, tag); + assertNotEquals(25, tag); + } } diff --git a/src/test/java/org/yaml/snakeyaml/nodes/TagsTest.java b/src/test/java/org/yaml/snakeyaml/nodes/TagsTest.java index 51556232..547910f2 100644 --- a/src/test/java/org/yaml/snakeyaml/nodes/TagsTest.java +++ b/src/test/java/org/yaml/snakeyaml/nodes/TagsTest.java @@ -1,57 +1,54 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.nodes; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; public class TagsTest extends TestCase { - public void testGetGlobalTagForClass() { - assertEquals(new Tag("tag:yaml.org,2002:java.lang.String"), new Tag(String.class)); - assertEquals(new Tag("tag:yaml.org,2002:org.yaml.snakeyaml.nodes.TagsTest"), new Tag( - TagsTest.class)); - } - - /** - * test fix for issue 18 - - * http://code.google.com/p/snakeyaml/issues/detail?id=18 - */ - public void testLong() { - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - Yaml yaml = new Yaml(options); - Foo foo = new Foo(); - String output = yaml.dump(foo); - // System.out.println(output); - Foo foo2 = (Foo) yaml.load(output); - assertEquals(new Long(42L), foo2.getBar()); + public void testGetGlobalTagForClass() { + assertEquals(new Tag("tag:yaml.org,2002:java.lang.String"), new Tag(String.class)); + assertEquals(new Tag("tag:yaml.org,2002:org.yaml.snakeyaml.nodes.TagsTest"), + new Tag(TagsTest.class)); + } + + /** + * test fix for issue 18 - http://code.google.com/p/snakeyaml/issues/detail?id=18 + */ + public void testLong() { + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + Yaml yaml = new Yaml(options); + Foo foo = new Foo(); + String output = yaml.dump(foo); + // System.out.println(output); + Foo foo2 = yaml.load(output); + assertEquals(Long.valueOf(42L), foo2.getBar()); + } + + public static class Foo { + + private Long bar = Long.valueOf(42L); + + public Long getBar() { + return bar; } - public static class Foo { - private Long bar = Long.valueOf(42L); - - public Long getBar() { - return bar; - } - - public void setBar(Long bar) { - this.bar = bar; - } + public void setBar(Long bar) { + this.bar = bar; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/parser/ParserImplTest.java b/src/test/java/org/yaml/snakeyaml/parser/ParserImplTest.java index d8bd3c8a..22163b8c 100644 --- a/src/test/java/org/yaml/snakeyaml/parser/ParserImplTest.java +++ b/src/test/java/org/yaml/snakeyaml/parser/ParserImplTest.java @@ -1,24 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.parser; import java.util.LinkedList; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.events.DocumentEndEvent; import org.yaml.snakeyaml.events.DocumentStartEvent; @@ -35,57 +32,72 @@ import org.yaml.snakeyaml.reader.StreamReader; public class ParserImplTest extends TestCase { - private void check(LinkedList<Event> etalonEvents, Parser parser) { - while (parser.checkEvent(null)) { - Event event = parser.getEvent(); - if (etalonEvents.isEmpty()) { - fail("unexpected event: " + event); - } - assertEquals(etalonEvents.removeFirst(), event); - } - assertFalse("Must contain no more events: " + parser.getEvent(), parser.checkEvent(null)); + private void check(LinkedList<Event> etalonEvents, Parser parser) { + for (Event etalonEvent : etalonEvents) { + parser.checkEvent(etalonEvent.getEventId()); + Event event = parser.getEvent(); + if (event == null) { + fail("Missing event: " + etalonEvent); + } + assertEquals(etalonEvent, event); } + } - public void testGetEvent() { - String data = "string: abcd"; - StreamReader reader = new StreamReader(data); - Parser parser = new ParserImpl(reader); - Mark dummyMark = new Mark("dummy", 0, 0, 0, "", 0); - LinkedList<Event> etalonEvents = new LinkedList<Event>(); - etalonEvents.add(new StreamStartEvent(dummyMark, dummyMark)); - etalonEvents.add(new DocumentStartEvent(dummyMark, dummyMark, false, null, null)); - etalonEvents.add(new MappingStartEvent(null, null, true, dummyMark, dummyMark, - Boolean.FALSE)); - etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "string", - dummyMark, dummyMark, (char) 0)); - etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "abcd", - dummyMark, dummyMark, (char) 0)); - etalonEvents.add(new MappingEndEvent(dummyMark, dummyMark)); - etalonEvents.add(new DocumentEndEvent(dummyMark, dummyMark, false)); - etalonEvents.add(new StreamEndEvent(dummyMark, dummyMark)); - check(etalonEvents, parser); - } + public void testGetEventWithTag() { + String data = "! 12"; + StreamReader reader = new StreamReader(data); + Parser parser = new ParserImpl(reader); + Mark dummyMark = new Mark("dummy", 0, 0, 0, "".toCharArray(), 0); + LinkedList<Event> etalonEvents = new LinkedList<Event>(); + etalonEvents.add(new StreamStartEvent(dummyMark, dummyMark)); + etalonEvents.add(new DocumentStartEvent(dummyMark, dummyMark, false, null, null)); + etalonEvents.add(new ScalarEvent(null, "!", new ImplicitTuple(true, false), "12", dummyMark, + dummyMark, DumperOptions.ScalarStyle.PLAIN)); + etalonEvents.add(new DocumentEndEvent(dummyMark, dummyMark, false)); + etalonEvents.add(new StreamEndEvent(dummyMark, dummyMark)); + check(etalonEvents, parser); + } - public void testGetEvent2() { - String data = "american:\n - Boston Red Sox"; - StreamReader reader = new StreamReader(data); - Parser parser = new ParserImpl(reader); - Mark dummyMark = new Mark("dummy", 0, 0, 0, "", 0); - LinkedList<Event> etalonEvents = new LinkedList<Event>(); - etalonEvents.add(new StreamStartEvent(dummyMark, dummyMark)); - etalonEvents.add(new DocumentStartEvent(dummyMark, dummyMark, false, null, null)); - etalonEvents - .add(new MappingStartEvent(null, null, true, dummyMark, dummyMark, Boolean.TRUE)); - etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "american", - dummyMark, dummyMark, (char) 0)); - etalonEvents.add(new SequenceStartEvent(null, null, true, dummyMark, dummyMark, - Boolean.FALSE)); - etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), - "Boston Red Sox", dummyMark, dummyMark, (char) 0)); - etalonEvents.add(new SequenceEndEvent(dummyMark, dummyMark)); - etalonEvents.add(new MappingEndEvent(dummyMark, dummyMark)); - etalonEvents.add(new DocumentEndEvent(dummyMark, dummyMark, false)); - etalonEvents.add(new StreamEndEvent(dummyMark, dummyMark)); - check(etalonEvents, parser); - } + public void testGetEvent() { + String data = "string: abcd"; + StreamReader reader = new StreamReader(data); + Parser parser = new ParserImpl(reader); + Mark dummyMark = new Mark("dummy", 0, 0, 0, "".toCharArray(), 0); + LinkedList<Event> etalonEvents = new LinkedList<Event>(); + etalonEvents.add(new StreamStartEvent(dummyMark, dummyMark)); + etalonEvents.add(new DocumentStartEvent(dummyMark, dummyMark, false, null, null)); + etalonEvents.add(new MappingStartEvent(null, null, true, dummyMark, dummyMark, + DumperOptions.FlowStyle.BLOCK)); + etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "string", + dummyMark, dummyMark, DumperOptions.ScalarStyle.PLAIN)); + etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "abcd", dummyMark, + dummyMark, DumperOptions.ScalarStyle.PLAIN)); + etalonEvents.add(new MappingEndEvent(dummyMark, dummyMark)); + etalonEvents.add(new DocumentEndEvent(dummyMark, dummyMark, false)); + etalonEvents.add(new StreamEndEvent(dummyMark, dummyMark)); + check(etalonEvents, parser); + } + + public void testGetEvent2() { + String data = "american:\n - Boston Red Sox"; + StreamReader reader = new StreamReader(data); + Parser parser = new ParserImpl(reader); + Mark dummyMark = new Mark("dummy", 0, 0, 0, "".toCharArray(), 0); + LinkedList<Event> etalonEvents = new LinkedList<Event>(); + etalonEvents.add(new StreamStartEvent(dummyMark, dummyMark)); + etalonEvents.add(new DocumentStartEvent(dummyMark, dummyMark, false, null, null)); + etalonEvents.add(new MappingStartEvent(null, null, true, dummyMark, dummyMark, + DumperOptions.FlowStyle.FLOW)); + etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "american", + dummyMark, dummyMark, DumperOptions.ScalarStyle.PLAIN)); + etalonEvents.add(new SequenceStartEvent(null, null, true, dummyMark, dummyMark, + DumperOptions.FlowStyle.BLOCK)); + etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "Boston Red Sox", + dummyMark, dummyMark, DumperOptions.ScalarStyle.PLAIN)); + etalonEvents.add(new SequenceEndEvent(dummyMark, dummyMark)); + etalonEvents.add(new MappingEndEvent(dummyMark, dummyMark)); + etalonEvents.add(new DocumentEndEvent(dummyMark, dummyMark, false)); + etalonEvents.add(new StreamEndEvent(dummyMark, dummyMark)); + check(etalonEvents, parser); + } } diff --git a/src/test/java/org/yaml/snakeyaml/parser/VersionTagsTupleTest.java b/src/test/java/org/yaml/snakeyaml/parser/VersionTagsTupleTest.java index abd072b0..3132dc6f 100644 --- a/src/test/java/org/yaml/snakeyaml/parser/VersionTagsTupleTest.java +++ b/src/test/java/org/yaml/snakeyaml/parser/VersionTagsTupleTest.java @@ -1,30 +1,26 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.parser; import java.util.HashMap; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions.Version; public class VersionTagsTupleTest extends TestCase { - public void testToString() { - VersionTagsTuple tuple = new VersionTagsTuple(Version.V1_1, new HashMap<String, String>()); - assertEquals("VersionTagsTuple<Version: 1.1, {}>", tuple.toString()); - } + public void testToString() { + VersionTagsTuple tuple = new VersionTagsTuple(Version.V1_1, new HashMap<String, String>()); + assertEquals("VersionTagsTuple<Version: 1.1, {}>", tuple.toString()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/partialconstruct/DeveloperBean.java b/src/test/java/org/yaml/snakeyaml/partialconstruct/DeveloperBean.java index f9a1e570..fcb7097b 100644 --- a/src/test/java/org/yaml/snakeyaml/partialconstruct/DeveloperBean.java +++ b/src/test/java/org/yaml/snakeyaml/partialconstruct/DeveloperBean.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.partialconstruct; public class DeveloperBean { - String name; - String language; - public String getName() { - return name; - } + String name; + String language; - public String getLanguage() { - return language; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public String getLanguage() { + return language; + } - public void setLanguage(String language) { - this.language = language; - } -}
\ No newline at end of file + public void setName(String name) { + this.name = name; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposer.java b/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposer.java index eccf57eb..d0883135 100644 --- a/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposer.java +++ b/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposer.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.partialconstruct; @@ -24,29 +22,30 @@ import org.yaml.snakeyaml.parser.Parser; import org.yaml.snakeyaml.resolver.Resolver; class FragmentComposer extends Composer { - String nodeName; - public FragmentComposer(Parser parser, Resolver resolver, String nodeName) { - super(parser, resolver); - this.nodeName = nodeName; - } + String nodeName; - @Override - public Node getSingleNode() { - Node node = super.getSingleNode(); - if (!MappingNode.class.isAssignableFrom(node.getClass())) { - throw new RuntimeException( - "Document is not structured as expected. Root element should be a map!"); - } - MappingNode root = (MappingNode) node; - for (NodeTuple tuple : root.getValue()) { - Node keyNode = tuple.getKeyNode(); - if (ScalarNode.class.isAssignableFrom(keyNode.getClass())) { - if (((ScalarNode) keyNode).getValue().equals(nodeName)) { - return tuple.getValueNode(); - } - } + public FragmentComposer(Parser parser, Resolver resolver, String nodeName) { + super(parser, resolver); + this.nodeName = nodeName; + } + + @Override + public Node getSingleNode() { + Node node = super.getSingleNode(); + if (!MappingNode.class.isAssignableFrom(node.getClass())) { + throw new RuntimeException( + "Document is not structured as expected. Root element should be a map!"); + } + MappingNode root = (MappingNode) node; + for (NodeTuple tuple : root.getValue()) { + Node keyNode = tuple.getKeyNode(); + if (ScalarNode.class.isAssignableFrom(keyNode.getClass())) { + if (((ScalarNode) keyNode).getValue().equals(nodeName)) { + return tuple.getValueNode(); } - throw new RuntimeException("Did not find key \"" + nodeName + "\" in document-level map"); + } } -}
\ No newline at end of file + throw new RuntimeException("Did not find key \"" + nodeName + "\" in document-level map"); + } +} diff --git a/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposerTest.java b/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposerTest.java index c2bb990d..de34f812 100644 --- a/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposerTest.java +++ b/src/test/java/org/yaml/snakeyaml/partialconstruct/FragmentComposerTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.partialconstruct; import junit.framework.TestCase; - import org.yaml.snakeyaml.composer.Composer; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.parser.ParserImpl; @@ -25,18 +22,17 @@ import org.yaml.snakeyaml.resolver.Resolver; public class FragmentComposerTest extends TestCase { - public void testFragment() { - String document = "foo: blargle\n" - + "developer: { name: \"Bjarne Stroustrup\", language: \"C++\"}\n" - + "gee: [ \"whiz\", \"bang\"]\n";// + public void testFragment() { + String document = + "foo: blargle\n" + "developer: { name: \"Bjarne Stroustrup\", language: \"C++\"}\n" + + "gee: [ \"whiz\", \"bang\"]\n";// - StreamReader reader = new StreamReader(document); - Composer composer = new FragmentComposer(new ParserImpl(reader), new Resolver(), - "developer"); - Constructor constructor = new Constructor(); - constructor.setComposer(composer); - DeveloperBean developer = (DeveloperBean) constructor.getSingleData(DeveloperBean.class); - assertEquals("Bjarne Stroustrup", developer.name); - assertEquals("C++", developer.language); - } + StreamReader reader = new StreamReader(document); + Composer composer = new FragmentComposer(new ParserImpl(reader), new Resolver(), "developer"); + Constructor constructor = new Constructor(); + constructor.setComposer(composer); + DeveloperBean developer = (DeveloperBean) constructor.getSingleData(DeveloperBean.class); + assertEquals("Bjarne Stroustrup", developer.name); + assertEquals("C++", developer.language); + } } diff --git a/src/test/java/org/yaml/snakeyaml/reader/IoReaderTest.java b/src/test/java/org/yaml/snakeyaml/reader/IoReaderTest.java index 625f735b..0817e684 100644 --- a/src/test/java/org/yaml/snakeyaml/reader/IoReaderTest.java +++ b/src/test/java/org/yaml/snakeyaml/reader/IoReaderTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.reader; @@ -19,31 +17,29 @@ import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class IoReaderTest extends TestCase { - @SuppressWarnings("unchecked") - public void testCheckPrintable() throws IOException { - Yaml yaml = new Yaml(); - Reader reader = new FileReader("src/test/resources/specification/example2_1.yaml"); - List<String> list = (List<String>) yaml.load(reader); - reader.close(); - assertEquals(3, list.size()); - } + @SuppressWarnings("unchecked") + public void testCheckPrintable() throws IOException { + Yaml yaml = new Yaml(); + Reader reader = new FileReader("src/test/resources/specification/example2_1.yaml"); + List<String> list = yaml.load(reader); + reader.close(); + assertEquals(3, list.size()); + } - /** - * test input which is longer then internal buffer - 1k - */ - public void testBigInput() throws IOException { - Yaml yaml = new Yaml(); - Reader reader = new FileReader("src/test/resources/reader/large.yaml"); - @SuppressWarnings("unchecked") - List<Object> list = (List<Object>) yaml.load(reader); - reader.close(); - assertEquals(37, list.size()); - } + /** + * test input which is longer then internal buffer - 1k + */ + public void testBigInput() throws IOException { + Yaml yaml = new Yaml(); + Reader reader = new FileReader("src/test/resources/reader/large.yaml"); + @SuppressWarnings("unchecked") + List<Object> list = yaml.load(reader); + reader.close(); + assertEquals(37, list.size()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/reader/ReaderBomTest.java b/src/test/java/org/yaml/snakeyaml/reader/ReaderBomTest.java index ffde7dda..c7396c2c 100644 --- a/src/test/java/org/yaml/snakeyaml/reader/ReaderBomTest.java +++ b/src/test/java/org/yaml/snakeyaml/reader/ReaderBomTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.reader; @@ -23,94 +21,97 @@ import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.nio.charset.Charset; - +import java.nio.charset.StandardCharsets; import junit.framework.TestCase; public class ReaderBomTest extends TestCase { - public void testReader() { - Reader input = new StringReader("test"); - StreamReader reader = new StreamReader(input); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('e', reader.peek()); - reader.forward(1); - assertEquals('s', reader.peek()); - reader.forward(1); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('\u0000', reader.peek()); - } + public void testReader() { + Reader input = new StringReader("test"); + StreamReader reader = new StreamReader(input); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('e', reader.peek()); + reader.forward(1); + assertEquals('s', reader.peek()); + reader.forward(1); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('\u0000', reader.peek()); + } - public void testNoBom() throws IOException { - byte[] data = "test".getBytes("UTF-8"); - ByteArrayInputStream input = new ByteArrayInputStream(data); - Reader r = new UnicodeReader(input); - StreamReader reader = new StreamReader(r); - assertEquals('t', reader.peek()); - assertEquals(Charset.forName("UTF-8"), reader.getEncoding()); - reader.forward(1); - assertEquals('e', reader.peek()); - reader.forward(1); - assertEquals('s', reader.peek()); - reader.forward(1); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('\u0000', reader.peek()); - r.close(); - } + public void testNoBom() throws IOException { + byte[] data = "test".getBytes(StandardCharsets.UTF_8); + ByteArrayInputStream input = new ByteArrayInputStream(data); + UnicodeReader r = new UnicodeReader(input); + StreamReader reader = new StreamReader(r); + assertEquals('t', reader.peek()); + assertEquals(StandardCharsets.UTF_8, Charset.forName(r.getEncoding())); + reader.forward(1); + assertEquals('e', reader.peek()); + reader.forward(1); + assertEquals('s', reader.peek()); + reader.forward(1); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('\u0000', reader.peek()); + r.close(); + } - public void testUtf8Bom() throws IOException { - File file = new File("src/test/resources/reader/utf-8.txt"); - assertTrue("Test file not found: " + file.getAbsolutePath(), file.exists()); - InputStream input = new FileInputStream(file); - StreamReader reader = new StreamReader(new UnicodeReader(input)); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('e', reader.peek()); - reader.forward(1); - assertEquals('s', reader.peek()); - reader.forward(1); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('\u0000', reader.peek()); - assertEquals(Charset.forName("UTF-8"), reader.getEncoding()); - input.close(); - } + public void testUtf8Bom() throws IOException { + File file = new File("src/test/resources/reader/utf-8.txt"); + assertTrue("Test file not found: " + file.getAbsolutePath(), file.exists()); + InputStream input = new FileInputStream(file); + UnicodeReader unicodeReader = new UnicodeReader(input); + StreamReader reader = new StreamReader(unicodeReader); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('e', reader.peek()); + reader.forward(1); + assertEquals('s', reader.peek()); + reader.forward(1); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('\u0000', reader.peek()); + assertEquals(StandardCharsets.UTF_8, Charset.forName(unicodeReader.getEncoding())); + input.close(); + } - public void testUnicodeLeBom() throws IOException { - File file = new File("src/test/resources/reader/unicode-16le.txt"); - assertTrue("Test file not found: " + file.getAbsolutePath(), file.exists()); - InputStream input = new FileInputStream(file); - StreamReader reader = new StreamReader(new UnicodeReader(input)); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('e', reader.peek()); - reader.forward(1); - assertEquals('s', reader.peek()); - reader.forward(1); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('\u0000', reader.peek()); - assertEquals(Charset.forName("UTF-16LE"), reader.getEncoding()); - input.close(); - } + public void testUnicodeLeBom() throws IOException { + File file = new File("src/test/resources/reader/unicode-16le.txt"); + assertTrue("Test file not found: " + file.getAbsolutePath(), file.exists()); + InputStream input = new FileInputStream(file); + UnicodeReader unicodeReader = new UnicodeReader(input); + StreamReader reader = new StreamReader(unicodeReader); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('e', reader.peek()); + reader.forward(1); + assertEquals('s', reader.peek()); + reader.forward(1); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('\u0000', reader.peek()); + assertEquals(StandardCharsets.UTF_16LE, Charset.forName(unicodeReader.getEncoding())); + input.close(); + } - public void testUnicodeBeBom() throws IOException { - File file = new File("src/test/resources/reader/unicode-16be.txt"); - assertTrue("Test file not found: " + file.getAbsolutePath(), file.exists()); - InputStream input = new FileInputStream(file); - StreamReader reader = new StreamReader(new UnicodeReader(input)); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('e', reader.peek()); - reader.forward(1); - assertEquals('s', reader.peek()); - reader.forward(1); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('\u0000', reader.peek()); - assertEquals(Charset.forName("UTF-16BE"), reader.getEncoding()); - input.close(); - } + public void testUnicodeBeBom() throws IOException { + File file = new File("src/test/resources/reader/unicode-16be.txt"); + assertTrue("Test file not found: " + file.getAbsolutePath(), file.exists()); + InputStream input = new FileInputStream(file); + UnicodeReader unicodeReader = new UnicodeReader(input); + StreamReader reader = new StreamReader(unicodeReader); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('e', reader.peek()); + reader.forward(1); + assertEquals('s', reader.peek()); + reader.forward(1); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('\u0000', reader.peek()); + assertEquals(StandardCharsets.UTF_16BE, Charset.forName(unicodeReader.getEncoding())); + input.close(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/reader/ReaderStringTest.java b/src/test/java/org/yaml/snakeyaml/reader/ReaderStringTest.java index 282b7e6f..6fc8defa 100644 --- a/src/test/java/org/yaml/snakeyaml/reader/ReaderStringTest.java +++ b/src/test/java/org/yaml/snakeyaml/reader/ReaderStringTest.java @@ -1,107 +1,94 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.reader; -import java.util.regex.Matcher; - +import java.io.StringReader; import junit.framework.TestCase; public class ReaderStringTest extends TestCase { - public void testCheckPrintable() { - StreamReader reader = new StreamReader("test"); - reader.checkPrintable("test"); - Matcher matcher = StreamReader.NON_PRINTABLE.matcher("test"); - assertFalse(matcher.find()); - - try { - reader.checkPrintable("test".toCharArray(), 0, 4); - } catch (ReaderException e) { - fail(); - } + public void testCheckPrintable() { + StreamReader reader = new StreamReader("test"); + assertEquals('\0', reader.peek(4)); + assertTrue(StreamReader.isPrintable("test")); + } + public void testCheckNonPrintable() { + assertFalse(StreamReader.isPrintable("test\u0005 fail")); + try { + StreamReader reader = new StreamReader("test\u0005 fail"); + while (reader.peek() != '\0') { + reader.forward(); + } + fail("Non printable Unicode code points must not be accepted."); + } catch (ReaderException e) { + assertEquals( + "unacceptable code point '' (0x5) special characters are not allowed\nin \"'string'\", position 4", + e.toString()); } + } - public void testCheckNonPrintable() { - Matcher matcher = StreamReader.NON_PRINTABLE.matcher("test\u0005 fail"); - assertTrue(matcher.find()); - try { - new StreamReader("test\u0005 fail"); - fail("Non printable Unicode characters must not be accepted."); - } catch (ReaderException e) { - assertEquals( - "unacceptable character '' (0x5) special characters are not allowed\nin \"'string'\", position 4", - e.toString()); - } - } + /** + * test that Reading date and checking String work the same + */ + public void testCheckAll() { + for (char i = 0; i < 256 * 256 - 1; i++) { + char[] chars = new char[1]; + chars[0] = i; + String str = new String(chars); + boolean regularExpressionResult = StreamReader.isPrintable(str); - /** - * test that regular expression and array check work the same - */ - public void testCheckAll() { - StreamReader streamReader = new StreamReader(""); - for (char i = 0; i < 256 * 256 - 1; i++) { - char[] chars = new char[1]; - chars[0] = i; - String str = new String(chars); - Matcher matcher = StreamReader.NON_PRINTABLE.matcher(str); - boolean regularExpressionResult = !matcher.find(); - - boolean charsArrayResult = true; - try { - streamReader.checkPrintable(chars, 0, 1); - } catch (Exception e) { - String error = e.getMessage(); - assertTrue( - error, - error.startsWith("unacceptable character") - || error.equals("special characters are not allowed")); - charsArrayResult = false; - } - assertEquals("Failed for #" + i, regularExpressionResult, charsArrayResult); - } + boolean charsArrayResult = true; + try { + new StreamReader(new StringReader(str)).peek(); + } catch (Exception e) { + String error = e.getMessage(); + assertTrue(error, error.startsWith("unacceptable character") + || error.equals("special characters are not allowed")); + charsArrayResult = false; + } + assertEquals("Failed for #" + i, regularExpressionResult, charsArrayResult); } + } - public void testForward() { - StreamReader reader = new StreamReader("test"); - while (reader.peek() != '\u0000') { - reader.forward(1); - } - reader = new StreamReader("test"); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('e', reader.peek()); - reader.forward(1); - assertEquals('s', reader.peek()); - reader.forward(1); - assertEquals('t', reader.peek()); - reader.forward(1); - assertEquals('\u0000', reader.peek()); + public void testForward() { + StreamReader reader = new StreamReader("test"); + while (reader.peek() != '\u0000') { + reader.forward(1); } + reader = new StreamReader("test"); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('e', reader.peek()); + reader.forward(1); + assertEquals('s', reader.peek()); + reader.forward(1); + assertEquals('t', reader.peek()); + reader.forward(1); + assertEquals('\u0000', reader.peek()); + } - public void testPeekInt() { - StreamReader reader = new StreamReader("test"); - assertEquals('t', reader.peek(0)); - assertEquals('e', reader.peek(1)); - assertEquals('s', reader.peek(2)); - assertEquals('t', reader.peek(3)); - reader.forward(1); - assertEquals('e', reader.peek(0)); - assertEquals('s', reader.peek(1)); - assertEquals('t', reader.peek(2)); - } + public void testPeekInt() { + StreamReader reader = new StreamReader("test"); + assertEquals('t', reader.peek(0)); + assertEquals('e', reader.peek(1)); + assertEquals('s', reader.peek(2)); + assertEquals('t', reader.peek(3)); + reader.forward(1); + assertEquals('e', reader.peek(0)); + assertEquals('s', reader.peek(1)); + assertEquals('t', reader.peek(2)); + } } diff --git a/src/test/java/org/yaml/snakeyaml/reader/WindowsTest.java b/src/test/java/org/yaml/snakeyaml/reader/WindowsTest.java new file mode 100644 index 00000000..33db2b36 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/reader/WindowsTest.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.reader; + +import junit.framework.TestCase; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.parser.ParserException; + +/** + * https://yaml.org/spec/1.1/#id871136 + */ +public class WindowsTest extends TestCase { + + // test windows style + public void testCRLF() { + try { + Yaml yaml = new Yaml(); + yaml.load("\r\n["); + } catch (ParserException e) { + assertTrue(e.getMessage().contains("line 2,")); + } + } + + public void testCRCR() { + try { + Yaml yaml = new Yaml(); + yaml.load("\r\r["); + } catch (ParserException e) { + assertTrue(e.getMessage().contains("line 3,")); + } + } + + // test UNIX style + public void testLFLF() { + try { + Yaml yaml = new Yaml(); + yaml.load("\n\n["); + } catch (ParserException e) { + assertTrue(e.getMessage().contains("line 3,")); + } + } +} diff --git a/src/test/java/org/yaml/snakeyaml/recursive/AbstractHuman.java b/src/test/java/org/yaml/snakeyaml/recursive/AbstractHuman.java index a0ee3334..c8f25695 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/AbstractHuman.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/AbstractHuman.java @@ -1,86 +1,91 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive; import java.util.Date; public abstract class AbstractHuman { - private String name; - private Date birthday; - private String birthPlace; - public String getName() { - return name; - } + private String name; + private Date birthday; + private String birthPlace; - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public Date getBirthday() { - return birthday; - } + public void setName(String name) { + this.name = name; + } - public void setBirthday(Date birthday) { - this.birthday = birthday; - } + public Date getBirthday() { + return birthday; + } - public String getBirthPlace() { - return birthPlace; - } + public void setBirthday(Date birthday) { + this.birthday = birthday; + } - public void setBirthPlace(String birthPlace) { - this.birthPlace = birthPlace; - } + public String getBirthPlace() { + return birthPlace; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((birthPlace == null) ? 0 : birthPlace.hashCode()); - result = prime * result + ((birthday == null) ? 0 : birthday.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } + public void setBirthPlace(String birthPlace) { + this.birthPlace = birthPlace; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AbstractHuman other = (AbstractHuman) obj; - if (birthPlace == null) { - if (other.birthPlace != null) - return false; - } else if (!birthPlace.equals(other.birthPlace)) - return false; - if (birthday == null) { - if (other.birthday != null) - return false; - } else if (!birthday.equals(other.birthday)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((birthPlace == null) ? 0 : birthPlace.hashCode()); + result = prime * result + ((birthday == null) ? 0 : birthday.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + AbstractHuman other = (AbstractHuman) obj; + if (birthPlace == null) { + if (other.birthPlace != null) { + return false; + } + } else if (!birthPlace.equals(other.birthPlace)) { + return false; + } + if (birthday == null) { + if (other.birthday != null) { + return false; + } + } else if (!birthday.equals(other.birthday)) { + return false; + } + if (name == null) { + return other.name == null; + } else { + return name.equals(other.name); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/Human.java b/src/test/java/org/yaml/snakeyaml/recursive/Human.java index 1ff91ae4..f5302d29 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/Human.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/Human.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive; @@ -20,54 +18,54 @@ import java.util.Set; public class Human extends AbstractHuman { - private Human father; - private Human mother; - private Human partner; - private Human bankAccountOwner; - protected Set<Human> children; + private Human father; + private Human mother; + private Human partner; + private Human bankAccountOwner; + protected Set<Human> children; - public Human() { - children = new HashSet<Human>(); - } + public Human() { + children = new HashSet<Human>(); + } - public Human getFather() { - return father; - } + public Human getFather() { + return father; + } - public void setFather(Human father) { - this.father = father; - } + public void setFather(Human father) { + this.father = father; + } - public Human getMother() { - return mother; - } + public Human getMother() { + return mother; + } - public void setMother(Human mother) { - this.mother = mother; - } + public void setMother(Human mother) { + this.mother = mother; + } - public Human getPartner() { - return partner; - } + public Human getPartner() { + return partner; + } - public void setPartner(Human partner) { - this.partner = partner; - } + public void setPartner(Human partner) { + this.partner = partner; + } - public Human getBankAccountOwner() { - return bankAccountOwner; - } + public Human getBankAccountOwner() { + return bankAccountOwner; + } - public void setBankAccountOwner(Human bankAccountOwner) { - this.bankAccountOwner = bankAccountOwner; - } + public void setBankAccountOwner(Human bankAccountOwner) { + this.bankAccountOwner = bankAccountOwner; + } - public Set<Human> getChildren() { - return children; - } + public Set<Human> getChildren() { + return children; + } - public void setChildren(Set<Human> children) { - this.children = children; - } + public void setChildren(Set<Human> children) { + this.children = children; + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/Human2.java b/src/test/java/org/yaml/snakeyaml/recursive/Human2.java index d056c725..1110a53d 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/Human2.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/Human2.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive; @@ -20,54 +18,54 @@ import java.util.Map; public class Human2 extends AbstractHuman { - private Human2 father; - private Human2 mother; - private Human2 partner; - private Human2 bankAccountOwner; - protected Map<Human2, String> children; + private Human2 father; + private Human2 mother; + private Human2 partner; + private Human2 bankAccountOwner; + protected Map<Human2, String> children; - public Human2() { - children = new HashMap<Human2, String>(); - } + public Human2() { + children = new HashMap<Human2, String>(); + } - public Human2 getFather() { - return father; - } + public Human2 getFather() { + return father; + } - public void setFather(Human2 father) { - this.father = father; - } + public void setFather(Human2 father) { + this.father = father; + } - public Human2 getMother() { - return mother; - } + public Human2 getMother() { + return mother; + } - public void setMother(Human2 mother) { - this.mother = mother; - } + public void setMother(Human2 mother) { + this.mother = mother; + } - public Human2 getPartner() { - return partner; - } + public Human2 getPartner() { + return partner; + } - public void setPartner(Human2 partner) { - this.partner = partner; - } + public void setPartner(Human2 partner) { + this.partner = partner; + } - public Human2 getBankAccountOwner() { - return bankAccountOwner; - } + public Human2 getBankAccountOwner() { + return bankAccountOwner; + } - public void setBankAccountOwner(Human2 bankAccountOwner) { - this.bankAccountOwner = bankAccountOwner; - } + public void setBankAccountOwner(Human2 bankAccountOwner) { + this.bankAccountOwner = bankAccountOwner; + } - public Map<Human2, String> getChildren() { - return children; - } + public Map<Human2, String> getChildren() { + return children; + } - public void setChildren(Map<Human2, String> children) { - this.children = children; - } + public void setChildren(Map<Human2, String> children) { + this.children = children; + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/Human3.java b/src/test/java/org/yaml/snakeyaml/recursive/Human3.java index 41bda1fb..038db9ed 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/Human3.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/Human3.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive; @@ -20,54 +18,54 @@ import java.util.List; public class Human3 extends AbstractHuman { - private Human3 father; - private Human3 mother; - private Human3 partner; - private Human3 bankAccountOwner; - protected List<Human3> children; + private Human3 father; + private Human3 mother; + private Human3 partner; + private Human3 bankAccountOwner; + protected List<Human3> children; - public Human3() { - children = new ArrayList<Human3>(); - } + public Human3() { + children = new ArrayList<Human3>(); + } - public Human3 getFather() { - return father; - } + public Human3 getFather() { + return father; + } - public void setFather(Human3 father) { - this.father = father; - } + public void setFather(Human3 father) { + this.father = father; + } - public Human3 getMother() { - return mother; - } + public Human3 getMother() { + return mother; + } - public void setMother(Human3 mother) { - this.mother = mother; - } + public void setMother(Human3 mother) { + this.mother = mother; + } - public Human3 getPartner() { - return partner; - } + public Human3 getPartner() { + return partner; + } - public void setPartner(Human3 partner) { - this.partner = partner; - } + public void setPartner(Human3 partner) { + this.partner = partner; + } - public Human3 getBankAccountOwner() { - return bankAccountOwner; - } + public Human3 getBankAccountOwner() { + return bankAccountOwner; + } - public void setBankAccountOwner(Human3 bankAccountOwner) { - this.bankAccountOwner = bankAccountOwner; - } + public void setBankAccountOwner(Human3 bankAccountOwner) { + this.bankAccountOwner = bankAccountOwner; + } - public List<Human3> getChildren() { - return children; - } + public List<Human3> getChildren() { + return children; + } - public void setChildren(List<Human3> children) { - this.children = children; - } + public void setChildren(List<Human3> children) { + this.children = children; + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/HumanTest.java b/src/test/java/org/yaml/snakeyaml/recursive/HumanTest.java index eab247e1..5cd70c24 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/HumanTest.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/HumanTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive; @@ -24,635 +22,640 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.representer.Representer; public class HumanTest extends TestCase { - public void testNoChildren() { - Human father = new Human(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - Human mother = new Human(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - Yaml yaml = new Yaml(); - String output = yaml.dump(father); - String etalon = Util.getLocalResource("recursive/no-children-1.yaml"); - assertEquals(etalon, output); - // - Human father2 = (Human) yaml.load(output); - assertNotNull(father2); - assertEquals("Father", father2.getName()); - assertEquals("Mother", father2.getPartner().getName()); - assertEquals("Father", father2.getBankAccountOwner().getName()); - assertSame(father2, father2.getBankAccountOwner()); + public void testNoChildren() { + Human father = new Human(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + Human mother = new Human(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + Yaml yaml = new Yaml(); + String output = yaml.dump(father); + String etalon = Util.getLocalResource("recursive/no-children-1.yaml"); + assertEquals(etalon, output); + // + Human father2 = yaml.load(output); + assertNotNull(father2); + assertEquals("Father", father2.getName()); + assertEquals("Mother", father2.getPartner().getName()); + assertEquals("Father", father2.getBankAccountOwner().getName()); + assertSame(father2, father2.getBankAccountOwner()); + } + + public void testNoChildrenPretty() { + Human father = new Human(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + Human mother = new Human(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + DumperOptions options = new DumperOptions(); + options.setPrettyFlow(true); + options.setDefaultFlowStyle(FlowStyle.FLOW); + Yaml yaml = new Yaml(options); + String output = yaml.dump(father); + String etalon = Util.getLocalResource("recursive/no-children-1-pretty.yaml"); + assertEquals(etalon, output); + // + Human father2 = yaml.load(output); + assertNotNull(father2); + assertEquals("Father", father2.getName()); + assertEquals("Mother", father2.getPartner().getName()); + assertEquals("Father", father2.getBankAccountOwner().getName()); + assertSame(father2, father2.getBankAccountOwner()); + } + + public void testChildren() { + Human father = new Human(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + Human mother = new Human(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + Human son = new Human(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + Human daughter = new Human(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + Set<Human> children = new LinkedHashSet<Human>(2); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + Yaml beanDumper = new Yaml(); + String output = beanDumper.dumpAsMap(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-children.yaml"); + assertEquals(etalon, output); + TypeDescription humanDescription = new TypeDescription(Human.class); + humanDescription.putMapPropertyType("children", Human.class, Object.class); + + LoaderOptions loaderOptions = new LoaderOptions(); + loaderOptions.setAllowRecursiveKeys(true); + Yaml beanLoader = new Yaml(new Constructor(humanDescription, loaderOptions)); + // + Human son2 = beanLoader.loadAs(output, Human.class); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + Human father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + Set<Human> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + // check if type descriptor was correct + assertSame(Human.class, child.getClass()); } - public void testNoChildrenPretty() { - Human father = new Human(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - Human mother = new Human(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - DumperOptions options = new DumperOptions(); - options.setPrettyFlow(true); - options.setDefaultFlowStyle(FlowStyle.FLOW); - Yaml yaml = new Yaml(options); - String output = yaml.dump(father); - String etalon = Util.getLocalResource("recursive/no-children-1-pretty.yaml"); - assertEquals(etalon, output); - // - Human father2 = (Human) yaml.load(output); - assertNotNull(father2); - assertEquals("Father", father2.getName()); - assertEquals("Mother", father2.getPartner().getName()); - assertEquals("Father", father2.getBankAccountOwner().getName()); - assertSame(father2, father2.getBankAccountOwner()); + // check if hashCode is correct + validateSet(children2); + } + + public void testChildrenPretty() { + Human father = new Human(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + Human mother = new Human(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + Human son = new Human(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + Human daughter = new Human(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + Set<Human> children = new LinkedHashSet<Human>(2); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.FLOW); + options.setPrettyFlow(true); + Yaml beanDumper = new Yaml(options); + String output = beanDumper.dump(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-children-pretty.yaml"); + assertEquals(etalon, output); + TypeDescription humanDescription = new TypeDescription(Human.class); + humanDescription.putMapPropertyType("children", Human.class, Object.class); + + LoaderOptions loaderOptions = new LoaderOptions(); + loaderOptions.setAllowRecursiveKeys(true); + Yaml beanLoader = new Yaml(new Constructor(humanDescription, loaderOptions)); + // + Human son2 = beanLoader.loadAs(output, Human.class); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + Human father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + Set<Human> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + // check if type descriptor was correct + assertSame(Human.class, child.getClass()); } - public void testChildren() { - Human father = new Human(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - Human mother = new Human(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - Human son = new Human(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - Human daughter = new Human(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - Set<Human> children = new LinkedHashSet<Human>(2); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - Yaml beanDumper = new Yaml(); - String output = beanDumper.dumpAsMap(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-children.yaml"); - assertEquals(etalon, output); - TypeDescription humanDescription = new TypeDescription(Human.class); - humanDescription.putMapPropertyType("children", Human.class, Object.class); - Yaml beanLoader = new Yaml(new Constructor(humanDescription)); - // - Human son2 = beanLoader.loadAs(output, Human.class); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - Human father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - Set<Human> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - // check if type descriptor was correct - assertSame(Human.class, child.getClass()); - } - - // check if hashCode is correct - validateSet(children2); + // check if hashCode is correct + validateSet(children2); + } + + public void testChildren2() { + Human2 father = new Human2(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + Human2 mother = new Human2(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + Human2 son = new Human2(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + Human2 daughter = new Human2(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + HashMap<Human2, String> children = new LinkedHashMap<Human2, String>(2); + children.put(son, "son"); + children.put(daughter, "daughter"); + father.setChildren(children); + mother.setChildren(children); + // + + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Constructor constructor = new Constructor(Human2.class, options); + TypeDescription humanDescription = new TypeDescription(Human2.class); + humanDescription.putMapPropertyType("children", Human2.class, String.class); + constructor.addTypeDescription(humanDescription); + + Yaml yaml = new Yaml(constructor, new Representer(), new DumperOptions(), options); + String output = yaml.dump(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-children-2.yaml"); + assertEquals(etalon, output); + // + Human2 son2 = yaml.load(output); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + Human2 father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + Map<Human2, String> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + validateMapKeys(children2); + } + + public void testChildren3() { + Human3 father = new Human3(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + Human3 mother = new Human3(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + Human3 son = new Human3(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + Human3 daughter = new Human3(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + ArrayList<Human3> children = new ArrayList<Human3>(); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + + Constructor constructor = new Constructor(Human3.class); + TypeDescription Human3Description = new TypeDescription(Human3.class); + Human3Description.putListPropertyType("children", Human3.class); + constructor.addTypeDescription(Human3Description); + + Yaml yaml = new Yaml(constructor); + String output = yaml.dump(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-children-3.yaml"); + assertEquals(etalon, output); + // + Human3 son2 = yaml.load(output); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + Human3 father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + List<Human3> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + // check if type descriptor was correct + assertSame(Human3.class, child.getClass()); } - - public void testChildrenPretty() { - Human father = new Human(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - Human mother = new Human(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - Human son = new Human(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - Human daughter = new Human(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - Set<Human> children = new LinkedHashSet<Human>(2); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.FLOW); - options.setPrettyFlow(true); - Yaml beanDumper = new Yaml(options); - String output = beanDumper.dump(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-children-pretty.yaml"); - assertEquals(etalon, output); - TypeDescription humanDescription = new TypeDescription(Human.class); - humanDescription.putMapPropertyType("children", Human.class, Object.class); - Yaml beanLoader = new Yaml(new Constructor(humanDescription)); - // - Human son2 = beanLoader.loadAs(output, Human.class); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - Human father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - Set<Human> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - // check if type descriptor was correct - assertSame(Human.class, child.getClass()); - } - - // check if hashCode is correct - validateSet(children2); + } + + /* + * Loads same structure as created in testChildren. But root object is set of children + */ + @SuppressWarnings("unchecked") + public void testChildrenSetAsRoot() { + String etalon = Util.getLocalResource("recursive/with-children-as-set.yaml"); + + Constructor constructor = new Constructor(); + TypeDescription humanDescription = new TypeDescription(Human.class); + humanDescription.putMapPropertyType("children", Human.class, Object.class); + constructor.addTypeDescription(humanDescription); + + Yaml yaml = new Yaml(constructor); + Set<Human> children2 = yaml.load(etalon); + assertNotNull(children2); + assertEquals(2, children2.size()); + + Human firstChild = children2.iterator().next(); + + Human father2 = firstChild.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", firstChild.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), firstChild.getMother()); + assertSame(father2, firstChild.getMother().getPartner()); + + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + // check if type descriptor was correct + assertSame(Human.class, child.getClass()); } - public void testChildren2() { - Human2 father = new Human2(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - Human2 mother = new Human2(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - Human2 son = new Human2(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - Human2 daughter = new Human2(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - HashMap<Human2, String> children = new LinkedHashMap<Human2, String>(2); - children.put(son, "son"); - children.put(daughter, "daughter"); - father.setChildren(children); - mother.setChildren(children); - // - - Constructor constructor = new Constructor(Human2.class); - TypeDescription humanDescription = new TypeDescription(Human2.class); - humanDescription.putMapPropertyType("children", Human2.class, String.class); - constructor.addTypeDescription(humanDescription); - - Yaml yaml = new Yaml(constructor); - String output = yaml.dump(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-children-2.yaml"); - assertEquals(etalon, output); - // - Human2 son2 = (Human2) yaml.load(output); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - Human2 father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - Map<Human2, String> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - validateMapKeys(children2); + validateSet(children2); + } + + /* + * Loads same structure as created in testChildren. But root object is map of children + */ + @SuppressWarnings("unchecked") + public void testChildrenMapAsRoot() { + String etalon = Util.getLocalResource("recursive/with-children-as-map.yaml"); + + Constructor constructor = new Constructor(); + TypeDescription Human2Description = new TypeDescription(Human2.class); + Human2Description.putMapPropertyType("children", Human2.class, String.class); + constructor.addTypeDescription(Human2Description); + + Yaml yaml = new Yaml(constructor); + Map<Human2, String> children2 = yaml.load(etalon); + assertNotNull(children2); + assertEquals(2, children2.size()); + + Entry<Human2, String> firstEntry = children2.entrySet().iterator().next(); + Human2 firstChild = firstEntry.getKey(); + + Human2 father2 = firstChild.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", firstChild.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), firstChild.getMother()); + assertSame(father2, firstChild.getMother().getPartner()); + + assertSame(father2.getPartner().getChildren(), children2); + + validateMapKeys(children2); + } + + /* + * Loads same structure as created in testChildren. But root object is list of children + */ + @SuppressWarnings("unchecked") + public void testChildrenListRoot() { + Human3 father = new Human3(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + Human3 mother = new Human3(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + Human3 son = new Human3(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + Human3 daughter = new Human3(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + ArrayList<Human3> children = new ArrayList<Human3>(); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + + Constructor constructor = new Constructor(); + TypeDescription Human3Description = new TypeDescription(Human3.class); + Human3Description.putListPropertyType("children", Human3.class); + constructor.addTypeDescription(Human3Description); + + Yaml yaml = new Yaml(constructor); + String output = yaml.dump(father.getChildren()); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-children-as-list.yaml"); + assertEquals(etalon, output); + // + List<Human3> children2 = yaml.load(output); + assertNotNull(children2); + Human3 son2 = children2.iterator().next(); + assertEquals(2, children2.size()); + + Human3 father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + // check if type descriptor was correct + assertSame(Human3.class, child.getClass()); } - - public void testChildren3() { - Human3 father = new Human3(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - Human3 mother = new Human3(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - Human3 son = new Human3(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - Human3 daughter = new Human3(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - ArrayList<Human3> children = new ArrayList<Human3>(); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - - Constructor constructor = new Constructor(Human3.class); - TypeDescription Human3Description = new TypeDescription(Human3.class); - Human3Description.putListPropertyType("children", Human3.class); - constructor.addTypeDescription(Human3Description); - - Yaml yaml = new Yaml(constructor); - String output = yaml.dump(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-children-3.yaml"); - assertEquals(etalon, output); - // - Human3 son2 = (Human3) yaml.load(output); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - Human3 father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - List<Human3> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - // check if type descriptor was correct - assertSame(Human3.class, child.getClass()); - } + } + + public void testBeanRing() { + Human man1 = new Human(); + man1.setName("Man 1"); + Human man2 = new Human(); + man2.setName("Man 2"); + Human man3 = new Human(); + man3.setName("Man 3"); + man1.setBankAccountOwner(man2); + man2.setBankAccountOwner(man3); + man3.setBankAccountOwner(man1); + // + Yaml yaml = new Yaml(); + String output = yaml.dump(man1); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/beanring-3.yaml"); + assertEquals(etalon, output); + // + Human loadedMan1 = yaml.load(output); + assertNotNull(loadedMan1); + assertEquals("Man 1", loadedMan1.getName()); + Human loadedMan2 = loadedMan1.getBankAccountOwner(); + Human loadedMan3 = loadedMan2.getBankAccountOwner(); + assertSame(loadedMan1, loadedMan3.getBankAccountOwner()); + } + + public void qtestCollectionRing() { + // Set<Object> set = new HashSet<Object>(); + // List<Object> list = new ArrayList<Object>(); + // Map<Object, Object> map = new HashMap<Object, Object>(); + // set.add(list); + // list.add(map); + // map.put("1", set); + // // + // try { + // Yaml yaml = new Yaml(); + // String output = yaml.dump(set); + // // String etalon = Util.getLocalResource("recursive/???.yaml"); + // // assertEquals(etalon, output); + // // + // // Set<Object> loadedSet = (Set<Object>) yaml.load(output); + // } catch (StackOverflowError e) { + // fail("Cannot dump recursive collections."); + // } + } + + /** + * Checks if object was put into the set after full construction. So the hashCode was calculated + * correctly (if it depends on internal object's state). + * + * @param set + */ + private void validateSet(Set<?> set) { + for (Object object : set) { + assertTrue(set.contains(object)); } - - /* - * Loads same structure as created in testChildren. But root object is set - * of children - */ - @SuppressWarnings("unchecked") - public void testChildrenSetAsRoot() { - String etalon = Util.getLocalResource("recursive/with-children-as-set.yaml"); - - Constructor constructor = new Constructor(); - TypeDescription humanDescription = new TypeDescription(Human.class); - humanDescription.putMapPropertyType("children", Human.class, Object.class); - constructor.addTypeDescription(humanDescription); - - Yaml yaml = new Yaml(constructor); - Set<Human> children2 = (Set<Human>) yaml.load(etalon); - assertNotNull(children2); - assertEquals(2, children2.size()); - - Human firstChild = children2.iterator().next(); - - Human father2 = firstChild.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", firstChild.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), firstChild.getMother()); - assertSame(father2, firstChild.getMother().getPartner()); - - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - // check if type descriptor was correct - assertSame(Human.class, child.getClass()); - } - - validateSet(children2); + } + + /** + * Checks if object was put into the map as key after full construction. So the hashCode was + * calculated correctly (if it depends on internal object's state). + * + * @param map + */ + private void validateMapKeys(Map<?, ?> map) { + for (Map.Entry<?, ?> entry : map.entrySet()) { + assertTrue(map.containsKey(entry.getKey())); } - - /* - * Loads same structure as created in testChildren. But root object is map - * of children - */ - @SuppressWarnings("unchecked") - public void testChildrenMapAsRoot() { - String etalon = Util.getLocalResource("recursive/with-children-as-map.yaml"); - - Constructor constructor = new Constructor(); - TypeDescription Human2Description = new TypeDescription(Human2.class); - Human2Description.putMapPropertyType("children", Human2.class, String.class); - constructor.addTypeDescription(Human2Description); - - Yaml yaml = new Yaml(constructor); - Map<Human2, String> children2 = (Map<Human2, String>) yaml.load(etalon); - assertNotNull(children2); - assertEquals(2, children2.size()); - - Entry<Human2, String> firstEntry = children2.entrySet().iterator().next(); - Human2 firstChild = firstEntry.getKey(); - - Human2 father2 = firstChild.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", firstChild.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), firstChild.getMother()); - assertSame(father2, firstChild.getMother().getPartner()); - - assertSame(father2.getPartner().getChildren(), children2); - - validateMapKeys(children2); - } - - /* - * Loads same structure as created in testChildren. But root object is list - * of children - */ - @SuppressWarnings("unchecked") - public void testChildrenListRoot() { - Human3 father = new Human3(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - Human3 mother = new Human3(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - Human3 son = new Human3(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - Human3 daughter = new Human3(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - ArrayList<Human3> children = new ArrayList<Human3>(); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - - Constructor constructor = new Constructor(); - TypeDescription Human3Description = new TypeDescription(Human3.class); - Human3Description.putListPropertyType("children", Human3.class); - constructor.addTypeDescription(Human3Description); - - Yaml yaml = new Yaml(constructor); - String output = yaml.dump(father.getChildren()); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-children-as-list.yaml"); - assertEquals(etalon, output); - // - List<Human3> children2 = (List<Human3>) yaml.load(output); - assertNotNull(children2); - Human3 son2 = children2.iterator().next(); - assertEquals(2, children2.size()); - - Human3 father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - // check if type descriptor was correct - assertSame(Human3.class, child.getClass()); - } + } + + public void testChildrenWithoutRootTag() { + Human father = new Human(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + Human mother = new Human(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + Human son = new Human(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + Human daughter = new Human(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + Set<Human> children = new LinkedHashSet<Human>(2); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + Yaml beanDumper = new Yaml(); + String output = beanDumper.dumpAsMap(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-children-no-root-tag.yaml"); + assertEquals(etalon, output); + TypeDescription humanDescription = new TypeDescription(Human.class); + humanDescription.putMapPropertyType("children", Human.class, Object.class); + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Yaml beanLoader = new Yaml(new Constructor(humanDescription, options)); + // + Human son2 = beanLoader.loadAs(output, Human.class); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + Human father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + Set<Human> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + // check if type descriptor was correct + assertSame(Human.class, child.getClass()); } - public void testBeanRing() { - Human man1 = new Human(); - man1.setName("Man 1"); - Human man2 = new Human(); - man2.setName("Man 2"); - Human man3 = new Human(); - man3.setName("Man 3"); - man1.setBankAccountOwner(man2); - man2.setBankAccountOwner(man3); - man3.setBankAccountOwner(man1); - // - Yaml yaml = new Yaml(); - String output = yaml.dump(man1); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/beanring-3.yaml"); - assertEquals(etalon, output); - // - Human loadedMan1 = (Human) yaml.load(output); - assertNotNull(loadedMan1); - assertEquals("Man 1", loadedMan1.getName()); - Human loadedMan2 = loadedMan1.getBankAccountOwner(); - Human loadedMan3 = loadedMan2.getBankAccountOwner(); - assertSame(loadedMan1, loadedMan3.getBankAccountOwner()); - } - - public void qtestCollectionRing() { - // Set<Object> set = new HashSet<Object>(); - // List<Object> list = new ArrayList<Object>(); - // Map<Object, Object> map = new HashMap<Object, Object>(); - // set.add(list); - // list.add(map); - // map.put("1", set); - // // - // try { - // Yaml yaml = new Yaml(); - // String output = yaml.dump(set); - // // String etalon = Util.getLocalResource("recursive/???.yaml"); - // // assertEquals(etalon, output); - // // - // // Set<Object> loadedSet = (Set<Object>) yaml.load(output); - // } catch (StackOverflowError e) { - // fail("Cannot dump recursive collections."); - // } - } - - /** - * Checks if object was put into the set after full construction. So the - * hashCode was calculated correctly (if it depends on internal object's - * state). - * - * @param set - */ - private void validateSet(Set<?> set) { - for (Object object : set) { - assertTrue(set.contains(object)); - } - } - - /** - * Checks if object was put into the map as key after full construction. So - * the hashCode was calculated correctly (if it depends on internal object's - * state). - * - * @param map - */ - private void validateMapKeys(Map<?, ?> map) { - for (Map.Entry<?, ?> entry : map.entrySet()) { - assertTrue(map.containsKey(entry.getKey())); - } - } - - public void testChildrenWithoutRootTag() { - Human father = new Human(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - Human mother = new Human(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - Human son = new Human(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - Human daughter = new Human(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - Set<Human> children = new LinkedHashSet<Human>(2); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - Yaml beanDumper = new Yaml(); - String output = beanDumper.dumpAsMap(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-children-no-root-tag.yaml"); - assertEquals(etalon, output); - TypeDescription humanDescription = new TypeDescription(Human.class); - humanDescription.putMapPropertyType("children", Human.class, Object.class); - Yaml beanLoader = new Yaml(new Constructor(humanDescription)); - // - Human son2 = beanLoader.loadAs(output, Human.class); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - Human father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - Set<Human> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - // check if type descriptor was correct - assertSame(Human.class, child.getClass()); - } - - // check if hashCode is correct - validateSet(children2); - } + // check if hashCode is correct + validateSet(children2); + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/Human_WithArrayOfChildrenTest.java b/src/test/java/org/yaml/snakeyaml/recursive/Human_WithArrayOfChildrenTest.java index b0d013c3..71db4d3e 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/Human_WithArrayOfChildrenTest.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/Human_WithArrayOfChildrenTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive; import java.util.Date; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -26,158 +22,158 @@ import org.yaml.snakeyaml.constructor.Constructor; public class Human_WithArrayOfChildrenTest extends TestCase { - public static class Human_WithArrayOfChildren extends AbstractHuman { - - private Human_WithArrayOfChildren father; - private Human_WithArrayOfChildren mother; - private Human_WithArrayOfChildren partner; - private Human_WithArrayOfChildren bankAccountOwner; - protected Human_WithArrayOfChildren[] children; - - public Human_WithArrayOfChildren() { - children = new Human_WithArrayOfChildren[0]; - } - - public Human_WithArrayOfChildren getFather() { - return father; - } - - public void setFather(Human_WithArrayOfChildren father) { - this.father = father; - } - - public Human_WithArrayOfChildren getMother() { - return mother; - } + public static class Human_WithArrayOfChildren extends AbstractHuman { - public void setMother(Human_WithArrayOfChildren mother) { - this.mother = mother; - } + private Human_WithArrayOfChildren father; + private Human_WithArrayOfChildren mother; + private Human_WithArrayOfChildren partner; + private Human_WithArrayOfChildren bankAccountOwner; + protected Human_WithArrayOfChildren[] children; - public Human_WithArrayOfChildren getPartner() { - return partner; - } + public Human_WithArrayOfChildren() { + children = new Human_WithArrayOfChildren[0]; + } - public void setPartner(Human_WithArrayOfChildren partner) { - this.partner = partner; - } + public Human_WithArrayOfChildren getFather() { + return father; + } - public Human_WithArrayOfChildren getBankAccountOwner() { - return bankAccountOwner; - } + public void setFather(Human_WithArrayOfChildren father) { + this.father = father; + } - public void setBankAccountOwner(Human_WithArrayOfChildren bankAccountOwner) { - this.bankAccountOwner = bankAccountOwner; - } + public Human_WithArrayOfChildren getMother() { + return mother; + } - public Human_WithArrayOfChildren[] getChildren() { - return children; - } + public void setMother(Human_WithArrayOfChildren mother) { + this.mother = mother; + } - public void setChildren(Human_WithArrayOfChildren[] children) { - this.children = children; - } + public Human_WithArrayOfChildren getPartner() { + return partner; + } + public void setPartner(Human_WithArrayOfChildren partner) { + this.partner = partner; } - private Human_WithArrayOfChildren createSon() { - Human_WithArrayOfChildren father = new Human_WithArrayOfChildren(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - Human_WithArrayOfChildren mother = new Human_WithArrayOfChildren(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - Human_WithArrayOfChildren son = new Human_WithArrayOfChildren(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - Human_WithArrayOfChildren daughter = new Human_WithArrayOfChildren(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - Human_WithArrayOfChildren[] children = new Human_WithArrayOfChildren[] { son, daughter }; - father.setChildren(children); - mother.setChildren(children); - // - return son; + public Human_WithArrayOfChildren getBankAccountOwner() { + return bankAccountOwner; } - private void checkSon(Human_WithArrayOfChildren son) { - assertNotNull(son); - assertEquals("Son", son.getName()); - - Human_WithArrayOfChildren father2 = son.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son.getMother()); - assertSame(father2, son.getMother().getPartner()); - - Human_WithArrayOfChildren[] fathersChildren = father2.getChildren(); - assertEquals(2, fathersChildren.length); - Human_WithArrayOfChildren[] mothersChildren = father2.getPartner().getChildren(); - assertEquals(2, mothersChildren.length); - assertSame(mothersChildren, fathersChildren); - - for (Object child : fathersChildren) { - // check if type descriptor was correct - assertSame(Human_WithArrayOfChildren.class, child.getClass()); - } + public void setBankAccountOwner(Human_WithArrayOfChildren bankAccountOwner) { + this.bankAccountOwner = bankAccountOwner; } - public void testChildrenArray() { - Constructor constructor = new Constructor(Human_WithArrayOfChildren.class); - TypeDescription HumanWithChildrenArrayDescription = new TypeDescription( - Human_WithArrayOfChildren.class); - HumanWithChildrenArrayDescription.putListPropertyType("children", - Human_WithArrayOfChildren.class); - constructor.addTypeDescription(HumanWithChildrenArrayDescription); - Human_WithArrayOfChildren son = createSon(); - Yaml yaml = new Yaml(constructor); - String output = yaml.dump(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-childrenArray.yaml"); - assertEquals(etalon, output); - // - Human_WithArrayOfChildren son2 = (Human_WithArrayOfChildren) yaml.load(output); - checkSon(son2); + public Human_WithArrayOfChildren[] getChildren() { + return children; } - public void testDumpChildrenArrayWithoutRootTag() { - Yaml yaml = new Yaml(); - Human_WithArrayOfChildren son = createSon(); - String output = yaml.dumpAsMap(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/with-childrenArray-no-root-tag.yaml"); - assertEquals(etalon, output); + public void setChildren(Human_WithArrayOfChildren[] children) { + this.children = children; } - public void testParseChildrenArrayWithoutRootTag() { - Constructor constructor = new Constructor(Human_WithArrayOfChildren.class); - TypeDescription HumanWithChildrenArrayDescription = new TypeDescription( - Human_WithArrayOfChildren.class); - HumanWithChildrenArrayDescription.putListPropertyType("children", - Human_WithArrayOfChildren.class); - constructor.addTypeDescription(HumanWithChildrenArrayDescription); - Yaml yaml = new Yaml(constructor); - String doc = Util.getLocalResource("recursive/with-childrenArray-no-root-tag.yaml"); - Human_WithArrayOfChildren son2 = (Human_WithArrayOfChildren) yaml.load(doc); - checkSon(son2); + } + + private Human_WithArrayOfChildren createSon() { + Human_WithArrayOfChildren father = new Human_WithArrayOfChildren(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + Human_WithArrayOfChildren mother = new Human_WithArrayOfChildren(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + Human_WithArrayOfChildren son = new Human_WithArrayOfChildren(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + Human_WithArrayOfChildren daughter = new Human_WithArrayOfChildren(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + Human_WithArrayOfChildren[] children = new Human_WithArrayOfChildren[] {son, daughter}; + father.setChildren(children); + mother.setChildren(children); + // + return son; + } + + private void checkSon(Human_WithArrayOfChildren son) { + assertNotNull(son); + assertEquals("Son", son.getName()); + + Human_WithArrayOfChildren father2 = son.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son.getMother()); + assertSame(father2, son.getMother().getPartner()); + + Human_WithArrayOfChildren[] fathersChildren = father2.getChildren(); + assertEquals(2, fathersChildren.length); + Human_WithArrayOfChildren[] mothersChildren = father2.getPartner().getChildren(); + assertEquals(2, mothersChildren.length); + assertSame(mothersChildren, fathersChildren); + + for (Object child : fathersChildren) { + // check if type descriptor was correct + assertSame(Human_WithArrayOfChildren.class, child.getClass()); } + } + + public void testChildrenArray() { + Constructor constructor = new Constructor(Human_WithArrayOfChildren.class); + TypeDescription HumanWithChildrenArrayDescription = + new TypeDescription(Human_WithArrayOfChildren.class); + HumanWithChildrenArrayDescription.putListPropertyType("children", + Human_WithArrayOfChildren.class); + constructor.addTypeDescription(HumanWithChildrenArrayDescription); + Human_WithArrayOfChildren son = createSon(); + Yaml yaml = new Yaml(constructor); + String output = yaml.dump(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-childrenArray.yaml"); + assertEquals(etalon, output); + // + Human_WithArrayOfChildren son2 = yaml.load(output); + checkSon(son2); + } + + public void testDumpChildrenArrayWithoutRootTag() { + Yaml yaml = new Yaml(); + Human_WithArrayOfChildren son = createSon(); + String output = yaml.dumpAsMap(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/with-childrenArray-no-root-tag.yaml"); + assertEquals(etalon, output); + } + + public void testParseChildrenArrayWithoutRootTag() { + Constructor constructor = new Constructor(Human_WithArrayOfChildren.class); + TypeDescription HumanWithChildrenArrayDescription = + new TypeDescription(Human_WithArrayOfChildren.class); + HumanWithChildrenArrayDescription.putListPropertyType("children", + Human_WithArrayOfChildren.class); + constructor.addTypeDescription(HumanWithChildrenArrayDescription); + Yaml yaml = new Yaml(constructor); + String doc = Util.getLocalResource("recursive/with-childrenArray-no-root-tag.yaml"); + Human_WithArrayOfChildren son2 = yaml.load(doc); + checkSon(son2); + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/generics/AbstractHumanGen.java b/src/test/java/org/yaml/snakeyaml/recursive/generics/AbstractHumanGen.java index 8a6a01bc..3265a382 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/generics/AbstractHumanGen.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/generics/AbstractHumanGen.java @@ -1,94 +1,93 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive.generics; import java.util.Date; public abstract class AbstractHumanGen<T, K extends AbstractHumanGen<T, ?>> { - private String name; - private Date birthday; - private String birthPlace; - private K father; - private K mother; - private K partner; - private K bankAccountOwner; - protected T children; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Date getBirthday() { - return birthday; - } - - public void setBirthday(Date birthday) { - this.birthday = birthday; - } - - public String getBirthPlace() { - return birthPlace; - } - - public K getFather() { - return father; - } - - public void setFather(K father) { - this.father = father; - } - - public K getMother() { - return mother; - } - - public void setMother(K mother) { - this.mother = mother; - } - - public void setBirthPlace(String birthPlace) { - this.birthPlace = birthPlace; - } - - public T getChildren() { - return children; - } - - public void setChildren(T children) { - this.children = children; - } - - public K getPartner() { - return partner; - } - - public void setPartner(K partner) { - this.partner = partner; - } - - public K getBankAccountOwner() { - return bankAccountOwner; - } - - public void setBankAccountOwner(K bankAccountOwner) { - this.bankAccountOwner = bankAccountOwner; - } + + private String name; + private Date birthday; + private String birthPlace; + private K father; + private K mother; + private K partner; + private K bankAccountOwner; + protected T children; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getBirthday() { + return birthday; + } + + public void setBirthday(Date birthday) { + this.birthday = birthday; + } + + public String getBirthPlace() { + return birthPlace; + } + + public K getFather() { + return father; + } + + public void setFather(K father) { + this.father = father; + } + + public K getMother() { + return mother; + } + + public void setMother(K mother) { + this.mother = mother; + } + + public void setBirthPlace(String birthPlace) { + this.birthPlace = birthPlace; + } + + public T getChildren() { + return children; + } + + public void setChildren(T children) { + this.children = children; + } + + public K getPartner() { + return partner; + } + + public void setPartner(K partner) { + this.partner = partner; + } + + public K getBankAccountOwner() { + return bankAccountOwner; + } + + public void setBankAccountOwner(K bankAccountOwner) { + this.bankAccountOwner = bankAccountOwner; + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen.java b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen.java index bf14d47a..3c745aa7 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive.generics; @@ -19,7 +17,8 @@ import java.util.LinkedHashSet; import java.util.Set; public class HumanGen extends AbstractHumanGen<Set<HumanGen>, HumanGen> { - public HumanGen() { - children = new LinkedHashSet<HumanGen>(); - } + + public HumanGen() { + children = new LinkedHashSet<HumanGen>(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen2.java b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen2.java index 0045680b..f6857e75 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen2.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen2.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive.generics; @@ -20,7 +18,7 @@ import java.util.Map; public class HumanGen2 extends AbstractHumanGen<Map<HumanGen2, String>, HumanGen2> { - public HumanGen2() { - children = new HashMap<HumanGen2, String>(); - } + public HumanGen2() { + children = new HashMap<HumanGen2, String>(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen3.java b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen3.java index b05d1367..8c3529de 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen3.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGen3.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive.generics; @@ -20,7 +18,7 @@ import java.util.List; public class HumanGen3 extends AbstractHumanGen<List<HumanGen3>, HumanGen3> { - public HumanGen3() { - children = new ArrayList<HumanGen3>(); - } + public HumanGen3() { + children = new ArrayList<HumanGen3>(); + } } diff --git a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGenericsTest.java b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGenericsTest.java index 5bc1a0e6..eac51023 100644 --- a/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGenericsTest.java +++ b/src/test/java/org/yaml/snakeyaml/recursive/generics/HumanGenericsTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.recursive.generics; @@ -26,474 +24,447 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.generics.GenericsBugDetector; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; public class HumanGenericsTest extends TestCase { - public void testNoChildren() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - HumanGen father = new HumanGen(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - HumanGen mother = new HumanGen(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - Yaml yaml = new Yaml(); - String output = yaml.dump(father); - String etalon = Util.getLocalResource("recursive/generics/no-children-1.yaml"); - assertEquals(etalon, output); - // - HumanGen father2 = (HumanGen) yaml.load(output); - assertNotNull(father2); - assertEquals("Father", father2.getName()); - assertEquals("Mother", father2.getPartner().getName()); - assertEquals("Father", father2.getBankAccountOwner().getName()); - assertSame(father2, father2.getBankAccountOwner()); - } - - /** - * the YAML document should contain no global tags - * - * @throws IntrospectionException - */ - public void testNoChildren2() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - HumanGen father = new HumanGen(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - HumanGen mother = new HumanGen(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - Yaml yaml = new Yaml(); - String output = yaml.dumpAsMap(father); - String etalon = Util.getLocalResource("recursive/generics/no-children-2.yaml"); - assertEquals(etalon, output); - // - Yaml loader = new Yaml(); - HumanGen father2 = (HumanGen) loader.loadAs(etalon, HumanGen.class); - assertNotNull(father2); - assertEquals("Father", father2.getName()); - assertEquals("Mother", father2.getPartner().getName()); - assertEquals("Father", father2.getBankAccountOwner().getName()); - assertSame(father2, father2.getBankAccountOwner()); - } - - public void testChildren() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - HumanGen father = new HumanGen(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - HumanGen mother = new HumanGen(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - HumanGen son = new HumanGen(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - HumanGen daughter = new HumanGen(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - Set<HumanGen> children = new LinkedHashSet<HumanGen>(2); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - - Constructor constructor = new Constructor(); - TypeDescription humanDescription = new TypeDescription(HumanGen.class); - humanDescription.putMapPropertyType("children", HumanGen.class, Object.class); - constructor.addTypeDescription(humanDescription); - - Yaml yaml = new Yaml(constructor); - String output = yaml.dump(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/generics/with-children.yaml"); - assertEquals(etalon, output); - // - HumanGen son2 = (HumanGen) yaml.load(output); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - HumanGen father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - Set<HumanGen> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - assertSame(HumanGen.class, child.getClass()); // check if type - // descriptor was correct - } - } - - public void testChildren2() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - HumanGen2 father = new HumanGen2(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - HumanGen2 mother = new HumanGen2(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - HumanGen2 son = new HumanGen2(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - HumanGen2 daughter = new HumanGen2(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - HashMap<HumanGen2, String> children = new LinkedHashMap<HumanGen2, String>(2); - children.put(son, "son"); - children.put(daughter, "daughter"); - father.setChildren(children); - mother.setChildren(children); - // - Representer representer = new Representer(); - representer.addClassTag(HumanGen2.class, Tag.MAP); - Yaml yaml = new Yaml(representer); - String output = yaml.dump(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/generics/with-children-2.yaml"); - assertEquals(etalon, output); - // load - TypeDescription humanDescription = new TypeDescription(HumanGen2.class); - humanDescription.putMapPropertyType("children", HumanGen2.class, String.class); - Yaml beanLoader = new Yaml(new Constructor(humanDescription)); - // - HumanGen2 son2 = beanLoader.loadAs(output, HumanGen2.class); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - HumanGen2 father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - Map<HumanGen2, String> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - } - - public void testChildren3() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - HumanGen3 father = new HumanGen3(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - HumanGen3 mother = new HumanGen3(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - HumanGen3 son = new HumanGen3(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - HumanGen3 daughter = new HumanGen3(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - ArrayList<HumanGen3> children = new ArrayList<HumanGen3>(); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - - Constructor constructor = new Constructor(); - TypeDescription Human3Description = new TypeDescription(HumanGen3.class); - Human3Description.putListPropertyType("children", HumanGen3.class); - constructor.addTypeDescription(Human3Description); - - Yaml yaml = new Yaml(constructor); - String output = yaml.dump(son); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/generics/with-children-3.yaml"); - assertEquals(etalon, output); - // - HumanGen3 son2 = (HumanGen3) yaml.load(output); - assertNotNull(son2); - assertEquals("Son", son.getName()); - - HumanGen3 father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - List<HumanGen3> children2 = father2.getChildren(); - assertEquals(2, children2.size()); - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - assertSame(HumanGen3.class, child.getClass()); // check if type - // descriptor was - // correct - } - } - - /* - * Loads same structure as created in testChildren. But root object is set - * of children - */ - @SuppressWarnings("unchecked") - public void testChildrenSetAsRoot() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - String etalon = Util.getLocalResource("recursive/generics/with-children-as-set.yaml"); - - Constructor constructor = new Constructor(); - TypeDescription humanDescription = new TypeDescription(HumanGen.class); - humanDescription.putMapPropertyType("children", HumanGen.class, Object.class); - constructor.addTypeDescription(humanDescription); - - Yaml yaml = new Yaml(constructor); - Set<HumanGen> children2 = (Set<HumanGen>) yaml.load(etalon); - assertNotNull(children2); - assertEquals(2, children2.size()); - - HumanGen firstChild = children2.iterator().next(); - - HumanGen father2 = firstChild.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", firstChild.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), firstChild.getMother()); - assertSame(father2, firstChild.getMother().getPartner()); - - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - assertSame(HumanGen.class, child.getClass()); // check if type - // descriptor was correct - } + public void testNoChildren() throws IOException, IntrospectionException { + HumanGen father = new HumanGen(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + HumanGen mother = new HumanGen(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + Yaml yaml = new Yaml(); + String output = yaml.dump(father); + String etalon = Util.getLocalResource("recursive/generics/no-children-1.yaml"); + assertEquals(etalon, output); + // + HumanGen father2 = yaml.load(output); + assertNotNull(father2); + assertEquals("Father", father2.getName()); + assertEquals("Mother", father2.getPartner().getName()); + assertEquals("Father", father2.getBankAccountOwner().getName()); + assertSame(father2, father2.getBankAccountOwner()); + } + + /** + * the YAML document should contain no global tags + * + * @throws IntrospectionException + */ + public void testNoChildren2() throws IOException, IntrospectionException { + HumanGen father = new HumanGen(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + HumanGen mother = new HumanGen(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + Yaml yaml = new Yaml(); + String output = yaml.dumpAsMap(father); + String etalon = Util.getLocalResource("recursive/generics/no-children-2.yaml"); + assertEquals(etalon, output); + // + Yaml loader = new Yaml(); + HumanGen father2 = loader.loadAs(etalon, HumanGen.class); + assertNotNull(father2); + assertEquals("Father", father2.getName()); + assertEquals("Mother", father2.getPartner().getName()); + assertEquals("Father", father2.getBankAccountOwner().getName()); + assertSame(father2, father2.getBankAccountOwner()); + } + + public void testChildren() throws IOException, IntrospectionException { + HumanGen father = new HumanGen(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + HumanGen mother = new HumanGen(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + HumanGen son = new HumanGen(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + HumanGen daughter = new HumanGen(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + Set<HumanGen> children = new LinkedHashSet<HumanGen>(2); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Constructor constructor = new Constructor(options); + TypeDescription humanDescription = new TypeDescription(HumanGen.class); + humanDescription.putMapPropertyType("children", HumanGen.class, Object.class); + constructor.addTypeDescription(humanDescription); + + Yaml yaml = new Yaml(constructor); + String output = yaml.dump(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/generics/with-children.yaml"); + assertEquals(etalon, output); + // + HumanGen son2 = yaml.load(output); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + HumanGen father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + Set<HumanGen> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + assertSame(HumanGen.class, child.getClass()); // check if type + // descriptor was correct } - - /* - * Loads same structure as created in testChildren. But root object is map - * of children - */ - @SuppressWarnings("unchecked") - public void testChildrenMapAsRoot() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - String etalon = Util.getLocalResource("recursive/generics/with-children-as-map.yaml"); - - Constructor constructor = new Constructor(); - TypeDescription Human2Description = new TypeDescription(HumanGen2.class); - Human2Description.putMapPropertyType("children", HumanGen2.class, String.class); - constructor.addTypeDescription(Human2Description); - - Yaml yaml = new Yaml(constructor); - Map<HumanGen2, String> children2 = (Map<HumanGen2, String>) yaml.load(etalon); - assertNotNull(children2); - assertEquals(2, children2.size()); - - Entry<HumanGen2, String> firstEntry = children2.entrySet().iterator().next(); - HumanGen2 firstChild = firstEntry.getKey(); - - HumanGen2 father2 = firstChild.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", firstChild.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), firstChild.getMother()); - assertSame(father2, firstChild.getMother().getPartner()); - - assertSame(father2.getPartner().getChildren(), children2); + } + + public void testChildren2() throws IOException, IntrospectionException { + HumanGen2 father = new HumanGen2(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + HumanGen2 mother = new HumanGen2(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + HumanGen2 son = new HumanGen2(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + HumanGen2 daughter = new HumanGen2(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + HashMap<HumanGen2, String> children = new LinkedHashMap<HumanGen2, String>(2); + children.put(son, "son"); + children.put(daughter, "daughter"); + father.setChildren(children); + mother.setChildren(children); + // + Representer representer = new Representer(); + representer.addClassTag(HumanGen2.class, Tag.MAP); + Yaml yaml = new Yaml(representer); + String output = yaml.dump(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/generics/with-children-2.yaml"); + assertEquals(etalon, output); + // load + TypeDescription humanDescription = new TypeDescription(HumanGen2.class); + humanDescription.putMapPropertyType("children", HumanGen2.class, String.class); + + LoaderOptions options = new LoaderOptions(); + options.setAllowRecursiveKeys(true); + Yaml beanLoader = new Yaml(new Constructor(humanDescription, options)); + // + HumanGen2 son2 = beanLoader.loadAs(output, HumanGen2.class); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + HumanGen2 father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + Map<HumanGen2, String> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + } + + public void testChildren3() throws IOException, IntrospectionException { + HumanGen3 father = new HumanGen3(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + HumanGen3 mother = new HumanGen3(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + HumanGen3 son = new HumanGen3(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + HumanGen3 daughter = new HumanGen3(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + ArrayList<HumanGen3> children = new ArrayList<HumanGen3>(); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + + Constructor constructor = new Constructor(); + TypeDescription Human3Description = new TypeDescription(HumanGen3.class); + Human3Description.putListPropertyType("children", HumanGen3.class); + constructor.addTypeDescription(Human3Description); + + Yaml yaml = new Yaml(constructor); + String output = yaml.dump(son); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/generics/with-children-3.yaml"); + assertEquals(etalon, output); + // + HumanGen3 son2 = yaml.load(output); + assertNotNull(son2); + assertEquals("Son", son.getName()); + + HumanGen3 father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + List<HumanGen3> children2 = father2.getChildren(); + assertEquals(2, children2.size()); + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + assertSame(HumanGen3.class, child.getClass()); // check if type + // descriptor was + // correct } - - /* - * Loads same structure as created in testChildren. But root object is list - * of children - */ - @SuppressWarnings("unchecked") - public void testChildrenListRoot() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - HumanGen3 father = new HumanGen3(); - father.setName("Father"); - father.setBirthday(new Date(1000000000)); - father.setBirthPlace("Leningrad"); - father.setBankAccountOwner(father); - // - HumanGen3 mother = new HumanGen3(); - mother.setName("Mother"); - mother.setBirthday(new Date(100000000000L)); - mother.setBirthPlace("Saint-Petersburg"); - father.setPartner(mother); - mother.setPartner(father); - mother.setBankAccountOwner(father); - // - HumanGen3 son = new HumanGen3(); - son.setName("Son"); - son.setBirthday(new Date(310000000000L)); - son.setBirthPlace("Munich"); - son.setBankAccountOwner(father); - son.setFather(father); - son.setMother(mother); - // - HumanGen3 daughter = new HumanGen3(); - daughter.setName("Daughter"); - daughter.setBirthday(new Date(420000000000L)); - daughter.setBirthPlace("New York"); - daughter.setBankAccountOwner(father); - daughter.setFather(father); - daughter.setMother(mother); - // - ArrayList<HumanGen3> children = new ArrayList<HumanGen3>(); - children.add(son); - children.add(daughter); - father.setChildren(children); - mother.setChildren(children); - // - - Constructor constructor = new Constructor(); - TypeDescription Human3Description = new TypeDescription(HumanGen3.class); - Human3Description.putListPropertyType("children", HumanGen3.class); - constructor.addTypeDescription(Human3Description); - - Yaml yaml = new Yaml(constructor); - String output = yaml.dump(father.getChildren()); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/generics/with-children-as-list.yaml"); - assertEquals(etalon, output); - // - List<HumanGen3> children2 = (List<HumanGen3>) yaml.load(output); - assertNotNull(children2); - HumanGen3 son2 = children2.iterator().next(); - assertEquals(2, children2.size()); - - HumanGen3 father2 = son2.getFather(); - assertEquals("Father", father2.getName()); - assertEquals("Mother", son2.getMother().getName()); - assertSame(father2, father2.getBankAccountOwner()); - assertSame(father2.getPartner(), son2.getMother()); - assertSame(father2, son2.getMother().getPartner()); - - assertSame(father2.getPartner().getChildren(), children2); - - for (Object child : children2) { - assertSame(HumanGen3.class, child.getClass()); // check if type - // descriptor was - // correct - } + } + + /* + * Loads same structure as created in testChildren. But root object is set of children + */ + @SuppressWarnings("unchecked") + public void testChildrenSetAsRoot() throws IOException, IntrospectionException { + String etalon = Util.getLocalResource("recursive/generics/with-children-as-set.yaml"); + + Constructor constructor = new Constructor(); + TypeDescription humanDescription = new TypeDescription(HumanGen.class); + humanDescription.putMapPropertyType("children", HumanGen.class, Object.class); + constructor.addTypeDescription(humanDescription); + + Yaml yaml = new Yaml(constructor); + Set<HumanGen> children2 = yaml.load(etalon); + assertNotNull(children2); + assertEquals(2, children2.size()); + + HumanGen firstChild = children2.iterator().next(); + + HumanGen father2 = firstChild.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", firstChild.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), firstChild.getMother()); + assertSame(father2, firstChild.getMother().getPartner()); + + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + assertSame(HumanGen.class, child.getClass()); // check if type + // descriptor was correct } - - public void testBeanRing() throws IOException, IntrospectionException { - if (!GenericsBugDetector.isProperIntrospection()) { - return; - } - HumanGen man1 = new HumanGen(); - man1.setName("Man 1"); - HumanGen man2 = new HumanGen(); - man2.setName("Man 2"); - HumanGen man3 = new HumanGen(); - man3.setName("Man 3"); - man1.setBankAccountOwner(man2); - man2.setBankAccountOwner(man3); - man3.setBankAccountOwner(man1); - // - Yaml yaml = new Yaml(); - String output = yaml.dump(man1); - // System.out.println(output); - String etalon = Util.getLocalResource("recursive/generics/beanring-3.yaml"); - assertEquals(etalon, output); - // - HumanGen loadedMan1 = (HumanGen) yaml.load(output); - assertNotNull(loadedMan1); - assertEquals("Man 1", loadedMan1.getName()); - HumanGen loadedMan2 = loadedMan1.getBankAccountOwner(); - HumanGen loadedMan3 = loadedMan2.getBankAccountOwner(); - assertSame(loadedMan1, loadedMan3.getBankAccountOwner()); + } + + /* + * Loads same structure as created in testChildren. But root object is map of children + */ + @SuppressWarnings("unchecked") + public void testChildrenMapAsRoot() throws IOException, IntrospectionException { + String etalon = Util.getLocalResource("recursive/generics/with-children-as-map.yaml"); + + Constructor constructor = new Constructor(); + TypeDescription Human2Description = new TypeDescription(HumanGen2.class); + Human2Description.putMapPropertyType("children", HumanGen2.class, String.class); + constructor.addTypeDescription(Human2Description); + + Yaml yaml = new Yaml(constructor); + Map<HumanGen2, String> children2 = yaml.load(etalon); + assertNotNull(children2); + assertEquals(2, children2.size()); + + Entry<HumanGen2, String> firstEntry = children2.entrySet().iterator().next(); + HumanGen2 firstChild = firstEntry.getKey(); + + HumanGen2 father2 = firstChild.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", firstChild.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), firstChild.getMother()); + assertSame(father2, firstChild.getMother().getPartner()); + + assertSame(father2.getPartner().getChildren(), children2); + } + + /* + * Loads same structure as created in testChildren. But root object is list of children + */ + @SuppressWarnings("unchecked") + public void testChildrenListRoot() throws IOException, IntrospectionException { + HumanGen3 father = new HumanGen3(); + father.setName("Father"); + father.setBirthday(new Date(1000000000)); + father.setBirthPlace("Leningrad"); + father.setBankAccountOwner(father); + // + HumanGen3 mother = new HumanGen3(); + mother.setName("Mother"); + mother.setBirthday(new Date(100000000000L)); + mother.setBirthPlace("Saint-Petersburg"); + father.setPartner(mother); + mother.setPartner(father); + mother.setBankAccountOwner(father); + // + HumanGen3 son = new HumanGen3(); + son.setName("Son"); + son.setBirthday(new Date(310000000000L)); + son.setBirthPlace("Munich"); + son.setBankAccountOwner(father); + son.setFather(father); + son.setMother(mother); + // + HumanGen3 daughter = new HumanGen3(); + daughter.setName("Daughter"); + daughter.setBirthday(new Date(420000000000L)); + daughter.setBirthPlace("New York"); + daughter.setBankAccountOwner(father); + daughter.setFather(father); + daughter.setMother(mother); + // + ArrayList<HumanGen3> children = new ArrayList<HumanGen3>(); + children.add(son); + children.add(daughter); + father.setChildren(children); + mother.setChildren(children); + // + + Constructor constructor = new Constructor(); + TypeDescription Human3Description = new TypeDescription(HumanGen3.class); + Human3Description.putListPropertyType("children", HumanGen3.class); + constructor.addTypeDescription(Human3Description); + + Yaml yaml = new Yaml(constructor); + String output = yaml.dump(father.getChildren()); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/generics/with-children-as-list.yaml"); + assertEquals(etalon, output); + // + List<HumanGen3> children2 = yaml.load(output); + assertNotNull(children2); + HumanGen3 son2 = children2.iterator().next(); + assertEquals(2, children2.size()); + + HumanGen3 father2 = son2.getFather(); + assertEquals("Father", father2.getName()); + assertEquals("Mother", son2.getMother().getName()); + assertSame(father2, father2.getBankAccountOwner()); + assertSame(father2.getPartner(), son2.getMother()); + assertSame(father2, son2.getMother().getPartner()); + + assertSame(father2.getPartner().getChildren(), children2); + + for (Object child : children2) { + assertSame(HumanGen3.class, child.getClass()); // check if type + // descriptor was + // correct } + } + + public void testBeanRing() throws IOException, IntrospectionException { + HumanGen man1 = new HumanGen(); + man1.setName("Man 1"); + HumanGen man2 = new HumanGen(); + man2.setName("Man 2"); + HumanGen man3 = new HumanGen(); + man3.setName("Man 3"); + man1.setBankAccountOwner(man2); + man2.setBankAccountOwner(man3); + man3.setBankAccountOwner(man1); + // + Yaml yaml = new Yaml(); + String output = yaml.dump(man1); + // System.out.println(output); + String etalon = Util.getLocalResource("recursive/generics/beanring-3.yaml"); + assertEquals(etalon, output); + // + HumanGen loadedMan1 = yaml.load(output); + assertNotNull(loadedMan1); + assertEquals("Man 1", loadedMan1.getName()); + HumanGen loadedMan2 = loadedMan1.getBankAccountOwner(); + HumanGen loadedMan3 = loadedMan2.getBankAccountOwner(); + assertSame(loadedMan1, loadedMan3.getBankAccountOwner()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/DumpStackTraceTest.java b/src/test/java/org/yaml/snakeyaml/representer/DumpStackTraceTest.java index 38a52567..c5e35825 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/DumpStackTraceTest.java +++ b/src/test/java/org/yaml/snakeyaml/representer/DumpStackTraceTest.java @@ -1,65 +1,62 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class DumpStackTraceTest extends TestCase { - public void testJavaStackTrace() { - Yaml yaml = new Yaml(); - String input = Util.getLocalResource("representer/stacktrace1.txt"); - String result = yaml.dump(input); - // System.out.println(result); - assertEquals(result, yaml.dump(yaml.load(result))); - } + public void testJavaStackTrace() { + Yaml yaml = new Yaml(); + String input = Util.getLocalResource("representer/stacktrace1.txt"); + String result = yaml.dump(input); + // System.out.println(result); + assertEquals(result, yaml.dump(yaml.load(result))); + } - public void testJavaStackTraceWithNoSpecialCharacters() { - DumperOptions options = new DumperOptions(); - options.setWidth(50); - Yaml yaml = new Yaml(options); - String input = Util.getLocalResource("representer/stacktrace2.txt"); - assertEquals(-1, input.indexOf(':')); - assertEquals(-1, input.indexOf('\t')); - String result = yaml.dump(input); - // System.out.println(result); - assertEquals(result, yaml.dump(yaml.load(result))); - } + public void testJavaStackTraceWithNoSpecialCharacters() { + DumperOptions options = new DumperOptions(); + options.setWidth(50); + Yaml yaml = new Yaml(options); + String input = Util.getLocalResource("representer/stacktrace2.txt"); + assertEquals(-1, input.indexOf(':')); + assertEquals(-1, input.indexOf('\t')); + String result = yaml.dump(input); + // System.out.println(result); + assertEquals(result, yaml.dump(yaml.load(result))); + } - public void testJavaStackTraceWithTabs() { - Yaml yaml = new Yaml(); - String input = Util.getLocalResource("representer/stacktrace3.txt"); - assertEquals(-1, input.indexOf(':')); - assertTrue("Tabs must be used.", input.indexOf('\t') > 0); - String result = yaml.dump(input); - // System.out.println(result); - assertEquals(result, yaml.dump(yaml.load(result))); - } + public void testJavaStackTraceWithTabs() { + Yaml yaml = new Yaml(); + String input = Util.getLocalResource("representer/stacktrace3.txt"); + assertEquals(-1, input.indexOf(':')); + assertTrue("Tabs must be used.", input.indexOf('\t') > 0); + String result = yaml.dump(input); + // System.out.println(result); + assertEquals(result, yaml.dump(yaml.load(result))); + } - public void testJavaStackTraceWithoutTabs() { - Yaml yaml = new Yaml(); - String input = Util.getLocalResource("representer/stacktrace1.txt"); - String result = (String) yaml.dump(input); - // System.out.println(result); - String etalon = Util.getLocalResource("representer/stacktrace1.yaml"); - // http://code.google.com/p/snakeyaml/issues/detail?id=66 - assertEquals(etalon, result); - } + public void testJavaStackTraceWithoutTabs() { + Yaml yaml = new Yaml(); + String input = Util.getLocalResource("representer/stacktrace1.txt"); + String result = yaml.dump(input); + // System.out.println(result); + String etalon = Util.getLocalResource("representer/stacktrace1.yaml"); + // http://code.google.com/p/snakeyaml/issues/detail?id=66 + assertEquals(etalon, result); + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/FilterPropertyToDumpTest.java b/src/test/java/org/yaml/snakeyaml/representer/FilterPropertyToDumpTest.java index 41c6bf23..c72c386b 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/FilterPropertyToDumpTest.java +++ b/src/test/java/org/yaml/snakeyaml/representer/FilterPropertyToDumpTest.java @@ -1,107 +1,135 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; -import java.beans.IntrospectionException; import java.util.Set; import java.util.TreeSet; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.introspector.Property; public class FilterPropertyToDumpTest extends TestCase { - public void testFilterPropertyInJavaBeanDumper() { - BeanToRemoveProperty bean = new BeanToRemoveProperty(); - bean.setNumber(24); - bean.setId("ID124"); - Yaml d = new Yaml(); - String dump = d.dumpAsMap(bean); - // System.out.println(dump); - assertEquals("id: ID124\nnumber: 24\n", dump); - } + public void testFilterPropertyInJavaBeanDumper() { + BeanToRemoveProperty bean = new BeanToRemoveProperty(); + bean.setNumber(24); + bean.setId("ID124"); + Yaml d = new Yaml(); + String dump = d.dumpAsMap(bean); + // System.out.println(dump); + assertEquals("id: ID124\nnumber: 24\n", dump); + } - public void testFilterPropertyInYaml() { - BeanToRemoveProperty bean = new BeanToRemoveProperty(); - bean.setNumber(25); - bean.setId("ID125"); - Yaml yaml = new Yaml(new MyRepresenter()); - String dump = yaml.dumpAsMap(bean); - // System.out.println(dump); - assertEquals("number: 25\n", dump); - } + public void testFilterPropertyInYaml() { + BeanToRemoveProperty bean = new BeanToRemoveProperty(); + bean.setNumber(25); + bean.setId("ID125"); + Yaml yaml = new Yaml(new MyRepresenter()); + String dump = yaml.dumpAsMap(bean); + // System.out.println(dump); + assertEquals("number: 25\n", dump); + } - public void testDoNotFilterPropertyIncludeReadOnly() { - BeanToRemoveProperty bean = new BeanToRemoveProperty(); - bean.setNumber(26); - bean.setId("ID126"); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - String dump = yaml.dump(bean); - // System.out.println(dump); - assertEquals( - "!!org.yaml.snakeyaml.representer.FilterPropertyToDumpTest$BeanToRemoveProperty {id: ID126,\n number: 26, something: true}\n", - dump); - } + public void testDoNotFilterPropertyIncludeReadOnly() { + BeanToRemoveProperty bean = new BeanToRemoveProperty(); + bean.setNumber(26); + bean.setId("ID126"); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + String dump = yaml.dump(bean); + // System.out.println(dump); + assertEquals( + "!!org.yaml.snakeyaml.representer.FilterPropertyToDumpTest$BeanToRemoveProperty {id: ID126,\n number: 26, something: true}\n", + dump); + } - public class BeanToRemoveProperty { - private int number; - private String id; + public void testFilterPropertyWithTypeDesciptionIncludes() { + BeanToRemoveProperty bean = new BeanToRemoveProperty(); + bean.setNumber(27); + bean.setId("ID127"); + Yaml yaml = new Yaml(); + TypeDescription td = new TypeDescription(BeanToRemoveProperty.class); + td.setIncludes("number"); + yaml.addTypeDescription(td); + String dump = yaml.dump(bean); + // System.out.println(dump); + assertEquals( + "!!org.yaml.snakeyaml.representer.FilterPropertyToDumpTest$BeanToRemoveProperty {number: 27}\n", + dump); + } - public boolean isSomething() { - return true; - } + public void testFilterPropertyWithTypeDesciptionExcludes() { + BeanToRemoveProperty bean = new BeanToRemoveProperty(); + bean.setNumber(28); + bean.setId("ID128"); + Yaml yaml = new Yaml(); + TypeDescription td = new TypeDescription(BeanToRemoveProperty.class); + td.setExcludes("id"); + yaml.addTypeDescription(td); + String dump = yaml.dump(bean); + // System.out.println(dump); + assertEquals( + "!!org.yaml.snakeyaml.representer.FilterPropertyToDumpTest$BeanToRemoveProperty {number: 28}\n", + dump); + } - public int getNumber() { - return number; - } - public void setNumber(int number) { - this.number = number; - } + public class BeanToRemoveProperty { - public void setId(String id) { - this.id = id; - } + private int number; + private String id; - public String getId() { - return id; - } + public boolean isSomething() { + return true; } - private class MyRepresenter extends Representer { - @Override - protected Set<Property> getProperties(Class<? extends Object> type) - throws IntrospectionException { - Set<Property> set = super.getProperties(type); - Set<Property> filtered = new TreeSet<Property>(); - if (type.equals(BeanToRemoveProperty.class)) { - // filter properties - for (Property prop : set) { - String name = prop.getName(); - if (!name.equals("id")) { - filtered.add(prop); - } - } - } - return filtered; + public int getNumber() { + return number; + } + + public void setNumber(int number) { + this.number = number; + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + } + + private class MyRepresenter extends Representer { + + @Override + protected Set<Property> getProperties(Class<? extends Object> type) { + Set<Property> set = super.getProperties(type); + Set<Property> filtered = new TreeSet<Property>(); + if (type.equals(BeanToRemoveProperty.class)) { + // filter properties + for (Property prop : set) { + String name = prop.getName(); + if (!name.equals("id")) { + filtered.add(prop); + } } + } + return filtered; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/RepresentFieldTest.java b/src/test/java/org/yaml/snakeyaml/representer/RepresentFieldTest.java index feff49e1..9a934197 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/RepresentFieldTest.java +++ b/src/test/java/org/yaml/snakeyaml/representer/RepresentFieldTest.java @@ -1,70 +1,66 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public class RepresentFieldTest extends TestCase { - public void testRepresent1() { - Yaml yaml = new Yaml(); - WrongJavaBean bean = new WrongJavaBean(); - bean.packageField = "Value";// the field is present - bean.publicField = "Michael Jackson"; - WrongJavaBean.staticField = "Another value"; - String output = yaml.dump(bean); - assertEquals( - "!!org.yaml.snakeyaml.representer.WrongJavaBean {publicField: Michael Jackson}\n", - output); - } + public void testRepresent1() { + Yaml yaml = new Yaml(); + WrongJavaBean bean = new WrongJavaBean(); + bean.packageField = "Value";// the field is present + bean.publicField = "Michael Jackson"; + WrongJavaBean.staticField = "Another value"; + String output = yaml.dump(bean); + assertEquals("!!org.yaml.snakeyaml.representer.WrongJavaBean {publicField: Michael Jackson}\n", + output); + } - public void testWrongNotPublicField() { - Yaml yaml = new Yaml(); - WrongJavaBean bean = new WrongJavaBean(); - bean.packageField = "Value";// the field is present - try { - yaml.load("!!org.yaml.snakeyaml.representer.WrongJavaBean {packageField: Gnome}\n"); - fail("Only public fields can be used."); - } catch (Exception e) { - // TODO improve the error message - the pointer should be at the - // property name, not value - assertTrue(e.getMessage().startsWith( - "Cannot create property=packageField for JavaBean=WrongJavaBean")); - assertEquals( - "Unable to find property 'packageField' on class: org.yaml.snakeyaml.representer.WrongJavaBean", - e.getCause().getMessage()); - } + public void testWrongNotPublicField() { + Yaml yaml = new Yaml(); + WrongJavaBean bean = new WrongJavaBean(); + bean.packageField = "Value";// the field is present + try { + yaml.load("!!org.yaml.snakeyaml.representer.WrongJavaBean {packageField: Gnome}\n"); + fail("Only public fields can be used."); + } catch (Exception e) { + // TODO improve the error message - the pointer should be at the + // property name, not value + assertTrue(e.getMessage() + .startsWith("Cannot create property=packageField for JavaBean=WrongJavaBean")); + assertEquals( + "Unable to find property 'packageField' on class: org.yaml.snakeyaml.representer.WrongJavaBean", + e.getCause().getMessage()); } + } - public void testStaticField() { - Yaml yaml = new Yaml(); - WrongJavaBean.staticField = "Value";// the field is present - try { - yaml.load("!!org.yaml.snakeyaml.representer.WrongJavaBean {staticField: Gnome}\n"); - fail("Static fields cannot be used."); - } catch (Exception e) { - // TODO improve the error message - the pointer should be at the - // property name, not value - assertTrue(e.getMessage().startsWith( - "Cannot create property=staticField for JavaBean=WrongJavaBean")); - assertEquals( - "Unable to find property 'staticField' on class: org.yaml.snakeyaml.representer.WrongJavaBean", - e.getCause().getMessage()); - } + public void testStaticField() { + Yaml yaml = new Yaml(); + WrongJavaBean.staticField = "Value";// the field is present + try { + yaml.load("!!org.yaml.snakeyaml.representer.WrongJavaBean {staticField: Gnome}\n"); + fail("Static fields cannot be used."); + } catch (Exception e) { + // TODO improve the error message - the pointer should be at the + // property name, not value + assertTrue(e.getMessage() + .startsWith("Cannot create property=staticField for JavaBean=WrongJavaBean")); + assertEquals( + "Unable to find property 'staticField' on class: org.yaml.snakeyaml.representer.WrongJavaBean", + e.getCause().getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/RepresentIterableTest.java b/src/test/java/org/yaml/snakeyaml/representer/RepresentIterableTest.java index 339e71de..b9492cb4 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/RepresentIterableTest.java +++ b/src/test/java/org/yaml/snakeyaml/representer/RepresentIterableTest.java @@ -1,24 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; import java.util.Iterator; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; /** @@ -26,48 +22,50 @@ import org.yaml.snakeyaml.Yaml; */ public class RepresentIterableTest extends TestCase { - public void testIterable() { - Yaml yaml = new Yaml(); - try { - yaml.dump(new CounterFactory()); - fail("Iterable should not be treated as sequence by default."); - } catch (Exception e) { - assertEquals( - "No JavaBean properties found in org.yaml.snakeyaml.representer.RepresentIterableTest$CounterFactory", - e.getMessage()); - } + public void testIterable() { + Yaml yaml = new Yaml(); + try { + yaml.dump(new CounterFactory()); + fail("Iterable should not be treated as sequence by default."); + } catch (Exception e) { + assertEquals( + "No JavaBean properties found in org.yaml.snakeyaml.representer.RepresentIterableTest$CounterFactory", + e.getMessage()); } + } - public void testIterator() { - Yaml yaml = new Yaml(); - String output = yaml.dump(new Counter(7)); - assertEquals("[0, 1, 2, 3, 4, 5, 6]\n", output); - } + public void testIterator() { + Yaml yaml = new Yaml(); + String output = yaml.dump(new Counter(7)); + assertEquals("[0, 1, 2, 3, 4, 5, 6]\n", output); + } + + private class CounterFactory implements Iterable<Integer> { - private class CounterFactory implements Iterable<Integer> { - public Iterator<Integer> iterator() { - return new Counter(10); - } + public Iterator<Integer> iterator() { + return new Counter(10); } + } - private class Counter implements Iterator<Integer> { - private int max = 0; - private int counter = 0; + private class Counter implements Iterator<Integer> { - public Counter(int max) { - this.max = max; - } + private int max = 0; + private int counter = 0; - public boolean hasNext() { - return counter < max; - } + public Counter(int max) { + this.max = max; + } + + public boolean hasNext() { + return counter < max; + } - public Integer next() { - return counter++; - } + public Integer next() { + return counter++; + } - public void remove() { - throw new UnsupportedOperationException(); - } + public void remove() { + throw new UnsupportedOperationException(); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/RepresentTest.java b/src/test/java/org/yaml/snakeyaml/representer/RepresentTest.java index a68beaf7..3b87ea38 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/RepresentTest.java +++ b/src/test/java/org/yaml/snakeyaml/representer/RepresentTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; @@ -26,65 +23,70 @@ import org.yaml.snakeyaml.nodes.Tag; public class RepresentTest extends TestCase { - public void testCustomRepresenter() { - Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); - CustomBean etalon = new CustomBean("A", 1); - String output = yaml.dump(etalon); - assertEquals("!!Dice 'Ad1'\n", output); - CustomBean bean = (CustomBean) yaml.load(output); - assertEquals("A", bean.getPrefix()); - assertEquals(1, bean.getSuffix()); - assertEquals(etalon, bean); + public void testCustomRepresenter() { + Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); + CustomBean etalon = new CustomBean("A", 1); + String output = yaml.dump(etalon); + assertEquals("!!Dice 'Ad1'\n", output); + CustomBean bean = yaml.load(output); + assertEquals("A", bean.getPrefix()); + assertEquals(1, bean.getSuffix()); + assertEquals(etalon, bean); + } + + class CustomBean { + + private final String prefix; + private final int suffix; + + public CustomBean(String prefix, int suffix) { + this.prefix = prefix; + this.suffix = suffix; + } + + public String getPrefix() { + return prefix; } - class CustomBean { - private String prefix; - private int suffix; + public int getSuffix() { + return suffix; + } + + @Override + public boolean equals(Object obj) { + CustomBean bean = (CustomBean) obj; + return prefix.equals(bean.getPrefix()) && suffix == bean.getSuffix(); + } + } - public CustomBean(String prefix, int suffix) { - this.prefix = prefix; - this.suffix = suffix; - } + class MyRepresenter extends Representer { - public String getPrefix() { - return prefix; - } + public MyRepresenter() { + this.representers.put(CustomBean.class, new RepresentDice()); + } - public int getSuffix() { - return suffix; - } + private class RepresentDice implements Represent { - @Override - public boolean equals(Object obj) { - CustomBean bean = (CustomBean) obj; - return prefix.equals(bean.getPrefix()) && suffix == bean.getSuffix(); - } + public Node representData(Object data) { + CustomBean coin = (CustomBean) data; + String value = coin.getPrefix() + "d" + coin.getSuffix(); + return representScalar(new Tag("!!Dice"), value); + } } + } + + class MyConstructor extends Constructor { - class MyRepresenter extends Representer { - public MyRepresenter() { - this.representers.put(CustomBean.class, new RepresentDice()); - } - - private class RepresentDice implements Represent { - public Node representData(Object data) { - CustomBean coin = (CustomBean) data; - String value = coin.getPrefix() + "d" + coin.getSuffix(); - return representScalar(new Tag("!!Dice"), value); - } - } + public MyConstructor() { + this.yamlConstructors.put(new Tag(Tag.PREFIX + "Dice"), new ConstructDice()); } - class MyConstructor extends Constructor { - public MyConstructor() { - this.yamlConstructors.put(new Tag(Tag.PREFIX + "Dice"), new ConstructDice()); - } - - private class ConstructDice extends AbstractConstruct { - public Object construct(Node node) { - String val = (String) constructScalar((ScalarNode) node); - return new CustomBean(val.substring(0, 1), new Integer(val.substring(2))); - } - } + private class ConstructDice extends AbstractConstruct { + + public Object construct(Node node) { + String val = constructScalar((ScalarNode) node); + return new CustomBean(val.substring(0, 1), Integer.valueOf(val.substring(2))); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/RepresenterTest.java b/src/test/java/org/yaml/snakeyaml/representer/RepresenterTest.java index db310629..0c944c6b 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/RepresenterTest.java +++ b/src/test/java/org/yaml/snakeyaml/representer/RepresenterTest.java @@ -1,192 +1,191 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.nodes.Tag; public class RepresenterTest extends TestCase { - public void testRepresenter() { - MyBean bean = new MyBean(); - bean.setName("Gnome"); - bean.setValid(true); - bean.setPrimitive(true); - Yaml yaml = new Yaml(); - assertEquals( - "!!org.yaml.snakeyaml.representer.RepresenterTest$MyBean {name: Gnome, primitive: true}\n", - yaml.dump(bean)); - } - - public static class MyBean { - private String name; - private Boolean valid; - private boolean primitive; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Boolean isValid() { - return valid; - } - - public void setValid(Boolean valid) { - this.valid = valid; - } - - public boolean isPrimitive() { - return primitive; - } - - public void setPrimitive(boolean primitive) { - this.primitive = primitive; - } - } - - public void testRepresenterNoConstructorAvailable() { - MyBean2 bean = new MyBean2("Gnome", true); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - assertEquals("!!org.yaml.snakeyaml.representer.RepresenterTest$MyBean2 {valid: true}\n", - yaml.dump(bean)); - } - - public static class MyBean2 { - private String name; - private Boolean valid; - - public MyBean2(String name, Boolean valid) { - this(); - this.name = name; - this.valid = valid; - } - - private MyBean2() { - super(); - } - - private String getName() { - return name; - } - - public Boolean getValid() { - return valid; - } - - @Override - public String toString() { - return getName() + " " + getValid(); - } - } - - public void testRepresenterGetterWithException() { - MyBean3 bean = new MyBean3("Gnome", false); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(true); - Yaml yaml = new Yaml(options); - try { - String str = yaml.dump(bean); - fail("Exception must be reported: " + str); - } catch (Exception e) { - assertTrue(true); - } - // no exception - MyBean3 bean2 = new MyBean3("Gnome", true); - String str = yaml.dump(bean2); - // isValid is no JavaBean property (it must be a primitive then) - assertEquals( - "isValid property must not be dumped.", - "!!org.yaml.snakeyaml.representer.RepresenterTest$MyBean3 {boolProperty: true, name: Gnome}\n", - str); - } - - public static class MyBean3 { - private String name; - private Boolean valid; - private boolean boolProperty; - - public MyBean3(String name, Boolean valid) { - this.name = name; - this.valid = valid; - boolProperty = true; - } - - public String getName() { - if (valid) { - return name; - } else { - throw new UnsupportedOperationException("Test."); - } - } - - public Boolean isValid() { - return valid; - } - - public boolean isBoolProperty() { - return boolProperty; - } - - @Override - public String toString() { - return "MyBean3<" + name + ", " + isValid() + ">"; - } - } - - public void testRepresenterAddNull() { - Representer representer = new Representer(); - try { - representer.addClassTag(EmptyBean.class, (Tag) null); - fail("Tag must be provided."); - } catch (Exception e) { - assertEquals("Tag must be provided.", e.getMessage()); - } - } - - public void testRepresenterEmptyBean() { - EmptyBean bean = new EmptyBean(); - Yaml yaml = new Yaml(); - try { - yaml.dump(bean); - fail("EmptyBean has empty representation."); - } catch (Exception e) { - assertEquals( - "No JavaBean properties found in org.yaml.snakeyaml.representer.RepresenterTest$EmptyBean", - e.getMessage()); - } - } - - public static class EmptyBean { - private int number; - - public void process() { - number += 1; - } - - public int obtain() { - return number; - } + public void testRepresenter() { + MyBean bean = new MyBean(); + bean.setName("Gnome"); + bean.setValid(true); + bean.setPrimitive(true); + Yaml yaml = new Yaml(); + assertEquals( + "!!org.yaml.snakeyaml.representer.RepresenterTest$MyBean {name: Gnome, primitive: true}\n", + yaml.dump(bean)); + } + + public static class MyBean { + + private String name; + private Boolean valid; + private boolean primitive; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean isValid() { + return valid; + } + + public void setValid(Boolean valid) { + this.valid = valid; + } + + public boolean isPrimitive() { + return primitive; + } + + public void setPrimitive(boolean primitive) { + this.primitive = primitive; + } + } + + public void testRepresenterNoConstructorAvailable() { + MyBean2 bean = new MyBean2("Gnome", true); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + assertEquals("!!org.yaml.snakeyaml.representer.RepresenterTest$MyBean2 {valid: true}\n", + yaml.dump(bean)); + } + + public static class MyBean2 { + + private String name; + private Boolean valid; + + public MyBean2(String name, Boolean valid) { + this(); + this.name = name; + this.valid = valid; + } + + private MyBean2() { + super(); + } + + private String getName() { + return name; + } + + public Boolean getValid() { + return valid; + } + + @Override + public String toString() { + return getName() + " " + getValid(); + } + } + + public void testRepresenterGetterWithException() { + MyBean3 bean = new MyBean3("Gnome", false); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(true); + Yaml yaml = new Yaml(options); + try { + String str = yaml.dump(bean); + fail("Exception must be reported: " + str); + } catch (Exception e) { + assertTrue(true); + } + // no exception + MyBean3 bean2 = new MyBean3("Gnome", true); + String str = yaml.dump(bean2); + // isValid is no JavaBean property (it must be a primitive then) + assertEquals("isValid property must not be dumped.", + "!!org.yaml.snakeyaml.representer.RepresenterTest$MyBean3 {boolProperty: true, name: Gnome}\n", + str); + } + + public static class MyBean3 { + + private final String name; + private final Boolean valid; + private final boolean boolProperty; + + public MyBean3(String name, Boolean valid) { + this.name = name; + this.valid = valid; + boolProperty = true; + } + + public String getName() { + if (valid) { + return name; + } else { + throw new UnsupportedOperationException("Test."); + } + } + + public Boolean isValid() { + return valid; + } + + public boolean isBoolProperty() { + return boolProperty; + } + + @Override + public String toString() { + return "MyBean3<" + name + ", " + isValid() + ">"; + } + } + + public void testRepresenterAddNull() { + Representer representer = new Representer(); + try { + representer.addClassTag(EmptyBean.class, null); + fail("Tag must be provided."); + } catch (Exception e) { + assertEquals("Tag must be provided.", e.getMessage()); + } + } + + public void testRepresenterEmptyBean() { + EmptyBean bean = new EmptyBean(); + Yaml yaml = new Yaml(); + try { + yaml.dump(bean); + fail("EmptyBean has empty representation."); + } catch (Exception e) { + assertEquals( + "No JavaBean properties found in org.yaml.snakeyaml.representer.RepresenterTest$EmptyBean", + e.getMessage()); + } + } + + public static class EmptyBean { + + private int number; + + public void process() { + number += 1; + } + + public int obtain() { + return number; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/SafeRepresenterTest.java b/src/test/java/org/yaml/snakeyaml/representer/SafeRepresenterTest.java index 719cf54d..e81c4e2d 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/SafeRepresenterTest.java +++ b/src/test/java/org/yaml/snakeyaml/representer/SafeRepresenterTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; @@ -22,116 +20,111 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.regex.Pattern; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.reader.StreamReader; public class SafeRepresenterTest extends TestCase { - public void testBinaryPattern() { - Pattern pattern = StreamReader.NON_PRINTABLE; - assertFalse(pattern.matcher("\tAndrey\r\n").find()); - assertTrue(pattern.matcher("\u0005Andrey").find()); - } + public void testBinaryPattern() { + assertTrue(StreamReader.isPrintable("\tAndrey\r\n")); + assertFalse(StreamReader.isPrintable("\u0005Andrey")); + } - public void testFloat() { - assertEquals("1.0E12", String.valueOf(new Double("1e12"))); - } + public void testFloat() { + assertEquals("1.0E12", String.valueOf(Double.valueOf("1e12"))); + } - public void testNumber() { - List<Number> list = new ArrayList<Number>(); - list.add(new Byte((byte) 3)); - list.add(new Short((short) 4)); - list.add(new Integer(5)); - list.add(new BigInteger("6")); - list.add(new Long(7L)); - list.add(Double.POSITIVE_INFINITY); - list.add(Double.NEGATIVE_INFINITY); - list.add(Double.NaN); - Yaml yaml = new Yaml(); - String output = yaml.dump(list); - assertEquals("[3, 4, 5, 6, 7, .inf, -.inf, .NaN]\n", output); - } + public void testNumber() { + List<Number> list = new ArrayList<Number>(); + list.add(Byte.valueOf((byte) 3)); + list.add(Short.valueOf((short) 4)); + list.add(Integer.valueOf(5)); + list.add(new BigInteger("6")); + list.add(Long.valueOf(7L)); + list.add(Double.POSITIVE_INFINITY); + list.add(Double.NEGATIVE_INFINITY); + list.add(Double.NaN); + Yaml yaml = new Yaml(); + String output = yaml.dump(list); + assertEquals("[3, 4, 5, 6, 7, .inf, -.inf, .NaN]\n", output); + } - public void testDate() { - List<Date> list = new ArrayList<Date>(); - list.add(new Date(1229684761159L)); - list.add(new Date(1229684761059L)); - list.add(new Date(1229684761009L)); - list.add(new Date(1229684761150L)); - list.add(new Date(1229684761100L)); - list.add(new Date(1229684761000L)); - list.add(new Date(1229684760000L)); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String output = yaml.dump(list); - assertEquals( - "- 2008-12-19T11:06:01.159Z\n- 2008-12-19T11:06:01.059Z\n- 2008-12-19T11:06:01.009Z\n- 2008-12-19T11:06:01.150Z\n- 2008-12-19T11:06:01.100Z\n- 2008-12-19T11:06:01Z\n- 2008-12-19T11:06:00Z\n", - output); - } + public void testDate() { + List<Date> list = new ArrayList<Date>(); + list.add(new Date(1229684761159L)); + list.add(new Date(1229684761059L)); + list.add(new Date(1229684761009L)); + list.add(new Date(1229684761150L)); + list.add(new Date(1229684761100L)); + list.add(new Date(1229684761000L)); + list.add(new Date(1229684760000L)); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String output = yaml.dump(list); + assertEquals( + "- 2008-12-19T11:06:01.159Z\n- 2008-12-19T11:06:01.059Z\n- 2008-12-19T11:06:01.009Z\n- 2008-12-19T11:06:01.150Z\n- 2008-12-19T11:06:01.100Z\n- 2008-12-19T11:06:01Z\n- 2008-12-19T11:06:00Z\n", + output); + } - public void testEmptyArray() { - Yaml yaml = new Yaml(); - String output = yaml.dump(new String[0]); - assertEquals("[]\n", output); - } + public void testEmptyArray() { + Yaml yaml = new Yaml(); + String output = yaml.dump(new String[0]); + assertEquals("[]\n", output); + } - public void testStyle() { - List<Integer> list = new ArrayList<Integer>(); - list.add(new Integer(1)); - list.add(new Integer(1)); - Map<String, Object> map = new HashMap<String, Object>(); - map.put("list", list); - map.put("name", "Ubuntu"); - map.put("age", 5); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - assertTrue(output.contains("\"age\": !!int \"5\"")); - assertTrue(output.contains("\"name\": \"Ubuntu\"")); - assertTrue(output.contains("- !!int \"1\"")); - } + public void testStyle() { + List<Integer> list = new ArrayList<Integer>(); + list.add(Integer.valueOf(1)); + list.add(Integer.valueOf(1)); + Map<String, Object> map = new HashMap<String, Object>(); + map.put("list", list); + map.put("name", "Ubuntu"); + map.put("age", 5); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + assertTrue(output.contains("\"age\": !!int \"5\"")); + assertTrue(output.contains("\"name\": \"Ubuntu\"")); + assertTrue(output.contains("- !!int \"1\"")); + } - public void testStyle2() { - List<Integer> list = new ArrayList<Integer>(); - list.add(new Integer(1)); - list.add(new Integer(1)); - Map<String, Object> map = new LinkedHashMap<String, Object>(); - map.put("age", 5); - map.put("name", "Ubuntu"); - map.put("list", list); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - assertEquals("{'age': !!int '5', 'name': 'Ubuntu', 'list': [!!int '1', !!int '1']}\n", - output); - } + public void testStyle2() { + List<Integer> list = new ArrayList<Integer>(); + list.add(Integer.valueOf(1)); + list.add(Integer.valueOf(1)); + Map<String, Object> map = new LinkedHashMap<String, Object>(); + map.put("age", 5); + map.put("name", "Ubuntu"); + map.put("list", list); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + assertEquals("{'age': !!int '5', 'name': 'Ubuntu', 'list': [!!int '1', !!int '1']}\n", output); + } - public void testStyle2Pretty() { - List<Integer> list = new ArrayList<Integer>(); - list.add(new Integer(1)); - list.add(new Integer(1)); - Map<String, Object> map = new LinkedHashMap<String, Object>(); - map.put("age", 5); - map.put("name", "Ubuntu"); - map.put("list", list); - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); - options.setPrettyFlow(true); - Yaml yaml = new Yaml(options); - String output = yaml.dump(map); - assertEquals( - "{\n 'age': !!int '5',\n 'name': 'Ubuntu',\n 'list': [\n !!int '1',\n !!int '1']\n \n}\n", - output); - } + public void testStyle2Pretty() { + List<Integer> list = new ArrayList<Integer>(); + list.add(Integer.valueOf(1)); + list.add(Integer.valueOf(1)); + Map<String, Object> map = new LinkedHashMap<String, Object>(); + map.put("age", 5); + map.put("name", "Ubuntu"); + map.put("list", list); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String output = yaml.dump(map); + assertEquals( + "{\n 'age': !!int '5',\n 'name': 'Ubuntu',\n 'list': [\n !!int '1',\n !!int '1'\n ]\n \n}\n", + output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/representer/WrongJavaBean.java b/src/test/java/org/yaml/snakeyaml/representer/WrongJavaBean.java index 729fc063..106b315f 100644 --- a/src/test/java/org/yaml/snakeyaml/representer/WrongJavaBean.java +++ b/src/test/java/org/yaml/snakeyaml/representer/WrongJavaBean.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.representer; public class WrongJavaBean { - String packageField; - static String staticField; - public transient String dynamo; - public String publicField; - private int privateValue; - public WrongJavaBean() { - method(); - } + String packageField; + static String staticField; + public transient String dynamo; + public String publicField; + private int privateValue; - private void method() { - privateValue++; - } + public WrongJavaBean() { + method(); + } - @Override - public String toString() { - return "WrongJavaBean"; - } + private void method() { + privateValue++; + } + + @Override + public String toString() { + return "WrongJavaBean"; + } } diff --git a/src/test/java/org/yaml/snakeyaml/resolver/ImplicitResolverTest.java b/src/test/java/org/yaml/snakeyaml/resolver/ImplicitResolverTest.java index 10ff70ea..63373dac 100644 --- a/src/test/java/org/yaml/snakeyaml/resolver/ImplicitResolverTest.java +++ b/src/test/java/org/yaml/snakeyaml/resolver/ImplicitResolverTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.resolver; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; - import junit.framework.TestCase; - import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; @@ -31,65 +27,69 @@ import org.yaml.snakeyaml.nodes.ScalarNode; import org.yaml.snakeyaml.nodes.Tag; /** - * Custom implicit resolver does not apply inside JavaBean declaration <a href= - * "http://groups.google.com/group/snakeyaml-core/browse_frm/thread/c75c35a3d9cfcaba" + * Custom implicit resolver does not apply inside JavaBean declaration + * <a href= "http://groups.google.com/group/snakeyaml-core/browse_frm/thread/c75c35a3d9cfcaba" * >mailing list</a> for more information */ public class ImplicitResolverTest extends TestCase { - private static final Tag CFG = new Tag("!cfg"); - public static class ConfigurationConstructor extends Constructor { - protected Map<String, String> config = null; + private static final Tag CFG = new Tag("!cfg"); - public ConfigurationConstructor(Map<String, String> config) { - this.config = config; - this.yamlConstructors.put(CFG, new ConfigObjectConstruct()); - } + public static class ConfigurationConstructor extends Constructor { - private class ConfigObjectConstruct extends AbstractConstruct { - public Object construct(Node node) { - String val = (String) constructScalar((ScalarNode) node); - val = val.substring(2, val.length() - 1); - return config.get(val); - } - } + protected Map<String, String> config = null; - protected Construct getConstructor(Node node) { - if (CFG.equals(node.getTag())) { - node.setUseClassConstructor(false); - } - return super.getConstructor(node); - } + public ConfigurationConstructor(Map<String, String> config) { + this.config = config; + this.yamlConstructors.put(CFG, new ConfigObjectConstruct()); } - public static class TestBean { - String myval; + private class ConfigObjectConstruct extends AbstractConstruct { - public String getMyval() { - return myval; - } + public Object construct(Node node) { + String val = constructScalar((ScalarNode) node); + val = val.substring(2, val.length() - 1); + return config.get(val); + } + } + + protected Construct getConstructor(Node node) { + if (CFG.equals(node.getTag())) { + node.setUseClassConstructor(false); + } + return super.getConstructor(node); + } + } - public void setMyval(String myval) { - this.myval = myval; - } + public static class TestBean { - public String toString() { - return "MyVal: " + myval; - } + String myval; + + public String getMyval() { + return myval; + } + + public void setMyval(String myval) { + this.myval = myval; } - public void testMain() { - Map<String, String> config = new HashMap<String, String>(); - config.put("user.home", "HOME"); - Constructor constructor = new ConfigurationConstructor(config); - constructor.addTypeDescription(new TypeDescription(TestBean.class, "!testbean")); - Yaml yaml = new Yaml(constructor); - yaml.addImplicitResolver(CFG, Pattern.compile("\\$\\([a-zA-Z\\d\\u002E\\u005F]+\\)"), "$"); - TestBean bean = (TestBean) yaml.load("!testbean {myval: !cfg $(user.home)}"); - // System.out.println(bean.toString()); - assertEquals("Explicit tag must be respected", "HOME", bean.getMyval()); - bean = (TestBean) yaml.load("!testbean {myval: $(user.home)}"); - // System.out.println(bean.toString()); - assertEquals("Implicit tag must be respected", "HOME", bean.getMyval()); + public String toString() { + return "MyVal: " + myval; } + } + + public void testMain() { + Map<String, String> config = new HashMap<String, String>(); + config.put("user.home", "HOME"); + Constructor constructor = new ConfigurationConstructor(config); + constructor.addTypeDescription(new TypeDescription(TestBean.class, "!testbean")); + Yaml yaml = new Yaml(constructor); + yaml.addImplicitResolver(CFG, Pattern.compile("\\$\\([a-zA-Z\\d\\u002E\\u005F]+\\)"), "$"); + TestBean bean = yaml.load("!testbean {myval: !cfg $(user.home)}"); + // System.out.println(bean.toString()); + assertEquals("Explicit tag must be respected", "HOME", bean.getMyval()); + bean = yaml.load("!testbean {myval: $(user.home)}"); + // System.out.println(bean.toString()); + assertEquals("Implicit tag must be respected", "HOME", bean.getMyval()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/resolver/ResolverTest.java b/src/test/java/org/yaml/snakeyaml/resolver/ResolverTest.java index c9a252d8..befc082e 100644 --- a/src/test/java/org/yaml/snakeyaml/resolver/ResolverTest.java +++ b/src/test/java/org/yaml/snakeyaml/resolver/ResolverTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.resolver; @@ -21,10 +19,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; - import junit.framework.TestCase; - -import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; @@ -36,115 +31,123 @@ import org.yaml.snakeyaml.representer.Representer; public class ResolverTest extends TestCase { - @SuppressWarnings("unchecked") - public void testAddImplicitResolver() { - Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); - Pattern regexp = Pattern.compile("\\d\\d-\\d\\d-\\d\\d\\d"); - yaml.addImplicitResolver(new Tag(Tag.PREFIX + "Phone"), regexp, "0123456789"); - Phone phone1 = new Phone("12-34-567"); - Phone phone2 = new Phone("11-22-333"); - Phone phone3 = new Phone("44-55-777"); - List<Phone> etalonList = new ArrayList<Phone>(); - etalonList.add(phone1); - etalonList.add(phone2); - etalonList.add(phone3); - String output = yaml.dump(etalonList); - assertEquals("[12-34-567, 11-22-333, 44-55-777]\n", output); - List<Phone> parsedList = (List<Phone>) yaml.load(output); - assertEquals(3, parsedList.size()); - assertEquals(phone1, parsedList.get(0)); - assertEquals(phone2, parsedList.get(1)); - assertEquals(phone3, parsedList.get(2)); - assertEquals(etalonList, parsedList); + @SuppressWarnings("unchecked") + public void testAddImplicitResolver() { + Yaml yaml = new Yaml(new MyConstructor(), new MyRepresenter()); + Pattern regexp = Pattern.compile("\\d\\d-\\d\\d-\\d\\d\\d"); + yaml.addImplicitResolver(new Tag(Tag.PREFIX + "Phone"), regexp, "0123456789"); + Phone phone1 = new Phone("12-34-567"); + Phone phone2 = new Phone("11-22-333"); + Phone phone3 = new Phone("44-55-777"); + List<Phone> etalonList = new ArrayList<Phone>(); + etalonList.add(phone1); + etalonList.add(phone2); + etalonList.add(phone3); + String output = yaml.dump(etalonList); + assertEquals("[12-34-567, 11-22-333, 44-55-777]\n", output); + List<Phone> parsedList = yaml.load(output); + assertEquals(3, parsedList.size()); + assertEquals(phone1, parsedList.get(0)); + assertEquals(phone2, parsedList.get(1)); + assertEquals(phone3, parsedList.get(2)); + assertEquals(etalonList, parsedList); + } + + public void testAddImplicitResolver2() { + Yaml yaml = new Yaml(new PointRepresenter()); + Pattern regexp = Pattern.compile("\\d\\d-\\d\\d-\\d\\d\\d"); + yaml.addImplicitResolver(new Tag(Tag.PREFIX + "Phone"), regexp, "\0"); + Pattern regexp2 = Pattern.compile("x\\d_y\\d"); + // try any scalar, and not only those which start with 'x' + yaml.addImplicitResolver(new Tag(Tag.PREFIX + "Point"), regexp2, null); + Map<String, Object> map = new LinkedHashMap<String, Object>(); + map.put("a", new Phone("12-34-567")); + map.put("b", new Point(1, 5)); + String output = yaml.dump(map); + assertEquals("{a: 12-34-567, b: x1_y5}\n", output); + } + + class Phone { + + private final String number; + + public Phone(String n) { + this.number = n; + } + + public String getNumber() { + return number; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Phone)) { + return false; + } + return toString().equals(obj.toString()); } - public void testAddImplicitResolver2() { - Yaml yaml = new Yaml(new PointRepresenter()); - Pattern regexp = Pattern.compile("\\d\\d-\\d\\d-\\d\\d\\d"); - yaml.addImplicitResolver(new Tag(Tag.PREFIX + "Phone"), regexp, "\0"); - Pattern regexp2 = Pattern.compile("x\\d_y\\d"); - // try any scalar, and not only those which start with 'x' - yaml.addImplicitResolver(new Tag(Tag.PREFIX + "Point"), regexp2, null); - Map<String, Object> map = new LinkedHashMap<String, Object>(); - map.put("a", new Phone("12-34-567")); - map.put("b", new Point(1, 5)); - String output = yaml.dump(map); - assertEquals("{a: 12-34-567, b: x1_y5}\n", output); + @Override + public String toString() { + return "Phone: " + number; } + } + + class MyRepresenter extends Representer { - class Phone { - private String number; - - public Phone(String n) { - this.number = n; - } - - public String getNumber() { - return number; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Phone)) { - return false; - } - return toString().equals(obj.toString()); - } - - @Override - public String toString() { - return "Phone: " + number; - } + public MyRepresenter() { + this.representers.put(Phone.class, new RepresentPhone()); } - class MyRepresenter extends Representer { - public MyRepresenter() { - this.representers.put(Phone.class, new RepresentPhone()); - } - - private class RepresentPhone implements Represent { - public Node representData(Object data) { - Phone phone = (Phone) data; - String value = phone.getNumber(); - return representScalar(new Tag(Tag.PREFIX + "Phone"), value); - } - } + private class RepresentPhone implements Represent { + + public Node representData(Object data) { + Phone phone = (Phone) data; + String value = phone.getNumber(); + return representScalar(new Tag(Tag.PREFIX + "Phone"), value); + } } + } - class MyConstructor extends Constructor { - public MyConstructor() { - this.yamlConstructors.put(new Tag(Tag.PREFIX + "Phone"), new ConstructPhone()); - } - - private class ConstructPhone extends AbstractConstruct { - public Object construct(Node node) { - String val = (String) constructScalar((ScalarNode) node); - return new Phone(val); - } - } + class MyConstructor extends Constructor { + + public MyConstructor() { + this.yamlConstructors.put(new Tag(Tag.PREFIX + "Phone"), new ConstructPhone()); } - class PointRepresenter extends Representer { - public PointRepresenter() { - this.representers.put(Point.class, new RepresentPoint()); - this.representers.put(Phone.class, new RepresentPhone()); - } - - private class RepresentPoint implements Represent { - public Node representData(Object data) { - Point phone = (Point) data; - String value = "x" + (int) phone.getX() + "_y" + (int) phone.getY(); - return representScalar(new Tag(Tag.PREFIX + "Point"), value); - } - } - - private class RepresentPhone implements Represent { - public Node representData(Object data) { - Phone phone = (Phone) data; - String value = phone.getNumber(); - return representScalar(new Tag(Tag.PREFIX + "Phone"), value); - } - } + private class ConstructPhone extends AbstractConstruct { + + public Object construct(Node node) { + String val = constructScalar((ScalarNode) node); + return new Phone(val); + } + } + } + + class PointRepresenter extends Representer { + + public PointRepresenter() { + this.representers.put(Point.class, new RepresentPoint()); + this.representers.put(Phone.class, new RepresentPhone()); + } + + private class RepresentPoint implements Represent { + + public Node representData(Object data) { + Point phone = (Point) data; + String value = "x" + (int) phone.getX() + "_y" + (int) phone.getY(); + return representScalar(new Tag(Tag.PREFIX + "Point"), value); + } + } + + private class RepresentPhone implements Represent { + + public Node representData(Object data) { + Phone phone = (Phone) data; + String value = phone.getNumber(); + return representScalar(new Tag(Tag.PREFIX + "Phone"), value); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/resolver/ResolverTupleTest.java b/src/test/java/org/yaml/snakeyaml/resolver/ResolverTupleTest.java index 4cac651a..1bde3455 100644 --- a/src/test/java/org/yaml/snakeyaml/resolver/ResolverTupleTest.java +++ b/src/test/java/org/yaml/snakeyaml/resolver/ResolverTupleTest.java @@ -1,30 +1,26 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.resolver; import java.util.regex.Pattern; - import junit.framework.TestCase; - import org.yaml.snakeyaml.nodes.Tag; public class ResolverTupleTest extends TestCase { - public void testToString() { - ResolverTuple tuple = new ResolverTuple(new Tag("dice"), Pattern.compile("\\d+")); - assertEquals("Tuple tag=dice regexp=\\d+", tuple.toString()); - } + public void testToString() { + ResolverTuple tuple = new ResolverTuple(new Tag("dice"), Pattern.compile("\\d+"), 5); + assertEquals("Tuple tag=dice regexp=\\d+ limit=5", tuple.toString()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/ruby/RubyTest.java b/src/test/java/org/yaml/snakeyaml/ruby/RubyTest.java index 7eaae71b..a9ae5658 100644 --- a/src/test/java/org/yaml/snakeyaml/ruby/RubyTest.java +++ b/src/test/java/org/yaml/snakeyaml/ruby/RubyTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.ruby; import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Util; @@ -27,87 +24,86 @@ import org.yaml.snakeyaml.representer.Representer; public class RubyTest extends TestCase { - public void testParse() { - TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); - assertNotNull(result); - assertEquals(0, result.getSub1().getAtt2()); - assertEquals("MyString", result.getSub2().getAtt1()); - assertEquals(1, result.getSub2().getAtt2().size()); - assertEquals(12345, result.getSub2().getAtt3()); - } + public void testParse() { + TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); + assertNotNull(result); + assertEquals(0, result.getSub1().getAtt2()); + assertEquals("MyString", result.getSub2().getAtt1()); + assertEquals(1, result.getSub2().getAtt2().size()); + assertEquals(12345, result.getSub2().getAtt3()); + } - public void testEmitNoTags() { - TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); - DumperOptions options = new DumperOptions(); - options.setExplicitStart(true); - Yaml yaml2 = new Yaml(options); - String output = yaml2.dumpAsMap(result); - assertFalse("No tags expected.", output.contains("Sub1")); - // System.out.println(output); - // parse back. Without tags it shall still work - Yaml beanLoader = new Yaml(); - TestObject result2 = beanLoader.loadAs(output, TestObject.class); - assertEquals(0, result2.getSub1().getAtt2()); - assertEquals("MyString", result2.getSub2().getAtt1()); - assertEquals(1, result2.getSub2().getAtt2().size()); - assertEquals(12345, result2.getSub2().getAtt3()); - } + public void testEmitNoTags() { + TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); + DumperOptions options = new DumperOptions(); + options.setExplicitStart(true); + Yaml yaml2 = new Yaml(options); + String output = yaml2.dumpAsMap(result); + assertFalse("No tags expected.", output.contains("Sub1")); + // System.out.println(output); + // parse back. Without tags it shall still work + Yaml beanLoader = new Yaml(); + TestObject result2 = beanLoader.loadAs(output, TestObject.class); + assertEquals(0, result2.getSub1().getAtt2()); + assertEquals("MyString", result2.getSub2().getAtt1()); + assertEquals(1, result2.getSub2().getAtt2().size()); + assertEquals(12345, result2.getSub2().getAtt3()); + } - public void testEmitWithTags() { - TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); - DumperOptions options = new DumperOptions(); - options.setExplicitStart(true); - Representer repr = new Representer(); - repr.addClassTag(TestObject.class, new Tag("!ruby/object:Test::Module::Object")); - repr.addClassTag(Sub1.class, new Tag("!ruby/object:Test::Module::Sub1")); - repr.addClassTag(Sub2.class, new Tag("!ruby/object:Test::Module::Sub2")); - Yaml yaml2 = new Yaml(repr, options); - String output = yaml2.dump(result); - // System.out.println(output); - assertTrue("Tags must be present.", - output.startsWith("--- !ruby/object:Test::Module::Object")); - assertTrue("Tags must be present: " + output, - output.contains("!ruby/object:Test::Module::Sub1")); - assertTrue("Tags must be present.", output.contains("!ruby/object:Test::Module::Sub2")); - // parse back. - TestObject result2 = parseObject(output); - assertEquals(0, result2.getSub1().getAtt2()); - assertEquals("MyString", result2.getSub2().getAtt1()); - assertEquals(1, result2.getSub2().getAtt2().size()); - assertEquals(12345, result2.getSub2().getAtt3()); - } + public void testEmitWithTags() { + TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); + DumperOptions options = new DumperOptions(); + options.setExplicitStart(true); + Representer repr = new Representer(); + repr.addClassTag(TestObject.class, new Tag("!ruby/object:Test::Module::Object")); + repr.addClassTag(Sub1.class, new Tag("!ruby/object:Test::Module::Sub1")); + repr.addClassTag(Sub2.class, new Tag("!ruby/object:Test::Module::Sub2")); + Yaml yaml2 = new Yaml(repr, options); + String output = yaml2.dump(result); + // System.out.println(output); + assertTrue("Tags must be present.", output.startsWith("--- !ruby/object:Test::Module::Object")); + assertTrue("Tags must be present: " + output, + output.contains("!ruby/object:Test::Module::Sub1")); + assertTrue("Tags must be present.", output.contains("!ruby/object:Test::Module::Sub2")); + // parse back. + TestObject result2 = parseObject(output); + assertEquals(0, result2.getSub1().getAtt2()); + assertEquals("MyString", result2.getSub2().getAtt1()); + assertEquals(1, result2.getSub2().getAtt2().size()); + assertEquals(12345, result2.getSub2().getAtt3()); + } - public void testEmitWithTags2WithoutTagForParentJavabean() { - TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); - DumperOptions options = new DumperOptions(); - options.setExplicitStart(true); - Representer repr = new Representer(); - repr.addClassTag(Sub1.class, new Tag("!ruby/object:Test::Module::Sub1")); - repr.addClassTag(Sub2.class, new Tag("!ruby/object:Test::Module::Sub2")); - Yaml yaml2 = new Yaml(repr, options); - String output = yaml2.dump(result); - // System.out.println(output); - assertTrue("Tags must be present.", - output.startsWith("--- !!org.yaml.snakeyaml.ruby.TestObject")); - assertTrue("Tags must be present: " + output, - output.contains("!ruby/object:Test::Module::Sub1")); - assertTrue("Tags must be present.", output.contains("!ruby/object:Test::Module::Sub2")); - // parse back. - TestObject result2 = parseObject(output); - assertEquals(0, result2.getSub1().getAtt2()); - assertEquals("MyString", result2.getSub2().getAtt1()); - assertEquals(1, result2.getSub2().getAtt2().size()); - assertEquals(12345, result2.getSub2().getAtt3()); - } + public void testEmitWithTags2WithoutTagForParentJavabean() { + TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml")); + DumperOptions options = new DumperOptions(); + options.setExplicitStart(true); + Representer repr = new Representer(); + repr.addClassTag(Sub1.class, new Tag("!ruby/object:Test::Module::Sub1")); + repr.addClassTag(Sub2.class, new Tag("!ruby/object:Test::Module::Sub2")); + Yaml yaml2 = new Yaml(repr, options); + String output = yaml2.dump(result); + // System.out.println(output); + assertTrue("Tags must be present.", + output.startsWith("--- !!org.yaml.snakeyaml.ruby.TestObject")); + assertTrue("Tags must be present: " + output, + output.contains("!ruby/object:Test::Module::Sub1")); + assertTrue("Tags must be present.", output.contains("!ruby/object:Test::Module::Sub2")); + // parse back. + TestObject result2 = parseObject(output); + assertEquals(0, result2.getSub1().getAtt2()); + assertEquals("MyString", result2.getSub2().getAtt1()); + assertEquals(1, result2.getSub2().getAtt2().size()); + assertEquals(12345, result2.getSub2().getAtt3()); + } - private TestObject parseObject(String input) { - Constructor con = new Constructor(TestObject.class); - con.addTypeDescription(new TypeDescription(TestObject.class, - "!ruby/object:Test::Module::Object")); - con.addTypeDescription(new TypeDescription(Sub1.class, "!ruby/object:Test::Module::Sub1")); - con.addTypeDescription(new TypeDescription(Sub2.class, "!ruby/object:Test::Module::Sub2")); + private TestObject parseObject(String input) { + Constructor con = new Constructor(TestObject.class); + con.addTypeDescription( + new TypeDescription(TestObject.class, "!ruby/object:Test::Module::Object")); + con.addTypeDescription(new TypeDescription(Sub1.class, "!ruby/object:Test::Module::Sub1")); + con.addTypeDescription(new TypeDescription(Sub2.class, "!ruby/object:Test::Module::Sub2")); - Yaml yaml = new Yaml(con); - return (TestObject) yaml.load(input); - } + Yaml yaml = new Yaml(con); + return yaml.load(input); + } } diff --git a/src/test/java/org/yaml/snakeyaml/ruby/Sub1.java b/src/test/java/org/yaml/snakeyaml/ruby/Sub1.java index 25618f4e..8ee1521d 100644 --- a/src/test/java/org/yaml/snakeyaml/ruby/Sub1.java +++ b/src/test/java/org/yaml/snakeyaml/ruby/Sub1.java @@ -1,48 +1,47 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.ruby; import java.util.List; public class Sub1 { - private List<Integer> att1; - private int att2; - private List<Integer> att3; - public List<Integer> getAtt1() { - return att1; - } + private List<Integer> att1; + private int att2; + private List<Integer> att3; - public void setAtt1(List<Integer> att1) { - this.att1 = att1; - } + public List<Integer> getAtt1() { + return att1; + } - public int getAtt2() { - return att2; - } + public void setAtt1(List<Integer> att1) { + this.att1 = att1; + } - public void setAtt2(int att2) { - this.att2 = att2; - } + public int getAtt2() { + return att2; + } - public List<Integer> getAtt3() { - return att3; - } + public void setAtt2(int att2) { + this.att2 = att2; + } - public void setAtt3(List<Integer> att3) { - this.att3 = att3; - } + public List<Integer> getAtt3() { + return att3; + } + + public void setAtt3(List<Integer> att3) { + this.att3 = att3; + } } diff --git a/src/test/java/org/yaml/snakeyaml/ruby/Sub2.java b/src/test/java/org/yaml/snakeyaml/ruby/Sub2.java index d8548f65..cf711248 100644 --- a/src/test/java/org/yaml/snakeyaml/ruby/Sub2.java +++ b/src/test/java/org/yaml/snakeyaml/ruby/Sub2.java @@ -1,49 +1,48 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.ruby; import java.util.List; public class Sub2 { - private String att1; - private List<String> att2; - private int att3; - public String getAtt1() { - return att1; - } + private String att1; + private List<String> att2; + private int att3; - public void setAtt1(String att1) { - this.att1 = att1; - } + public String getAtt1() { + return att1; + } - public List<String> getAtt2() { - return att2; - } + public void setAtt1(String att1) { + this.att1 = att1; + } - public void setAtt2(List<String> att2) { - this.att2 = att2; - } + public List<String> getAtt2() { + return att2; + } - public int getAtt3() { - return att3; - } + public void setAtt2(List<String> att2) { + this.att2 = att2; + } - public void setAtt3(int att3) { - this.att3 = att3; - } + public int getAtt3() { + return att3; + } + + public void setAtt3(int att3) { + this.att3 = att3; + } } diff --git a/src/test/java/org/yaml/snakeyaml/ruby/TestObject.java b/src/test/java/org/yaml/snakeyaml/ruby/TestObject.java index 2885d097..f677fc10 100644 --- a/src/test/java/org/yaml/snakeyaml/ruby/TestObject.java +++ b/src/test/java/org/yaml/snakeyaml/ruby/TestObject.java @@ -1,37 +1,36 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.ruby; public class TestObject { - private Sub1 sub1; - private Sub2 sub2; - public Sub1 getSub1() { - return sub1; - } + private Sub1 sub1; + private Sub2 sub2; - public void setSub1(Sub1 sub1) { - this.sub1 = sub1; - } + public Sub1 getSub1() { + return sub1; + } - public Sub2 getSub2() { - return sub2; - } + public void setSub1(Sub1 sub1) { + this.sub1 = sub1; + } - public void setSub2(Sub2 sub2) { - this.sub2 = sub2; - } + public Sub2 getSub2() { + return sub2; + } + + public void setSub2(Sub2 sub2) { + this.sub2 = sub2; + } } diff --git a/src/test/java/org/yaml/snakeyaml/scanner/ConstantTest.java b/src/test/java/org/yaml/snakeyaml/scanner/ConstantTest.java index 8a398578..52e6459a 100644 --- a/src/test/java/org/yaml/snakeyaml/scanner/ConstantTest.java +++ b/src/test/java/org/yaml/snakeyaml/scanner/ConstantTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; @@ -19,18 +17,18 @@ import junit.framework.TestCase; public class ConstantTest extends TestCase { - public void testHasChar() { - assertTrue(Constant.LINEBR.has('\n')); - assertTrue(Constant.LINEBR.has('\u0085')); - assertFalse(Constant.LINEBR.has(' ')); - } + public void testHasChar() { + assertTrue(Constant.LINEBR.has('\n')); + assertTrue(Constant.LINEBR.has('\u0085')); + assertFalse(Constant.LINEBR.has(' ')); + } - public void testHasStringChar() { - assertTrue(Constant.LINEBR.has(' ', " ")); - } + public void testHasStringChar() { + assertTrue(Constant.LINEBR.has(' ', " ")); + } - public void testHas0() { - assertTrue(Constant.LINEBR.has((char) 0, "\0")); - } + public void testHas0() { + assertTrue(Constant.LINEBR.has((char) 0, "\0")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/scanner/ScannerImplTest.java b/src/test/java/org/yaml/snakeyaml/scanner/ScannerImplTest.java index 4e194125..77e98d6a 100644 --- a/src/test/java/org/yaml/snakeyaml/scanner/ScannerImplTest.java +++ b/src/test/java/org/yaml/snakeyaml/scanner/ScannerImplTest.java @@ -1,24 +1,21 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; import java.util.LinkedList; - import junit.framework.TestCase; - +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.reader.StreamReader; @@ -33,38 +30,36 @@ import org.yaml.snakeyaml.tokens.ValueToken; public class ScannerImplTest extends TestCase { - public void testGetToken() { - String data = "string: abcd"; - StreamReader reader = new StreamReader(data); - Scanner scanner = new ScannerImpl(reader); - Mark dummy = new Mark("dummy", 0, 0, 0, "", 0); - LinkedList<Token> etalonTokens = new LinkedList<Token>(); - etalonTokens.add(new StreamStartToken(dummy, dummy)); - etalonTokens.add(new BlockMappingStartToken(dummy, dummy)); - etalonTokens.add(new KeyToken(dummy, dummy)); - etalonTokens.add(new ScalarToken("string", true, dummy, dummy, (char) 0)); - etalonTokens.add(new ValueToken(dummy, dummy)); - etalonTokens.add(new ScalarToken("abcd", true, dummy, dummy, (char) 0)); - etalonTokens.add(new BlockEndToken(dummy, dummy)); - etalonTokens.add(new StreamEndToken(dummy, dummy)); - while (!etalonTokens.isEmpty() && scanner.checkToken(etalonTokens.get(0).getTokenId())) { - assertEquals(etalonTokens.removeFirst(), scanner.getToken()); - } - assertFalse("Must contain no more tokens: " + scanner.getToken(), - scanner.checkToken(new Token.ID[0])); + public void testGetToken() { + String data = "string: abcd"; + StreamReader reader = new StreamReader(data); + Scanner scanner = new ScannerImpl(reader); + Mark dummy = new Mark("dummy", 0, 0, 0, "".toCharArray(), 0); + LinkedList<Token> etalonTokens = new LinkedList<Token>(); + etalonTokens.add(new StreamStartToken(dummy, dummy)); + etalonTokens.add(new BlockMappingStartToken(dummy, dummy)); + etalonTokens.add(new KeyToken(dummy, dummy)); + etalonTokens + .add(new ScalarToken("string", true, dummy, dummy, DumperOptions.ScalarStyle.PLAIN)); + etalonTokens.add(new ValueToken(dummy, dummy)); + etalonTokens.add(new ScalarToken("abcd", true, dummy, dummy, DumperOptions.ScalarStyle.PLAIN)); + etalonTokens.add(new BlockEndToken(dummy, dummy)); + etalonTokens.add(new StreamEndToken(dummy, dummy)); + while (!etalonTokens.isEmpty() && scanner.checkToken(etalonTokens.get(0).getTokenId())) { + assertEquals(etalonTokens.removeFirst().getTokenId(), scanner.getToken().getTokenId()); } + assertFalse("Must contain no more tokens.", scanner.checkToken()); + } - public void testWrongTab() { - Yaml yaml = new Yaml(); - try { - yaml.load("\t data: 1"); - fail("TAB cannot start a token."); - } catch (Exception e) { - assertEquals( - "while scanning for the next token\n" - + "found character '\\t(TAB)' that cannot start any token. (Do not use \\t(TAB) for indentation)\n" - + " in 'string', line 1, column 1:\n" + " \t data: 1\n" + " ^\n", - e.getMessage()); - } + public void testWrongTab() { + Yaml yaml = new Yaml(); + try { + yaml.load("\t data: 1"); + fail("TAB cannot start a token."); + } catch (Exception e) { + assertEquals("while scanning for the next token\n" + + "found character '\\t(TAB)' that cannot start any token. (Do not use \\t(TAB) for indentation)\n" + + " in 'string', line 1, column 1:\n" + " \t data: 1\n" + " ^\n", e.getMessage()); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/scanner/SimpleKeyTest.java b/src/test/java/org/yaml/snakeyaml/scanner/SimpleKeyTest.java index 8c577f3d..5d9c064a 100644 --- a/src/test/java/org/yaml/snakeyaml/scanner/SimpleKeyTest.java +++ b/src/test/java/org/yaml/snakeyaml/scanner/SimpleKeyTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.scanner; @@ -19,8 +17,8 @@ import junit.framework.TestCase; public class SimpleKeyTest extends TestCase { - public void testToString() { - SimpleKey key = new SimpleKey(1, false, 5, 3, 2, null); - assertTrue(key.toString().contains("SimpleKey")); - } + public void testToString() { + SimpleKey key = new SimpleKey(1, false, 5, 3, 2, null); + assertTrue(key.toString().contains("SimpleKey")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/serialization/TransientValuesTest.java b/src/test/java/org/yaml/snakeyaml/serialization/TransientValuesTest.java new file mode 100644 index 00000000..2bd3e80b --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/serialization/TransientValuesTest.java @@ -0,0 +1,83 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.serialization; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.beans.Transient; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class TransientValuesTest { + + // This test expects that transient fields and properties do not get (de)serialized, + // while non-transient fields and properties do get (de)serialized. + @Test + public void testDumpTransientFieldsAndProperties() throws Exception { + ClassWithTransientFields entity = new ClassWithTransientFields(); + entity.setNonTransientProperty("alpha"); + entity.setTransientProperty("beta"); + entity.transientField = "gamma"; + entity.nonTransientField = "delta"; + + Yaml yaml = new Yaml(); + String dumpedInstance = yaml.dump(entity); + yaml = new Yaml(new Constructor(ClassWithTransientFields.class.getName())); + ClassWithTransientFields deserializedEntity = yaml.load(dumpedInstance); + + assertTrue(dumpedInstance.contains("alpha")); + assertTrue(dumpedInstance.contains("delta")); + assertFalse(dumpedInstance.contains("gamma")); + assertFalse(dumpedInstance.contains("beta")); + + assertEquals("delta", deserializedEntity.nonTransientField); + assertEquals("alpha", deserializedEntity.getNonTransientProperty()); + assertNull(deserializedEntity.transientField); + assertNull(deserializedEntity.getTransientProperty()); + + } + + public static class ClassWithTransientFields { + + public String nonTransientField; + public transient String transientField; + + private String nonTransientProperty; + private String transientProperty; + + public String getNonTransientProperty() { + return nonTransientProperty; + } + + @Transient + public String getTransientProperty() { + return transientProperty; + } + + public void setNonTransientProperty(String nonTransientProperty) { + this.nonTransientProperty = nonTransientProperty; + } + + @Transient + public void setTransientProperty(String transientProperty) { + this.transientProperty = transientProperty; + } + + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/serializer/AnchorGeneratorTest.java b/src/test/java/org/yaml/snakeyaml/serializer/AnchorGeneratorTest.java index 82c04fba..59e0c631 100644 --- a/src/test/java/org/yaml/snakeyaml/serializer/AnchorGeneratorTest.java +++ b/src/test/java/org/yaml/snakeyaml/serializer/AnchorGeneratorTest.java @@ -1,68 +1,61 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.serializer; +import java.util.ArrayList; +import java.util.List; import junit.framework.TestCase; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.Tag; -import java.util.ArrayList; -import java.util.List; - public class AnchorGeneratorTest extends TestCase { - public void testNext() { - AnchorGenerator generator = new NumberAnchorGenerator(0); - assertEquals("id001", generator.nextAnchor(null)); - assertEquals("id002", generator.nextAnchor(null)); + public void testNext() { + AnchorGenerator generator = new NumberAnchorGenerator(0); + assertEquals("id001", generator.nextAnchor(null)); + assertEquals("id002", generator.nextAnchor(null)); + } + + public void testCustomGenerator() { + List<Object> list = new ArrayList<Object>(); + list.add("data123"); + list.add(list); + Yaml yaml1 = new Yaml(); + String output = yaml1.dump(list); + assertEquals("&id001\n" + "- data123\n" + "- *id001\n", output); + + DumperOptions options = new DumperOptions(); + Yaml yaml2 = new Yaml(options); + options.setAnchorGenerator(new Gener(3)); + String output2 = yaml2.dump(list); + assertEquals("&list-id004\n" + "- data123\n" + "- *list-id004\n", output2); + } + + class Gener extends NumberAnchorGenerator { + + public Gener(int lastAnchorId) { + super(lastAnchorId); } - public void testCustomGenerator() { - List<Object> list = new ArrayList<Object>(); - list.add("data123"); - list.add(list); - Yaml yaml1 = new Yaml(); - String output = yaml1.dump(list); - assertEquals("&id001\n" + - "- data123\n" + - "- *id001\n", output); - - - DumperOptions options = new DumperOptions(); - Yaml yaml2 = new Yaml(options); - options.setAnchorGenerator(new Gener(3)); - String output2 = yaml2.dump(list); - assertEquals("&list-id004\n" + - "- data123\n" + - "- *list-id004\n", output2); - } - - class Gener extends NumberAnchorGenerator { - - public Gener(int lastAnchorId) { - super(lastAnchorId); - } - - public String nextAnchor(Node node) { - if (node.getTag() == Tag.SEQ) - return "list-" + super.nextAnchor(node); - else - return super.nextAnchor(node); - } + public String nextAnchor(Node node) { + if (node.getTag() == Tag.SEQ) { + return "list-" + super.nextAnchor(node); + } else { + return super.nextAnchor(node); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/serializer/SerializerTest.java b/src/test/java/org/yaml/snakeyaml/serializer/SerializerTest.java index 69eaca49..a4008248 100644 --- a/src/test/java/org/yaml/snakeyaml/serializer/SerializerTest.java +++ b/src/test/java/org/yaml/snakeyaml/serializer/SerializerTest.java @@ -1,26 +1,22 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.serializer; import java.io.IOException; import java.io.StringWriter; import java.text.NumberFormat; - import junit.framework.TestCase; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.emitter.Emitter; import org.yaml.snakeyaml.nodes.ScalarNode; @@ -28,75 +24,78 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.resolver.Resolver; public class SerializerTest extends TestCase { - private Serializer serializer; - @Override - protected void setUp() { - DumperOptions config = new DumperOptions(); - StringWriter writer = new StringWriter(); - serializer = new Serializer(new Emitter(writer, config), new Resolver(), config, null); - } + private Serializer serializer; - public void testSerializerIsAlreadyOpened() throws IOException { - serializer.open(); - try { - serializer.open(); - fail(); - } catch (RuntimeException e) { - assertEquals("serializer is already opened", e.getMessage()); - } - } + @Override + protected void setUp() { + DumperOptions config = new DumperOptions(); + StringWriter writer = new StringWriter(); + serializer = new Serializer(new Emitter(writer, config), new Resolver(), config, null); + } - public void testSerializerIsClosed1() throws IOException { - serializer.open(); - serializer.close(); - try { - serializer.open(); - fail(); - } catch (RuntimeException e) { - assertEquals("serializer is closed", e.getMessage()); - } + public void testSerializerIsAlreadyOpened() throws IOException { + serializer.open(); + try { + serializer.open(); + fail(); + } catch (RuntimeException e) { + assertEquals("serializer is already opened", e.getMessage()); } + } - public void testSerializerIsClosed2() throws IOException { - serializer.open(); - serializer.close(); - try { - serializer.serialize(new ScalarNode(new Tag("!foo"), "bar", null, null, (char) 0)); - fail(); - } catch (RuntimeException e) { - assertEquals("serializer is closed", e.getMessage()); - } + public void testSerializerIsClosed1() throws IOException { + serializer.open(); + serializer.close(); + try { + serializer.open(); + fail(); + } catch (RuntimeException e) { + assertEquals("serializer is closed", e.getMessage()); } + } - public void testSerializerIsClosed3() throws IOException { - serializer.open(); - serializer.close(); - serializer.close();// no problem to close twice + public void testSerializerIsClosed2() throws IOException { + serializer.open(); + serializer.close(); + try { + serializer.serialize( + new ScalarNode(new Tag("!foo"), "bar", null, null, DumperOptions.ScalarStyle.PLAIN)); + fail(); + } catch (RuntimeException e) { + assertEquals("serializer is closed", e.getMessage()); } + } - public void testSerializerIsNotOpened1() throws IOException { - try { - serializer.close(); - fail(); - } catch (RuntimeException e) { - assertEquals("serializer is not opened", e.getMessage()); - } - } + public void testSerializerIsClosed3() throws IOException { + serializer.open(); + serializer.close(); + serializer.close();// no problem to close twice + } - public void testSerializerIsNotOpened2() throws IOException { - try { - serializer.serialize(new ScalarNode(new Tag("!foo"), "bar", null, null, (char) 0)); - fail(); - } catch (RuntimeException e) { - assertEquals("serializer is not opened", e.getMessage()); - } + public void testSerializerIsNotOpened1() throws IOException { + try { + serializer.close(); + fail(); + } catch (RuntimeException e) { + assertEquals("serializer is not opened", e.getMessage()); } + } - public void testGenerateAnchor() { - NumberFormat format = NumberFormat.getNumberInstance(); - format.setMinimumIntegerDigits(3); - String anchor = format.format(3L); - assertEquals("003", anchor); + public void testSerializerIsNotOpened2() throws IOException { + try { + serializer.serialize( + new ScalarNode(new Tag("!foo"), "bar", null, null, DumperOptions.ScalarStyle.PLAIN)); + fail(); + } catch (RuntimeException e) { + assertEquals("serializer is not opened", e.getMessage()); } + } + + public void testGenerateAnchor() { + NumberFormat format = NumberFormat.getNumberInstance(); + format.setMinimumIntegerDigits(3); + String anchor = format.format(3L); + assertEquals("003", anchor); + } } diff --git a/src/test/java/org/yaml/snakeyaml/stress/ParallelTest.java b/src/test/java/org/yaml/snakeyaml/stress/ParallelTest.java index 3bae53f0..e9fa4346 100644 --- a/src/test/java/org/yaml/snakeyaml/stress/ParallelTest.java +++ b/src/test/java/org/yaml/snakeyaml/stress/ParallelTest.java @@ -1,22 +1,19 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.stress; import junit.framework.TestCase; - import org.yaml.snakeyaml.Invoice; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; @@ -25,47 +22,49 @@ import org.yaml.snakeyaml.Yaml; * Test that Yaml instances are independent and can be used in multiple threads. */ public class ParallelTest extends TestCase { - private int progress = 0; - private int MAX = 5; - public void testPerfomance() { - String doc = Util.getLocalResource("specification/example2_27.yaml"); - for (int i = 0; i < MAX; i++) { - Worker worker = new Worker(i, doc); - Thread thread = new Thread(worker); - thread.start(); - } - while (progress < MAX - 1) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - fail(e.getMessage()); - } - } + private int progress = 0; + private final int MAX = 5; + + public void testPerfomance() { + String doc = Util.getLocalResource("specification/example2_27.yaml"); + for (int i = 0; i < MAX; i++) { + Worker worker = new Worker(i, doc); + Thread thread = new Thread(worker); + thread.start(); + } + while (progress < MAX - 1) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail(e.getMessage()); + } } + } - private class Worker implements Runnable { - private int id; - private String doc; + private class Worker implements Runnable { - public Worker(int id, String doc) { - this.id = id; - this.doc = doc; - } + private final int id; + private final String doc; + + public Worker(int id, String doc) { + this.id = id; + this.doc = doc; + } - public void run() { - System.out.println("Started: " + id); - Yaml loader = new Yaml(); - long time1 = System.nanoTime(); - int cycles = 200; - for (int i = 0; i < cycles; i++) { - Invoice invoice = loader.loadAs(doc, Invoice.class); - assertNotNull(invoice); - } - long time2 = System.nanoTime(); - float duration = ((time2 - time1) / 1000000) / (float) cycles; - System.out.println("Duration of " + id + " was " + duration + " ms/load."); - progress++; - } + public void run() { + System.out.println("Started: " + id); + Yaml loader = new Yaml(); + long time1 = System.nanoTime(); + int cycles = 200; + for (int i = 0; i < cycles; i++) { + Invoice invoice = loader.loadAs(doc, Invoice.class); + assertNotNull(invoice); + } + long time2 = System.nanoTime(); + float duration = ((time2 - time1) / 1000000) / (float) cycles; + System.out.println("Duration of " + id + " was " + duration + " ms/load."); + progress++; } + } } diff --git a/src/test/java/org/yaml/snakeyaml/stress/StressEmitterTest.java b/src/test/java/org/yaml/snakeyaml/stress/StressEmitterTest.java index 5185e020..1699d7e1 100644 --- a/src/test/java/org/yaml/snakeyaml/stress/StressEmitterTest.java +++ b/src/test/java/org/yaml/snakeyaml/stress/StressEmitterTest.java @@ -1,80 +1,77 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.stress; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; - import org.yaml.snakeyaml.Invoice; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; public class StressEmitterTest extends TestCase { - public static void main(String args[]) { - junit.textui.TestRunner.run(suite()); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public static Test suite() { - return new TestSuite(StressEmitterTest.class); - } + public static Test suite() { + return new TestSuite(StressEmitterTest.class); + } - public void testPerformance() { - Yaml loader = new Yaml(); - Invoice invoice = loader.loadAs(Util.getLocalResource("specification/example2_27.yaml"), - Invoice.class); - Yaml dumper = new Yaml(); - long time1 = System.nanoTime(); - dumper.dumpAsMap(invoice); - long time2 = System.nanoTime(); - float duration = (time2 - time1) / 1000000; - System.out.println("\nSingle dump was " + duration + " ms."); + public void testPerformance() { + Yaml loader = new Yaml(); + Invoice invoice = + loader.loadAs(Util.getLocalResource("specification/example2_27.yaml"), Invoice.class); + Yaml dumper = new Yaml(); + long time1 = System.nanoTime(); + dumper.dumpAsMap(invoice); + long time2 = System.nanoTime(); + float duration = (time2 - time1) / 1000000; + System.out.println("\nSingle dump was " + duration + " ms."); - int[] range = new int[] { 1000, 2000 /* , 8000 */}; - System.out.println("\nOne instance."); - for (int number : range) { - time1 = System.nanoTime(); - for (int i = 0; i < number; i++) { - dumper.dump(invoice); - } - time2 = System.nanoTime(); - duration = ((time2 - time1) / 1000000) / (float) number; - System.out.println("Duration for r=" + number + " was " + duration + " ms/dump."); - // cobertura may make it very slow - if (duration > 3) { - System.err.println("!!!!!! Too long. Expected <1 but was " + duration); - } - } + int[] range = new int[] {1000, 2000 /* , 8000 */}; + System.out.println("\nOne instance."); + for (int number : range) { + time1 = System.nanoTime(); + for (int i = 0; i < number; i++) { + dumper.dump(invoice); + } + time2 = System.nanoTime(); + duration = ((time2 - time1) / 1000000) / (float) number; + System.out.println("Duration for r=" + number + " was " + duration + " ms/dump."); + // cobertura may make it very slow + if (duration > 3) { + System.err.println("!!!!!! Too long. Expected <1 but was " + duration); + } + } - System.out.println("\nMany instances."); - for (int number : range) { - time1 = System.nanoTime(); - for (int i = 0; i < number; i++) { - dumper = new Yaml(); - dumper.dumpAsMap(invoice); - } - time2 = System.nanoTime(); - duration = ((time2 - time1) / 1000000) / (float) number; - System.out.println("Duration for r=" + number + " was " + duration + " ms/dump."); - // cobertura may make it very slow - if (duration > 3) { - System.err.println("!!!!!! Too long. Expected <1 but was " + duration); - } - // assertTrue("duration=" + duration, duration < 3); - } + System.out.println("\nMany instances."); + for (int number : range) { + time1 = System.nanoTime(); + for (int i = 0; i < number; i++) { + dumper = new Yaml(); + dumper.dumpAsMap(invoice); + } + time2 = System.nanoTime(); + duration = ((time2 - time1) / 1000000) / (float) number; + System.out.println("Duration for r=" + number + " was " + duration + " ms/dump."); + // cobertura may make it very slow + if (duration > 3) { + System.err.println("!!!!!! Too long. Expected <1 but was " + duration); + } + // assertTrue("duration=" + duration, duration < 3); } -}
\ No newline at end of file + } +} diff --git a/src/test/java/org/yaml/snakeyaml/stress/StressTest.java b/src/test/java/org/yaml/snakeyaml/stress/StressTest.java index 299d1a39..23f6688b 100644 --- a/src/test/java/org/yaml/snakeyaml/stress/StressTest.java +++ b/src/test/java/org/yaml/snakeyaml/stress/StressTest.java @@ -1,91 +1,89 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.stress; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; - import org.yaml.snakeyaml.Invoice; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class StressTest extends TestCase { - String doc; - public static void main(String args[]) { - junit.textui.TestRunner.run(suite()); - } + String doc; - public static Test suite() { - return new TestSuite(StressTest.class); - } + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } - public void setUp() { - doc = Util.getLocalResource("specification/example2_27.yaml"); - } + public static Test suite() { + return new TestSuite(StressTest.class); + } + + public void setUp() { + doc = Util.getLocalResource("specification/example2_27.yaml"); + } - public void testPerformance() { - long time1 = System.nanoTime(); - new Yaml(new Constructor(Invoice.class)); - long time2 = System.nanoTime(); - float duration = (time2 - time1) / 1000000; - System.out.println("Init was " + duration + " ms."); + public void testPerformance() { + long time1 = System.nanoTime(); + new Yaml(new Constructor(Invoice.class)); + long time2 = System.nanoTime(); + float duration = (time2 - time1) / 1000000; + System.out.println("Init was " + duration + " ms."); - Yaml loader = new Yaml(); - time1 = System.nanoTime(); + Yaml loader = new Yaml(); + time1 = System.nanoTime(); + loader.loadAs(doc, Invoice.class); + time2 = System.nanoTime(); + duration = (time2 - time1) / 1000000; + System.out.println("\nSingle load was " + duration + " ms."); + + loader = new Yaml(); + int[] range = new int[] {1000, 2000 /* , 4000, 8000 */}; + System.out.println("\nOne instance."); + for (int number : range) { + time1 = System.nanoTime(); + for (int i = 0; i < number; i++) { loader.loadAs(doc, Invoice.class); - time2 = System.nanoTime(); - duration = (time2 - time1) / 1000000; - System.out.println("\nSingle load was " + duration + " ms."); + } + time2 = System.nanoTime(); + duration = ((time2 - time1) / 1000000) / (float) number; + System.out.println("Duration for r=" + number + " was " + duration + " ms/load."); + // cobertura may make it very slow + if (duration > 3) { + System.err.println("!!!!!! Too long. Expected <1 but was " + duration); + } + // assertTrue("duration=" + duration, duration < 3); + } + System.out.println("\nMany instances."); + for (int number : range) { + time1 = System.nanoTime(); + for (int i = 0; i < number; i++) { loader = new Yaml(); - int[] range = new int[] { 1000, 2000 /* , 4000, 8000 */}; - System.out.println("\nOne instance."); - for (int number : range) { - time1 = System.nanoTime(); - for (int i = 0; i < number; i++) { - loader.loadAs(doc, Invoice.class); - } - time2 = System.nanoTime(); - duration = ((time2 - time1) / 1000000) / (float) number; - System.out.println("Duration for r=" + number + " was " + duration + " ms/load."); - // cobertura may make it very slow - if (duration > 3) { - System.err.println("!!!!!! Too long. Expected <1 but was " + duration); - } - // assertTrue("duration=" + duration, duration < 3); - } - - System.out.println("\nMany instances."); - for (int number : range) { - time1 = System.nanoTime(); - for (int i = 0; i < number; i++) { - loader = new Yaml(); - loader.loadAs(doc, Invoice.class); - } - time2 = System.nanoTime(); - duration = ((time2 - time1) / 1000000) / (float) number; - System.out.println("Duration for r=" + number + " was " + duration + " ms/load."); - // cobertura may make it very slow - if (duration > 3) { - System.err.println("!!!!!! Too long. Expected <1 but was " + duration); - } - // assertTrue("duration=" + duration, duration < 3); - } + loader.loadAs(doc, Invoice.class); + } + time2 = System.nanoTime(); + duration = ((time2 - time1) / 1000000) / (float) number; + System.out.println("Duration for r=" + number + " was " + duration + " ms/load."); + // cobertura may make it very slow + if (duration > 3) { + System.err.println("!!!!!! Too long. Expected <1 but was " + duration); + } + // assertTrue("duration=" + duration, duration < 3); } -}
\ No newline at end of file + } +} diff --git a/src/test/java/org/yaml/snakeyaml/tokens/AliasTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/AliasTokenTest.java index da0fd421..65f59993 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/AliasTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/AliasTokenTest.java @@ -1,42 +1,35 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; -import junit.framework.TestCase; +import static org.junit.Assert.assertNotEquals; +import junit.framework.TestCase; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class AliasTokenTest extends TestCase { - public void testEquals() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - AliasToken token = new AliasToken("*id123", mark, mark); - assertFalse(token.equals(mark)); - } - - public void testGetArguments() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - AliasToken token = new AliasToken("*id123", mark, mark); - assertEquals("value=*id123", token.getArguments()); - } + public void testEquals() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + AliasToken token = new AliasToken("*id123", mark, mark); + assertNotEquals(token, mark); + } - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - AliasToken token = new AliasToken("&id123", mark, mark); - assertEquals(ID.Alias, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + AliasToken token = new AliasToken("&id123", mark, mark); + assertEquals(ID.Alias, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/AnchorTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/AnchorTokenTest.java index 472f7d23..357707cb 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/AnchorTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/AnchorTokenTest.java @@ -1,36 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class AnchorTokenTest extends TestCase { - public void testGetArguments() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - AnchorToken token = new AnchorToken("&id123", mark, mark); - assertEquals("value=&id123", token.getArguments()); - } - - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - AnchorToken token = new AnchorToken("&id123", mark, mark); - assertEquals(ID.Anchor, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + AnchorToken token = new AnchorToken("&id123", mark, mark); + assertEquals(ID.Anchor, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/BlockEndTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/BlockEndTokenTest.java index 3c96859d..8030e92b 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/BlockEndTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/BlockEndTokenTest.java @@ -1,36 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class BlockEndTokenTest extends TestCase { - public void testGetArguments() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - BlockEndToken token = new BlockEndToken(mark, mark); - assertEquals("", token.getArguments()); - } - - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - BlockEndToken token = new BlockEndToken(mark, mark); - assertEquals(ID.BlockEnd, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + BlockEndToken token = new BlockEndToken(mark, mark); + assertEquals(ID.BlockEnd, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/BlockEntryTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/BlockEntryTokenTest.java index 651a2309..a7a8485a 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/BlockEntryTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/BlockEntryTokenTest.java @@ -1,31 +1,28 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class BlockEntryTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - BlockEntryToken token = new BlockEntryToken(mark, mark); - assertEquals(ID.BlockEntry, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + BlockEntryToken token = new BlockEntryToken(mark, mark); + assertEquals(ID.BlockEntry, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/BlockSequenceStartTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/BlockSequenceStartTokenTest.java index 69203d0a..bdd0c667 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/BlockSequenceStartTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/BlockSequenceStartTokenTest.java @@ -1,30 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class BlockSequenceStartTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - BlockSequenceStartToken token = new BlockSequenceStartToken(mark, mark); - assertEquals(ID.BlockSequenceStart, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + BlockSequenceStartToken token = new BlockSequenceStartToken(mark, mark); + assertEquals(ID.BlockSequenceStart, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/DirectiveTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/DirectiveTokenTest.java index f1e8ff15..4029c66d 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/DirectiveTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/DirectiveTokenTest.java @@ -1,69 +1,41 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import java.util.ArrayList; import java.util.List; - import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class DirectiveTokenTest extends TestCase { - public void testGetArguments() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - DirectiveToken<Integer> token = new DirectiveToken<Integer>("YAML", null, mark, mark); - assertEquals("name=YAML", token.getArguments()); + public void testInvalidList() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + List<Integer> list = new ArrayList<Integer>(); + list.add(Integer.valueOf(1)); + try { + new DirectiveToken<Integer>("YAML", list, mark, mark); + fail("List must have 2 values."); + } catch (Exception e) { + assertEquals("Two strings must be provided instead of 1", e.getMessage()); } + } - public void testInvalidList() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - List<Integer> list = new ArrayList<Integer>(); - list.add(new Integer(1)); - try { - new DirectiveToken<Integer>("YAML", list, mark, mark); - fail("List must have 2 values."); - } catch (Exception e) { - assertEquals("Two strings must be provided instead of 1", e.getMessage()); - } - } - - public void testTag() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - List<String> list = new ArrayList<String>(); - list.add("!foo"); - list.add("!bar"); - DirectiveToken<String> token = new DirectiveToken<String>("TAG", list, mark, mark); - assertEquals("name=TAG, value=[!foo, !bar]", token.getArguments()); - } - - public void testList() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - List<Integer> list = new ArrayList<Integer>(); - list.add(new Integer(1)); - list.add(new Integer(1)); - DirectiveToken<Integer> token = new DirectiveToken<Integer>("YAML", list, mark, mark); - assertEquals("name=YAML, value=[1, 1]", token.getArguments()); - } - - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - DirectiveToken<Integer> token = new DirectiveToken<Integer>("YAML", null, mark, mark); - assertEquals(ID.Directive, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + DirectiveToken<Integer> token = new DirectiveToken<Integer>("YAML", null, mark, mark); + assertEquals(ID.Directive, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/DocumentEndTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/DocumentEndTokenTest.java index a6955bac..1b97ff7e 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/DocumentEndTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/DocumentEndTokenTest.java @@ -1,30 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class DocumentEndTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - DocumentEndToken token = new DocumentEndToken(mark, mark); - assertEquals(ID.DocumentEnd, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + DocumentEndToken token = new DocumentEndToken(mark, mark); + assertEquals(ID.DocumentEnd, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/DocumentStartTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/DocumentStartTokenTest.java index f7fa01e8..c5d33e59 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/DocumentStartTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/DocumentStartTokenTest.java @@ -1,30 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class DocumentStartTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - DocumentStartToken token = new DocumentStartToken(mark, mark); - assertEquals(ID.DocumentStart, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + DocumentStartToken token = new DocumentStartToken(mark, mark); + assertEquals(ID.DocumentStart, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/FlowEntryTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/FlowEntryTokenTest.java index 3293919c..4e81201b 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/FlowEntryTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/FlowEntryTokenTest.java @@ -1,30 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class FlowEntryTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - FlowEntryToken token = new FlowEntryToken(mark, mark); - assertEquals(ID.FlowEntry, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + FlowEntryToken token = new FlowEntryToken(mark, mark); + assertEquals(ID.FlowEntry, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/FlowMappingStartTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/FlowMappingStartTokenTest.java index 4548552d..937ef3ba 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/FlowMappingStartTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/FlowMappingStartTokenTest.java @@ -1,30 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class FlowMappingStartTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - FlowMappingStartToken token = new FlowMappingStartToken(mark, mark); - assertEquals(ID.FlowMappingStart, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + FlowMappingStartToken token = new FlowMappingStartToken(mark, mark); + assertEquals(ID.FlowMappingStart, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/FlowSequenceStartTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/FlowSequenceStartTokenTest.java index b62e6a89..c2548f28 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/FlowSequenceStartTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/FlowSequenceStartTokenTest.java @@ -1,30 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class FlowSequenceStartTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - FlowSequenceStartToken token = new FlowSequenceStartToken(mark, mark); - assertEquals(ID.FlowSequenceStart, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + FlowSequenceStartToken token = new FlowSequenceStartToken(mark, mark); + assertEquals(ID.FlowSequenceStart, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/StreamStartTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/StreamStartTokenTest.java index 8ae19a42..1f02186d 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/StreamStartTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/StreamStartTokenTest.java @@ -1,30 +1,27 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.tokens.Token.ID; public class StreamStartTokenTest extends TestCase { - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - StreamStartToken token = new StreamStartToken(mark, mark); - assertEquals(ID.StreamStart, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + StreamStartToken token = new StreamStartToken(mark, mark); + assertEquals(ID.StreamStart, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/TagTokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/TagTokenTest.java index 11940884..1c057f44 100644 --- a/src/test/java/org/yaml/snakeyaml/tokens/TagTokenTest.java +++ b/src/test/java/org/yaml/snakeyaml/tokens/TagTokenTest.java @@ -1,63 +1,54 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.tokens; import junit.framework.TestCase; - import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.tokens.Token.ID; public class TagTokenTest extends TestCase { - public void testGetArguments() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - TagToken token = new TagToken(new TagTuple("!foo", "!bar"), mark, mark); - assertEquals("value=[!foo, !bar]", token.getArguments()); + public void testNoMarks() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + try { + new TagToken(new TagTuple("!foo", "!bar"), null, mark); + fail("Token without start mark should not be accepted."); + } catch (YAMLException e) { + assertEquals("Token requires marks.", e.getMessage()); } - - public void testNoMarks() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - try { - new TagToken(new TagTuple("!foo", "!bar"), null, mark); - fail("Token without start mark should not be accepted."); - } catch (YAMLException e) { - assertEquals("Token requires marks.", e.getMessage()); - } - try { - new TagToken(new TagTuple("!foo", "!bar"), mark, null); - fail("Token without end mark should not be accepted."); - } catch (YAMLException e) { - assertEquals("Token requires marks.", e.getMessage()); - } + try { + new TagToken(new TagTuple("!foo", "!bar"), mark, null); + fail("Token without end mark should not be accepted."); + } catch (YAMLException e) { + assertEquals("Token requires marks.", e.getMessage()); } + } - public void testNoTag() { - try { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - new TagToken(new TagTuple("!foo", null), mark, mark); - fail("Marks must be provided."); - } catch (NullPointerException e) { - assertEquals("Suffix must be provided.", e.getMessage()); - } + public void testNoTag() { + try { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + new TagToken(new TagTuple("!foo", null), mark, mark); + fail("Marks must be provided."); + } catch (NullPointerException e) { + assertEquals("Suffix must be provided.", e.getMessage()); } + } - public void testGetTokenId() { - Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); - TagToken token = new TagToken(new TagTuple("!foo", "!bar"), mark, mark); - assertEquals(ID.Tag, token.getTokenId()); - } + public void testGetTokenId() { + Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.".toCharArray(), 0); + TagToken token = new TagToken(new TagTuple("!foo", "!bar"), mark, mark); + assertEquals(ID.Tag, token.getTokenId()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/tokens/TokenTest.java b/src/test/java/org/yaml/snakeyaml/tokens/TokenTest.java new file mode 100644 index 00000000..fa7051bc --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/tokens/TokenTest.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.tokens; + +import junit.framework.TestCase; + +public class TokenTest extends TestCase { + + public void testTokenID() { + assertEquals("<alias>", Token.ID.Alias.toString()); + assertEquals("<anchor>", Token.ID.Anchor.toString()); + assertEquals("<block end>", Token.ID.BlockEnd.toString()); + assertEquals("-", Token.ID.BlockEntry.toString()); + assertEquals("<block mapping start>", Token.ID.BlockMappingStart.toString()); + assertEquals("<block sequence start>", Token.ID.BlockSequenceStart.toString()); + assertEquals("<directive>", Token.ID.Directive.toString()); + assertEquals("<document end>", Token.ID.DocumentEnd.toString()); + assertEquals("<document start>", Token.ID.DocumentStart.toString()); + assertEquals(",", Token.ID.FlowEntry.toString()); + assertEquals("}", Token.ID.FlowMappingEnd.toString()); + assertEquals("{", Token.ID.FlowMappingStart.toString()); + assertEquals("]", Token.ID.FlowSequenceEnd.toString()); + assertEquals("[", Token.ID.FlowSequenceStart.toString()); + assertEquals("?", Token.ID.Key.toString()); + assertEquals("<scalar>", Token.ID.Scalar.toString()); + assertEquals("<stream end>", Token.ID.StreamEnd.toString()); + assertEquals("<stream start>", Token.ID.StreamStart.toString()); + assertEquals("<tag>", Token.ID.Tag.toString()); + assertEquals(":", Token.ID.Value.toString()); + assertEquals("<whitespace>", Token.ID.Whitespace.toString()); + assertEquals("#", Token.ID.Comment.toString()); + assertEquals("<error>", Token.ID.Error.toString()); + } +} + diff --git a/src/test/java/org/yaml/snakeyaml/types/AbstractTest.java b/src/test/java/org/yaml/snakeyaml/types/AbstractTest.java index 91fd03c8..10e8c263 100644 --- a/src/test/java/org/yaml/snakeyaml/types/AbstractTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/AbstractTest.java @@ -1,47 +1,44 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.util.Map; - import junit.framework.TestCase; - import org.yaml.snakeyaml.Yaml; public abstract class AbstractTest extends TestCase { - @SuppressWarnings("unchecked") - protected Map<String, Object> getMap(String data) { - Yaml yaml = new Yaml(); - Map<String, Object> nativeData = (Map<String, Object>) yaml.load(data); - return nativeData; - } - protected Object load(String data) { - Yaml yaml = new Yaml(); - Object obj = yaml.load(data); - return obj; - } + @SuppressWarnings("unchecked") + protected Map<String, Object> getMap(String data) { + Yaml yaml = new Yaml(); + Map<String, Object> nativeData = yaml.load(data); + return nativeData; + } + + protected Object load(String data) { + Yaml yaml = new Yaml(); + Object obj = yaml.load(data); + return obj; + } - protected String dump(Object data) { - Yaml yaml = new Yaml(); - return yaml.dump(data); - } + protected String dump(Object data) { + Yaml yaml = new Yaml(); + return yaml.dump(data); + } - protected Object getMapValue(String data, String key) { - Map<String, Object> nativeData = getMap(data); - return nativeData.get(key); - } + protected Object getMapValue(String data, String key) { + Map<String, Object> nativeData = getMap(data); + return nativeData.get(key); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/BinaryTagTest.java b/src/test/java/org/yaml/snakeyaml/types/BinaryTagTest.java index 82ff9477..803685f9 100644 --- a/src/test/java/org/yaml/snakeyaml/types/BinaryTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/BinaryTagTest.java @@ -1,76 +1,76 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; /** - * @see <a href="http://yaml.org/type/binary.html"></a> + * @see <a href="http://yaml.org/type/binary.html">binary</a> */ public class BinaryTagTest extends AbstractTest { - String line1 = "R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5"; - String line2 = "OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+"; - String line3 = "+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC"; - String line4 = "AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="; - String content = line1 + line2 + line3 + line4; - public void testBinary() { - byte[] binary = (byte[]) getMapValue("canonical: !!binary " + content, "canonical"); - assertEquals((byte) 'G', binary[0]); - assertEquals((byte) 'I', binary[1]); - assertEquals((byte) 'F', binary[2]); - assertEquals((byte) '8', binary[3]); - assertEquals((byte) '9', binary[4]); - } + String line1 = "R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5"; + String line2 = "OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+"; + String line3 = "+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC"; + String line4 = "AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="; + String content = line1 + line2 + line3 + line4; - public void testBinary2() { - byte[] binary = (byte[]) load("!!binary \"MQ==\""); - assertEquals(1, binary.length); - assertEquals((byte) '1', binary[0]); - } + public void testBinary() { + byte[] binary = (byte[]) getMapValue("canonical: !!binary " + content, "canonical"); + assertEquals((byte) 'G', binary[0]); + assertEquals((byte) 'I', binary[1]); + assertEquals((byte) 'F', binary[2]); + assertEquals((byte) '8', binary[3]); + assertEquals((byte) '9', binary[4]); + } - public void testBinaryTag() { - byte[] binary = (byte[]) getMapValue("canonical: !<tag:yaml.org,2002:binary> " + content, - "canonical"); - assertEquals((byte) 'G', binary[0]); - assertEquals((byte) 'I', binary[1]); - assertEquals((byte) 'F', binary[2]); - assertEquals((byte) '8', binary[3]); - assertEquals((byte) '9', binary[4]); - } + public void testBinary2() { + byte[] binary = (byte[]) load("!!binary \"MQ==\""); + assertEquals(1, binary.length); + assertEquals((byte) '1', binary[0]); + } - public void testBinaryOut() throws IOException { - byte[] data = "GIF89\tbi\u0003\u0000nary\n\u001Fimage\n".getBytes("ISO-8859-1"); - Map<String, String> map = new HashMap<String, String>(); - String value = new String(data, "ISO-8859-1"); - map.put("canonical", value); - String output = dump(map); - assertEquals("canonical: !!binary |-\n R0lGODkJYmkDAG5hcnkKH2ltYWdlCg==\n", output); - } + public void testBinaryTag() { + byte[] binary = + (byte[]) getMapValue("canonical: !<tag:yaml.org,2002:binary> " + content, "canonical"); + assertEquals((byte) 'G', binary[0]); + assertEquals((byte) 'I', binary[1]); + assertEquals((byte) 'F', binary[2]); + assertEquals((byte) '8', binary[3]); + assertEquals((byte) '9', binary[4]); + } + + public void testBinaryOut() throws IOException { + byte[] data = "GIF89\tbi\u0003\u0000nary\n\u001Fimage\n".getBytes(StandardCharsets.ISO_8859_1); + Map<String, String> map = new HashMap<String, String>(); + String value = new String(data, StandardCharsets.ISO_8859_1); + map.put("canonical", value); + String output = dump(map); + assertEquals("canonical: !!binary |-\n R0lGODkJYmkDAG5hcnkKH2ltYWdlCg==\n", output); + } - public void testByteArray() { - byte[] data = { 8, 14, 15, 10, 126, 32, 65, 65, 65 }; - String output = dump(data); - assertEquals("!!binary |-\n CA4PCn4gQUFB\n", output); - byte[] parsed = (byte[]) load(output); - assertEquals(data.length, parsed.length); - for (int i = 0; i < data.length; i++) { - assertEquals(data[i], parsed[i]); - } + public void testByteArray() { + byte[] data = {8, 14, 15, 10, 126, 32, 65, 65, 65}; + String output = dump(data); + assertEquals("!!binary |-\n CA4PCn4gQUFB\n", output); + byte[] parsed = (byte[]) load(output); + assertEquals(data.length, parsed.length); + for (int i = 0; i < data.length; i++) { + assertEquals(data[i], parsed[i]); } + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/BoolTagTest.java b/src/test/java/org/yaml/snakeyaml/types/BoolTagTest.java index 96b2b3a1..d048d488 100644 --- a/src/test/java/org/yaml/snakeyaml/types/BoolTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/BoolTagTest.java @@ -1,23 +1,20 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.util.HashMap; import java.util.Map; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; @@ -27,107 +24,109 @@ import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; /** - * @see <a href="http://yaml.org/type/bool.html"></a> + * @see <a href="http://yaml.org/type/bool.html">bool</a> */ public class BoolTagTest extends AbstractTest { - public void testBool() { - assertEquals(Boolean.TRUE, getMapValue("canonical: true", "canonical")); - assertEquals(Boolean.FALSE, getMapValue("answer: NO", "answer")); - assertEquals(Boolean.TRUE, getMapValue("logical: True", "logical")); - assertEquals(Boolean.TRUE, getMapValue("option: on", "option")); - } - public void testBoolCanonical() { - assertEquals(Boolean.TRUE, getMapValue("canonical: Yes", "canonical")); - assertEquals(Boolean.TRUE, getMapValue("canonical: yes", "canonical")); - assertEquals(Boolean.TRUE, getMapValue("canonical: YES", "canonical")); - assertEquals("yES", getMapValue("canonical: yES", "canonical")); - assertEquals(Boolean.FALSE, getMapValue("canonical: No", "canonical")); - assertEquals(Boolean.FALSE, getMapValue("canonical: NO", "canonical")); - assertEquals(Boolean.FALSE, getMapValue("canonical: no", "canonical")); - assertEquals(Boolean.FALSE, getMapValue("canonical: off", "canonical")); - assertEquals(Boolean.FALSE, getMapValue("canonical: Off", "canonical")); - assertEquals(Boolean.FALSE, getMapValue("canonical: OFF", "canonical")); - assertEquals(Boolean.TRUE, getMapValue("canonical: ON", "canonical")); - assertEquals(Boolean.TRUE, getMapValue("canonical: On", "canonical")); - assertEquals(Boolean.TRUE, getMapValue("canonical: on", "canonical")); - // it looks like it is against the specification but it is like in - // PyYAML - assertEquals("n", getMapValue("canonical: n", "canonical")); - assertEquals("N", getMapValue("canonical: N", "canonical")); - assertEquals("y", getMapValue("canonical: y", "canonical")); - assertEquals("Y", getMapValue("canonical: Y", "canonical")); - } + public void testBool() { + assertEquals(Boolean.TRUE, getMapValue("canonical: true", "canonical")); + assertEquals(Boolean.FALSE, getMapValue("answer: NO", "answer")); + assertEquals(Boolean.TRUE, getMapValue("logical: True", "logical")); + assertEquals(Boolean.TRUE, getMapValue("option: on", "option")); + } - public void testBoolShorthand() { - assertEquals(Boolean.TRUE, getMapValue("boolean: !!bool true", "boolean")); - } + public void testBoolCanonical() { + assertEquals(Boolean.TRUE, getMapValue("canonical: Yes", "canonical")); + assertEquals(Boolean.TRUE, getMapValue("canonical: yes", "canonical")); + assertEquals(Boolean.TRUE, getMapValue("canonical: YES", "canonical")); + assertEquals("yES", getMapValue("canonical: yES", "canonical")); + assertEquals(Boolean.FALSE, getMapValue("canonical: No", "canonical")); + assertEquals(Boolean.FALSE, getMapValue("canonical: NO", "canonical")); + assertEquals(Boolean.FALSE, getMapValue("canonical: no", "canonical")); + assertEquals(Boolean.FALSE, getMapValue("canonical: off", "canonical")); + assertEquals(Boolean.FALSE, getMapValue("canonical: Off", "canonical")); + assertEquals(Boolean.FALSE, getMapValue("canonical: OFF", "canonical")); + assertEquals(Boolean.TRUE, getMapValue("canonical: ON", "canonical")); + assertEquals(Boolean.TRUE, getMapValue("canonical: On", "canonical")); + assertEquals(Boolean.TRUE, getMapValue("canonical: on", "canonical")); + // it looks like it is against the specification but it is like in + // PyYAML + assertEquals("n", getMapValue("canonical: n", "canonical")); + assertEquals("N", getMapValue("canonical: N", "canonical")); + assertEquals("y", getMapValue("canonical: y", "canonical")); + assertEquals("Y", getMapValue("canonical: Y", "canonical")); + } - public void testBoolTag() { - assertEquals(Boolean.TRUE, - getMapValue("boolean: !<tag:yaml.org,2002:bool> true", "boolean")); - } + public void testBoolShorthand() { + assertEquals(Boolean.TRUE, getMapValue("boolean: !!bool true", "boolean")); + } - public void testBoolOut() { - Map<String, Boolean> map = new HashMap<String, Boolean>(); - map.put("boolean", Boolean.TRUE); - String output = dump(map); - assertTrue(output, output.contains("boolean: true")); - } + public void testBoolTag() { + assertEquals(Boolean.TRUE, getMapValue("boolean: !<tag:yaml.org,2002:bool> true", "boolean")); + } - public void testBoolOutAsYes() { - Yaml yaml = new Yaml(new BoolRepresenter("YES")); - String output = yaml.dump(true); - assertEquals("YES\n", output); - } + public void testBoolOut() { + Map<String, Boolean> map = new HashMap<String, Boolean>(); + map.put("boolean", Boolean.TRUE); + String output = dump(map); + assertTrue(output, output.contains("boolean: true")); + } - /** - * test flow style - */ - public void testBoolOutAsEmpty2() { - Yaml yaml = new Yaml(new BoolRepresenter("on")); - Map<String, Boolean> map = new HashMap<String, Boolean>(); - map.put("aaa", false); - map.put("bbb", true); - String output = yaml.dump(map); - assertEquals("{aaa: false, bbb: on}\n", output); - } + public void testBoolOutAsYes() { + Yaml yaml = new Yaml(new BoolRepresenter("YES")); + String output = yaml.dump(true); + assertEquals("YES\n", output); + } - /** - * test block style - */ - public void testBoolOutAsEmpty3() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(new BoolRepresenter("True"), options); - Map<String, Boolean> map = new HashMap<String, Boolean>(); - map.put("aaa", false); - map.put("bbb", true); - String output = yaml.dump(map); - assertEquals("aaa: false\nbbb: True\n", output); - } + /** + * test flow style + */ + public void testBoolOutAsEmpty2() { + Yaml yaml = new Yaml(new BoolRepresenter("on")); + Map<String, Boolean> map = new HashMap<String, Boolean>(); + map.put("aaa", false); + map.put("bbb", true); + String output = yaml.dump(map); + assertEquals("{aaa: false, bbb: on}\n", output); + } - private class BoolRepresenter extends Representer { - private String value; + /** + * test block style + */ + public void testBoolOutAsEmpty3() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(new BoolRepresenter("True"), options); + Map<String, Boolean> map = new HashMap<String, Boolean>(); + map.put("aaa", false); + map.put("bbb", true); + String output = yaml.dump(map); + assertEquals("aaa: false\nbbb: True\n", output); + } - public BoolRepresenter(String value) { - super(); - this.value = value; - this.representers.put(Boolean.class, new RepresentBool()); - } + private class BoolRepresenter extends Representer { + + private final String value; + + public BoolRepresenter(String value) { + super(); + this.value = value; + this.representers.put(Boolean.class, new RepresentBool()); + } + + // possible values are here http://yaml.org/type/bool.html + // y, Y, n, N should not be used + private class RepresentBool implements Represent { - // possible values are here http://yaml.org/type/bool.html - // y, Y, n, N should not be used - private class RepresentBool implements Represent { - public Node representData(Object data) { - String v; - if (Boolean.TRUE.equals(data)) { - v = value; - } else { - v = "false"; - } - return representScalar(Tag.BOOL, v); - } + public Node representData(Object data) { + String v; + if (Boolean.TRUE.equals(data)) { + v = value; + } else { + v = "false"; } + return representScalar(Tag.BOOL, v); + } } + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/FloatTagTest.java b/src/test/java/org/yaml/snakeyaml/types/FloatTagTest.java index c517f660..7369e5e7 100644 --- a/src/test/java/org/yaml/snakeyaml/types/FloatTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/FloatTagTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; @@ -19,59 +17,59 @@ import java.util.HashMap; import java.util.Map; /** - * @see <a href="http://yaml.org/type/float.html"></a> + * @see <a href="http://yaml.org/type/float.html">float</a> */ public class FloatTagTest extends AbstractTest { - public void testFloat() { - assertEquals(new Double(6.8523015e+5), getMapValue("canonical: 6.8523015e+5", "canonical")); - assertEquals(new Double(6.8523015e+5), - getMapValue("exponentioal: 685.230_15e+03", "exponentioal")); - assertEquals(new Double(6.8523015e+5), getMapValue("fixed: 685_230.15", "fixed")); - assertEquals(new Double(6.8523015e+5), - getMapValue("sexagesimal: 190:20:30.15", "sexagesimal")); - assertEquals(Double.NEGATIVE_INFINITY, - getMapValue("negative infinity: -.inf", "negative infinity")); - assertEquals(Double.NaN, getMapValue("not a number: .NaN", "not a number")); - } + public void testFloat() { + assertEquals(Double.valueOf(6.8523015e+5), getMapValue("canonical: 6.8523015e+5", "canonical")); + assertEquals(Double.valueOf(6.8523015e+5), + getMapValue("exponentioal: 685.230_15e+03", "exponentioal")); + assertEquals(Double.valueOf(6.8523015e+5), getMapValue("fixed: 685_230.15", "fixed")); + assertEquals(Double.valueOf(6.8523015e+5), + getMapValue("sexagesimal: 190:20:30.15", "sexagesimal")); + assertEquals(Double.NEGATIVE_INFINITY, + getMapValue("negative infinity: -.inf", "negative infinity")); + assertEquals(Double.NaN, getMapValue("not a number: .NaN", "not a number")); + } - public void testFloatShorthand() { - assertEquals(new Double(1), getMapValue("number: !!float 1", "number")); - } + public void testFloatShorthand() { + assertEquals(Double.valueOf(1), getMapValue("number: !!float 1", "number")); + } - public void testFloatTag() { - assertEquals(new Double(1), getMapValue("number: !<tag:yaml.org,2002:float> 1", "number")); - } + public void testFloatTag() { + assertEquals(Double.valueOf(1), getMapValue("number: !<tag:yaml.org,2002:float> 1", "number")); + } - public void testFloatOut() { - Map<String, Object> map = new HashMap<String, Object>(); - map.put("number", new Double(1)); - String output = dump(map); - assertEquals("{number: 1.0}\n", output); - } + public void testFloatOut() { + Map<String, Object> map = new HashMap<String, Object>(); + map.put("number", Double.valueOf(1)); + String output = dump(map); + assertEquals("{number: 1.0}\n", output); + } - public void testBasicDoubleScalarLoad() { - assertEquals(new Double(47.0), load("47.0")); - assertEquals(new Double(0.0), load("0.0")); - assertEquals(new Double(-1.0), load("-1.0")); - } + public void testBasicDoubleScalarLoad() { + assertEquals(Double.valueOf(47.0), load("47.0")); + assertEquals(Double.valueOf(0.0), load("0.0")); + assertEquals(Double.valueOf(-1.0), load("-1.0")); + } - public void testDumpStr() { - assertEquals("'1.0'\n", dump("1.0")); - } + public void testDumpStr() { + assertEquals("'1.0'\n", dump("1.0")); + } - public void testDump() { - assertEquals("1.0\n", dump(1.0)); - } + public void testDump() { + assertEquals("1.0\n", dump(1.0)); + } - /** - * to test http://code.google.com/p/snakeyaml/issues/detail?id=130 - */ - public void testScientificFloatWithoutDecimalDot() { - assertEquals(new Double(8e-06), load("8e-06")); - assertEquals(new Double(8e06), load("8e06")); - assertEquals(new Double(8e06), load("8e+06")); - assertEquals(new Double(8000e06), load("8_000e06")); - assertEquals(new Double(123e-06), load("123e-06")); - } + /** + * to test http://code.google.com/p/snakeyaml/issues/detail?id=130 + */ + public void testScientificFloatWithoutDecimalDot() { + assertEquals(Double.valueOf(8e-06), load("8e-06")); + assertEquals(Double.valueOf(8e06), load("8e06")); + assertEquals(Double.valueOf(8e06), load("8e+06")); + assertEquals(Double.valueOf(8000e06), load("8_000e06")); + assertEquals(Double.valueOf(123e-06), load("123e-06")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/IntTagTest.java b/src/test/java/org/yaml/snakeyaml/types/IntTagTest.java index 2adb9c86..aae7881f 100644 --- a/src/test/java/org/yaml/snakeyaml/types/IntTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/IntTagTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; @@ -20,46 +18,46 @@ import java.util.HashMap; import java.util.Map; /** - * @see <a href="http://yaml.org/type/int.html"></a> + * @see <a href="http://yaml.org/type/int.html">int</a> */ public class IntTagTest extends AbstractTest { - public void testInt() { - assertEquals(new Integer(685230), getMapValue("canonical: 685230", "canonical")); - assertEquals(new Integer(685230), getMapValue("number: 685_230", "number")); - assertEquals(new Integer(685230), getMapValue("decimal: +685230", "decimal")); - assertEquals(new Integer(-685230), getMapValue("number: -685230", "number")); - assertEquals(new Integer(685230), getMapValue("octal: 02472256", "octal")); - assertEquals(new Integer(685230), getMapValue("hexadecimal: 0x_0A_74_AE", "hexadecimal")); - assertEquals(new Integer(685230), - getMapValue("binary: 0b1010_0111_0100_1010_1110", "binary")); - assertEquals(new Integer(685230), getMapValue("sexagesimal: 190:20:30", "sexagesimal")); - assertEquals(new Integer(0), load("0")); - assertEquals(new Integer(0), load("-0")); - assertEquals(new Integer(0), load("+0")); - assertEquals(Integer.MIN_VALUE, load(dump(Integer.MIN_VALUE))); - assertEquals(Integer.MAX_VALUE, load(dump(Integer.MAX_VALUE))); - } + public void testInt() { + assertEquals(Integer.valueOf(685230), getMapValue("canonical: 685230", "canonical")); + assertEquals(Integer.valueOf(685230), getMapValue("number: 685_230", "number")); + assertEquals(Integer.valueOf(685230), getMapValue("decimal: +685230", "decimal")); + assertEquals(Integer.valueOf(-685230), getMapValue("number: -685230", "number")); + assertEquals(Integer.valueOf(685230), getMapValue("octal: 02472256", "octal")); + assertEquals(Integer.valueOf(685230), getMapValue("hexadecimal: 0x_0A_74_AE", "hexadecimal")); + assertEquals(Integer.valueOf(685230), + getMapValue("binary: 0b1010_0111_0100_1010_1110", "binary")); + assertEquals(Integer.valueOf(685230), getMapValue("sexagesimal: 190:20:30", "sexagesimal")); + assertEquals(Integer.valueOf(0), load("0")); + assertEquals(Integer.valueOf(0), load("-0")); + assertEquals(Integer.valueOf(0), load("+0")); + assertEquals(Integer.MIN_VALUE, load(dump(Integer.MIN_VALUE))); + assertEquals(Integer.MAX_VALUE, load(dump(Integer.MAX_VALUE))); + } - public void testBigInt() { - assertEquals(new Long(922337203685477580L), load("922337203685477580")); - assertEquals(new BigInteger("9223372036854775809999999999"), - load("9223372036854775809999999999")); - assertEquals(Long.MIN_VALUE, load("-9223372036854775808")); - } + public void testBigInt() { + assertEquals(Long.valueOf(922337203685477580L), load("922337203685477580")); + assertEquals(new BigInteger("9223372036854775809999999999"), + load("9223372036854775809999999999")); + assertEquals(Long.MIN_VALUE, load("-9223372036854775808")); + } - public void testIntShorthand() { - assertEquals(new Integer(1), getMapValue("number: !!int 1", "number")); - } + public void testIntShorthand() { + assertEquals(Integer.valueOf(1), getMapValue("number: !!int 1", "number")); + } - public void testIntTag() { - assertEquals(new Integer(1), getMapValue("number: !<tag:yaml.org,2002:int> 1", "number")); - } + public void testIntTag() { + assertEquals(Integer.valueOf(1), getMapValue("number: !<tag:yaml.org,2002:int> 1", "number")); + } - public void testIntOut() { - Map<String, Integer> map = new HashMap<String, Integer>(); - map.put("number", new Integer(1)); - String output = dump(map); - assertTrue(output.contains("number: 1")); - } + public void testIntOut() { + Map<String, Integer> map = new HashMap<String, Integer>(); + map.put("number", Integer.valueOf(1)); + String output = dump(map); + assertTrue(output.contains("number: 1")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/MapTagTest.java b/src/test/java/org/yaml/snakeyaml/types/MapTagTest.java index b6449a7a..9d496ee9 100644 --- a/src/test/java/org/yaml/snakeyaml/types/MapTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/MapTagTest.java @@ -1,70 +1,67 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.util.Map; - import org.yaml.snakeyaml.YamlDocument; /** - * @see <a href="http://yaml.org/type/map.html"></a> + * @see <a href="http://yaml.org/type/map.html">map</a> */ public class MapTagTest extends AbstractTest { - @SuppressWarnings("unchecked") - public void testMap() { - YamlDocument document = new YamlDocument("types/map.yaml"); - Map<String, Map<String, String>> map = (Map<String, Map<String, String>>) document - .getNativeData(); - assertEquals(2, map.size()); - Map<String, String> map1 = (Map<String, String>) map.get("Block style"); - assertEquals(3, map1.size()); - assertEquals("Evans", map1.get("Clark")); - assertEquals("Ingerson", map1.get("Brian")); - assertEquals("Ben-Kiki", map1.get("Oren")); - // - Map<String, String> map2 = (Map<String, String>) map.get("Flow style"); - assertEquals(3, map2.size()); - assertEquals("Evans", map2.get("Clark")); - assertEquals("Ingerson", map2.get("Brian")); - assertEquals("Ben-Kiki", map2.get("Oren")); - // - assertEquals(map1, map2); - assertNotSame(map1, map2); - } + @SuppressWarnings("unchecked") + public void testMap() { + YamlDocument document = new YamlDocument("types/map.yaml"); + Map<String, Map<String, String>> map = + (Map<String, Map<String, String>>) document.getNativeData(); + assertEquals(2, map.size()); + Map<String, String> map1 = map.get("Block style"); + assertEquals(3, map1.size()); + assertEquals("Evans", map1.get("Clark")); + assertEquals("Ingerson", map1.get("Brian")); + assertEquals("Ben-Kiki", map1.get("Oren")); + // + Map<String, String> map2 = map.get("Flow style"); + assertEquals(3, map2.size()); + assertEquals("Evans", map2.get("Clark")); + assertEquals("Ingerson", map2.get("Brian")); + assertEquals("Ben-Kiki", map2.get("Oren")); + // + assertEquals(map1, map2); + assertNotSame(map1, map2); + } - @SuppressWarnings("unchecked") - public void testMapYaml11() { - YamlDocument document = new YamlDocument("types/map_mixed_tags.yaml"); - Map<String, Map<String, String>> map = (Map<String, Map<String, String>>) document - .getNativeData(); - assertEquals(2, map.size()); - Map<String, String> map1 = (Map<String, String>) map.get("Block style"); - assertEquals(3, map1.size()); - assertEquals("Evans", map1.get("Clark")); - assertEquals("Ingerson", map1.get("Brian")); - assertEquals("Ben-Kiki", map1.get("Oren")); - // - Map<String, String> map2 = (Map<String, String>) map.get("Flow style"); - assertEquals(3, map2.size()); - assertEquals("Evans", map2.get("Clark")); - assertEquals("Ingerson", map2.get("Brian")); - assertEquals("Ben-Kiki", map2.get("Oren")); - // - assertEquals(map1, map2); - } + @SuppressWarnings("unchecked") + public void testMapYaml11() { + YamlDocument document = new YamlDocument("types/map_mixed_tags.yaml"); + Map<String, Map<String, String>> map = + (Map<String, Map<String, String>>) document.getNativeData(); + assertEquals(2, map.size()); + Map<String, String> map1 = map.get("Block style"); + assertEquals(3, map1.size()); + assertEquals("Evans", map1.get("Clark")); + assertEquals("Ingerson", map1.get("Brian")); + assertEquals("Ben-Kiki", map1.get("Oren")); + // + Map<String, String> map2 = map.get("Flow style"); + assertEquals(3, map2.size()); + assertEquals("Evans", map2.get("Clark")); + assertEquals("Ingerson", map2.get("Brian")); + assertEquals("Ben-Kiki", map2.get("Oren")); + // + assertEquals(map1, map2); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/MergeTagTest.java b/src/test/java/org/yaml/snakeyaml/types/MergeTagTest.java index 9af5d47b..0e3aae8c 100644 --- a/src/test/java/org/yaml/snakeyaml/types/MergeTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/MergeTagTest.java @@ -1,70 +1,67 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.YamlDocument; /** - * @see <a href="http://yaml.org/type/merge.html"></a> + * @see <a href="http://yaml.org/type/merge.html">merge</a> */ public class MergeTagTest extends AbstractTest { - @SuppressWarnings("unchecked") - public void testMerge() { - YamlDocument document = new YamlDocument("types/merge.yaml"); - List<Object> list = (List<Object>) document.getNativeData(); - assertEquals(8, list.size()); - Map<Object, Object> center = (Map<Object, Object>) list.get(0); - assertEquals(2, center.size()); - assertEquals(new Integer(1), center.get("x")); - assertEquals(new Integer(2), center.get("y")); - // - Map<Object, Object> left = (Map<Object, Object>) list.get(1); - assertEquals(2, left.size()); - assertEquals(left.get("x").getClass().toString(), new Integer(0), left.get("x")); - assertEquals(new Integer(2), left.get("y")); - // - Map<Object, Object> big = (Map<Object, Object>) list.get(2); - assertEquals(1, big.size()); - assertEquals(new Integer(10), big.get("r")); - // - Map<Object, Object> small = (Map<Object, Object>) list.get(3); - assertEquals(1, small.size()); - assertEquals(new Integer(1), small.get("r")); - // Explicit keys - Map<Object, Object> explicit = (Map<Object, Object>) list.get(4); - assertEquals(4, explicit.size()); - assertEquals(new Integer(1), explicit.get("x")); - assertEquals(new Integer(2), explicit.get("y")); - assertEquals(new Integer(10), explicit.get("r")); - assertEquals("center/big", explicit.get("label")); - // Merge one map - Map<Object, Object> merged1 = (Map<Object, Object>) list.get(5); - assertEquals(explicit, merged1); - assertNotSame(explicit, merged1); - // Merge multiple maps - Map<Object, Object> merged2 = (Map<Object, Object>) list.get(6); - assertEquals(explicit, merged2); - assertNotSame(explicit, merged2); - // Override - Map<Object, Object> merged3 = (Map<Object, Object>) list.get(7); - assertEquals(explicit, merged3); - assertNotSame(explicit, merged3); - } + @SuppressWarnings("unchecked") + public void testMerge() { + YamlDocument document = new YamlDocument("types/merge.yaml"); + List<Object> list = (List<Object>) document.getNativeData(); + assertEquals(8, list.size()); + Map<Object, Object> center = (Map<Object, Object>) list.get(0); + assertEquals(2, center.size()); + assertEquals(Integer.valueOf(1), center.get("x")); + assertEquals(Integer.valueOf(2), center.get("y")); + // + Map<Object, Object> left = (Map<Object, Object>) list.get(1); + assertEquals(2, left.size()); + assertEquals(left.get("x").getClass().toString(), Integer.valueOf(0), left.get("x")); + assertEquals(Integer.valueOf(2), left.get("y")); + // + Map<Object, Object> big = (Map<Object, Object>) list.get(2); + assertEquals(1, big.size()); + assertEquals(Integer.valueOf(10), big.get("r")); + // + Map<Object, Object> small = (Map<Object, Object>) list.get(3); + assertEquals(1, small.size()); + assertEquals(Integer.valueOf(1), small.get("r")); + // Explicit keys + Map<Object, Object> explicit = (Map<Object, Object>) list.get(4); + assertEquals(4, explicit.size()); + assertEquals(Integer.valueOf(1), explicit.get("x")); + assertEquals(Integer.valueOf(2), explicit.get("y")); + assertEquals(Integer.valueOf(10), explicit.get("r")); + assertEquals("center/big", explicit.get("label")); + // Merge one map + Map<Object, Object> merged1 = (Map<Object, Object>) list.get(5); + assertEquals(explicit, merged1); + assertNotSame(explicit, merged1); + // Merge multiple maps + Map<Object, Object> merged2 = (Map<Object, Object>) list.get(6); + assertEquals(explicit, merged2); + assertNotSame(explicit, merged2); + // Override + Map<Object, Object> merged3 = (Map<Object, Object>) list.get(7); + assertEquals(explicit, merged3); + assertNotSame(explicit, merged3); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/NullTagTest.java b/src/test/java/org/yaml/snakeyaml/types/NullTagTest.java index b3cd9665..eb1fca3a 100644 --- a/src/test/java/org/yaml/snakeyaml/types/NullTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/NullTagTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; @@ -19,7 +17,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; @@ -29,124 +26,126 @@ import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; /** - * @see <a href="http://yaml.org/type/null.html"></a> + * @see <a href="http://yaml.org/type/null.html">null</a> */ public class NullTagTest extends AbstractTest { - public void testNull() { - assertNull("Got: '" + load("---\n") + "'", load("---\n")); - assertNull(load("---\n...")); - assertNull(load("---\n...\n")); - assertNull(load("\n")); - assertNull(load("")); - assertNull(load(" ")); - assertNull(load("~")); - assertNull(load("---\n~")); - assertNull(load("null")); - assertNull(load("Null")); - assertNull(load("NULL")); - assertNull(getMapValue("empty:\n", "empty")); - assertNull(getMapValue("canonical: ~", "canonical")); - assertNull(getMapValue("english: null", "english")); - assertNull(getMapValue("english: Null", "english")); - assertNull(getMapValue("english: NULL", "english")); - assertEquals("null key", getMapValue("~: null key\n", null)); - } + public void testNull() { + assertNull("Got: '" + load("---\n") + "'", load("---\n")); + assertNull(load("---\n...")); + assertNull(load("---\n...\n")); + assertNull(load("\n")); + assertNull(load("")); + assertNull(load(" ")); + assertNull(load("~")); + assertNull(load("---\n~")); + assertNull(load("null")); + assertNull(load("Null")); + assertNull(load("NULL")); + assertNull(getMapValue("empty:\n", "empty")); + assertNull(getMapValue("canonical: ~", "canonical")); + assertNull(getMapValue("english: null", "english")); + assertNull(getMapValue("english: Null", "english")); + assertNull(getMapValue("english: NULL", "english")); + assertEquals("null key", getMapValue("~: null key\n", null)); + } - @SuppressWarnings("unchecked") - public void testSequenceNull() { - String input = "---\n# This sequence has five\n# entries, two have values.\nsparse:\n - ~\n - 2nd entry\n -\n - 4th entry\n - Null\n"; - List<String> parsed = (List<String>) getMapValue(input, "sparse"); - assertEquals(5, parsed.size()); - assertNull(parsed.get(0)); - assertEquals("2nd entry", parsed.get(1)); - assertNull("Got: '" + parsed.get(2) + "'", parsed.get(2)); - assertEquals("4th entry", parsed.get(3)); - assertNull(parsed.get(4)); - } + @SuppressWarnings("unchecked") + public void testSequenceNull() { + String input = + "---\n# This sequence has five\n# entries, two have values.\nsparse:\n - ~\n - 2nd entry\n -\n - 4th entry\n - Null\n"; + List<String> parsed = (List<String>) getMapValue(input, "sparse"); + assertEquals(5, parsed.size()); + assertNull(parsed.get(0)); + assertEquals("2nd entry", parsed.get(1)); + assertNull("Got: '" + parsed.get(2) + "'", parsed.get(2)); + assertEquals("4th entry", parsed.get(3)); + assertNull(parsed.get(4)); + } - public void testNullInMap() { - String input = "key1: null\n~: value1"; - Map<String, Object> parsed = getMap(input); - assertEquals(2, parsed.size()); - assertTrue(parsed.containsKey(null)); - Object value1 = parsed.get(null); - assertEquals("value1", value1); - // - assertNull(parsed.get("key1")); - // - assertFalse(getMap("key2: value2").containsKey(null)); - } + public void testNullInMap() { + String input = "key1: null\n~: value1"; + Map<String, Object> parsed = getMap(input); + assertEquals(2, parsed.size()); + assertTrue(parsed.containsKey(null)); + Object value1 = parsed.get(null); + assertEquals("value1", value1); + // + assertNull(parsed.get("key1")); + // + assertFalse(getMap("key2: value2").containsKey(null)); + } - public void testNullShorthand() { - assertNull(getMapValue("nothing: !!null null", "nothing")); - } + public void testNullShorthand() { + assertNull(getMapValue("nothing: !!null null", "nothing")); + } - public void testNullTag() { - assertNull(getMapValue("nothing: !<tag:yaml.org,2002:null> null", "nothing")); - } + public void testNullTag() { + assertNull(getMapValue("nothing: !<tag:yaml.org,2002:null> null", "nothing")); + } - public void testNullOut() { - String output = dump(null); - assertEquals("null\n", output); - } + public void testNullOut() { + String output = dump(null); + assertEquals("null\n", output); + } - public void testNullOutAsEmpty() { - Yaml yaml = new Yaml(new NullRepresenter()); - String output = yaml.dump(null); - assertEquals("", output); - } + public void testNullOutAsEmpty() { + Yaml yaml = new Yaml(new NullRepresenter()); + String output = yaml.dump(null); + assertEquals("", output); + } - /** - * test flow style - */ - public void testNullOutAsEmpty2() { - Yaml yaml = new Yaml(new NullRepresenter()); - Map<String, String> map = new HashMap<String, String>(); - map.put("aaa", "foo"); - map.put("bbb", null); - String output = yaml.dump(map); - assertEquals("{aaa: foo, bbb: !!null ''}\n", output); - } + /** + * test flow style + */ + public void testNullOutAsEmpty2() { + Yaml yaml = new Yaml(new NullRepresenter()); + Map<String, String> map = new HashMap<String, String>(); + map.put("aaa", "foo"); + map.put("bbb", null); + String output = yaml.dump(map); + assertEquals("{aaa: foo, bbb: !!null ''}\n", output); + } - /** - * test block style - */ - public void testBoolOutAsEmpty3() { - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - Yaml yaml = new Yaml(new NullRepresenter(), options); - Map<String, String> map = new HashMap<String, String>(); - map.put("aaa", "foo"); - map.put("bbb", null); - String output = yaml.dump(map); - assertEquals("aaa: foo\nbbb:\n", output); - } + /** + * test block style + */ + public void testBoolOutAsEmpty3() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + Yaml yaml = new Yaml(new NullRepresenter(), options); + Map<String, String> map = new HashMap<String, String>(); + map.put("aaa", "foo"); + map.put("bbb", null); + String output = yaml.dump(map); + assertEquals("aaa: foo\nbbb:\n", output); + } - private class NullRepresenter extends Representer { - public NullRepresenter() { - super(); - // null representer is exceptional and it is stored as an instance - // variable. - this.nullRepresenter = new RepresentNull(); - } - - private class RepresentNull implements Represent { - public Node representData(Object data) { - // possible values are here http://yaml.org/type/null.html - return representScalar(Tag.NULL, ""); - } - } + private class NullRepresenter extends Representer { + + public NullRepresenter() { + super(); + // null representer is exceptional and it is stored as an instance + // variable. + this.nullRepresenter = new RepresentNull(); } - public void testNoAnchors() { - List<String> list = new ArrayList<String>(3); - list.add(null); - list.add("value"); - list.add(null); - Yaml yaml = new Yaml(); - String output = yaml.dump(list); - assertEquals("Null values must not get anchors and aliases.", "[null, value, null]\n", - output); + private class RepresentNull implements Represent { + + public Node representData(Object data) { + // possible values are here http://yaml.org/type/null.html + return representScalar(Tag.NULL, ""); + } } + } + + public void testNoAnchors() { + List<String> list = new ArrayList<String>(3); + list.add(null); + list.add("value"); + list.add(null); + Yaml yaml = new Yaml(); + String output = yaml.dump(list); + assertEquals("Null values must not get anchors and aliases.", "[null, value, null]\n", output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/OmapTagTest.java b/src/test/java/org/yaml/snakeyaml/types/OmapTagTest.java index 2811deaa..da74d9da 100644 --- a/src/test/java/org/yaml/snakeyaml/types/OmapTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/OmapTagTest.java @@ -1,46 +1,43 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.util.Map; - import org.yaml.snakeyaml.YamlDocument; /** - * @see <a href="http://yaml.org/type/omap.html"></a> + * @see <a href="http://yaml.org/type/omap.html">omap</a> */ public class OmapTagTest extends AbstractTest { - @SuppressWarnings("unchecked") - public void testOmap() { - YamlDocument document = new YamlDocument("types/omap.yaml"); - Map<String, Map<String, String>> map = (Map<String, Map<String, String>>) document - .getNativeData(); - assertEquals(2, map.size()); - Map<String, String> map1 = (Map<String, String>) map.get("Bestiary"); - assertEquals(3, map1.size()); - assertEquals("African pig-like ant eater. Ugly.", map1.get("aardvark")); - assertEquals("South-American ant eater. Two species.", map1.get("anteater")); - assertEquals("South-American constrictor snake. Scaly.", map1.get("anaconda")); - // - Map<String, String> map2 = (Map<String, String>) map.get("Numbers"); - assertEquals(3, map2.size()); - assertEquals(new Integer(1), map2.get("one")); - assertEquals(new Integer(2), map2.get("two")); - assertEquals(new Integer(3), map2.get("three")); - } + @SuppressWarnings("unchecked") + public void testOmap() { + YamlDocument document = new YamlDocument("types/omap.yaml"); + Map<String, Map<String, String>> map = + (Map<String, Map<String, String>>) document.getNativeData(); + assertEquals(2, map.size()); + Map<String, String> map1 = map.get("Bestiary"); + assertEquals(3, map1.size()); + assertEquals("African pig-like ant eater. Ugly.", map1.get("aardvark")); + assertEquals("South-American ant eater. Two species.", map1.get("anteater")); + assertEquals("South-American constrictor snake. Scaly.", map1.get("anaconda")); + // + Map<String, String> map2 = map.get("Numbers"); + assertEquals(3, map2.size()); + assertEquals(Integer.valueOf(1), map2.get("one")); + assertEquals(Integer.valueOf(2), map2.get("two")); + assertEquals(Integer.valueOf(3), map2.get("three")); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/PairsTagTest.java b/src/test/java/org/yaml/snakeyaml/types/PairsTagTest.java index 2f3c73e3..321d95a3 100644 --- a/src/test/java/org/yaml/snakeyaml/types/PairsTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/PairsTagTest.java @@ -1,70 +1,67 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.YamlDocument; /** - * @see <a href="http://yaml.org/type/pairs.html"></a> + * @see <a href="http://yaml.org/type/pairs.html">pairs</a> */ public class PairsTagTest extends AbstractTest { - @SuppressWarnings("unchecked") - public void testPairs() { - YamlDocument document = new YamlDocument("types/pairs.yaml", false); - Map<String, List<String[]>> map = (Map<String, List<String[]>>) document.getNativeData(); - assertEquals(2, map.size()); - List<String[]> list1 = (List<String[]>) map.get("Block tasks"); - assertEquals(4, list1.size()); - Object[] tuple1 = list1.get(0); - assertEquals(2, tuple1.length); - assertEquals("meeting", tuple1[0]); - assertEquals("with team.", tuple1[1]); - // + @SuppressWarnings("unchecked") + public void testPairs() { + YamlDocument document = new YamlDocument("types/pairs.yaml", false); + Map<String, List<String[]>> map = (Map<String, List<String[]>>) document.getNativeData(); + assertEquals(2, map.size()); + List<String[]> list1 = map.get("Block tasks"); + assertEquals(4, list1.size()); + Object[] tuple1 = list1.get(0); + assertEquals(2, tuple1.length); + assertEquals("meeting", tuple1[0]); + assertEquals("with team.", tuple1[1]); + // - Object[] tuple2 = list1.get(1); - assertEquals(2, tuple2.length); - assertEquals("meeting", tuple2[0]); - assertEquals("with boss.", tuple2[1]); - // + Object[] tuple2 = list1.get(1); + assertEquals(2, tuple2.length); + assertEquals("meeting", tuple2[0]); + assertEquals("with boss.", tuple2[1]); + // - Object[] tuple3 = list1.get(2); - assertEquals(2, tuple3.length); - assertEquals("break", tuple3[0]); - assertEquals("lunch.", tuple3[1]); - // + Object[] tuple3 = list1.get(2); + assertEquals(2, tuple3.length); + assertEquals("break", tuple3[0]); + assertEquals("lunch.", tuple3[1]); + // - Object[] tuple4 = list1.get(3); - assertEquals(2, tuple4.length); - assertEquals("meeting", tuple4[0]); - assertEquals("with client.", tuple4[1]); - // - List<String[]> list2 = (List<String[]>) map.get("Flow tasks"); - assertEquals(2, list2.size()); - Object[] tuple2_1 = list2.get(0); - assertEquals(2, tuple2_1.length); - assertEquals("meeting", tuple2_1[0]); - assertEquals("with team", tuple2_1[1]); - // - Object[] tuple2_2 = list2.get(1); - assertEquals(2, tuple2_2.length); - assertEquals("meeting", tuple2_2[0]); - assertEquals("with boss", tuple2_2[1]); - } + Object[] tuple4 = list1.get(3); + assertEquals(2, tuple4.length); + assertEquals("meeting", tuple4[0]); + assertEquals("with client.", tuple4[1]); + // + List<String[]> list2 = map.get("Flow tasks"); + assertEquals(2, list2.size()); + Object[] tuple2_1 = list2.get(0); + assertEquals(2, tuple2_1.length); + assertEquals("meeting", tuple2_1[0]); + assertEquals("with team", tuple2_1[1]); + // + Object[] tuple2_2 = list2.get(1); + assertEquals(2, tuple2_2.length); + assertEquals("meeting", tuple2_2[0]); + assertEquals("with boss", tuple2_2[1]); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/SeqTagTest.java b/src/test/java/org/yaml/snakeyaml/types/SeqTagTest.java index 0f4123bc..e2829108 100644 --- a/src/test/java/org/yaml/snakeyaml/types/SeqTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/SeqTagTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; @@ -20,74 +18,73 @@ import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.YamlDocument; /** - * @see <a href="http://yaml.org/type/seq.html"></a> + * @see <a href="http://yaml.org/type/seq.html">seq</a> */ public class SeqTagTest extends AbstractTest { - @SuppressWarnings("unchecked") - public void testSeq() { - YamlDocument document = new YamlDocument("types/seq.yaml"); - Map<String, List<String>> map = (Map<String, List<String>>) document.getNativeData(); - assertEquals(2, map.size()); - List<String> list1 = (List<String>) map.get("Block style"); - assertEquals(9, list1.size()); - assertEquals("Mercury", list1.get(0)); - assertEquals("Venus", list1.get(1)); - assertEquals("Earth", list1.get(2)); - assertEquals("Mars", list1.get(3)); - assertEquals("Jupiter", list1.get(4)); - assertEquals("Saturn", list1.get(5)); - assertEquals("Uranus", list1.get(6)); - assertEquals("Neptune", list1.get(7)); - assertEquals("Pluto", list1.get(8)); - // - List<String> list2 = (List<String>) map.get("Flow style"); - assertEquals(9, list2.size()); - assertEquals("Mercury", list2.get(0)); - assertEquals("Venus", list2.get(1)); - assertEquals("Earth", list2.get(2)); - assertEquals("Mars", list2.get(3)); - assertEquals("Jupiter", list2.get(4)); - assertEquals("Saturn", list2.get(5)); - assertEquals("Uranus", list2.get(6)); - assertEquals("Neptune", list2.get(7)); - assertEquals("Pluto", list2.get(8)); - // - assertEquals(list1, list2); - assertNotSame(list1, list2); - } + @SuppressWarnings("unchecked") + public void testSeq() { + YamlDocument document = new YamlDocument("types/seq.yaml"); + Map<String, List<String>> map = (Map<String, List<String>>) document.getNativeData(); + assertEquals(2, map.size()); + List<String> list1 = map.get("Block style"); + assertEquals(9, list1.size()); + assertEquals("Mercury", list1.get(0)); + assertEquals("Venus", list1.get(1)); + assertEquals("Earth", list1.get(2)); + assertEquals("Mars", list1.get(3)); + assertEquals("Jupiter", list1.get(4)); + assertEquals("Saturn", list1.get(5)); + assertEquals("Uranus", list1.get(6)); + assertEquals("Neptune", list1.get(7)); + assertEquals("Pluto", list1.get(8)); + // + List<String> list2 = map.get("Flow style"); + assertEquals(9, list2.size()); + assertEquals("Mercury", list2.get(0)); + assertEquals("Venus", list2.get(1)); + assertEquals("Earth", list2.get(2)); + assertEquals("Mars", list2.get(3)); + assertEquals("Jupiter", list2.get(4)); + assertEquals("Saturn", list2.get(5)); + assertEquals("Uranus", list2.get(6)); + assertEquals("Neptune", list2.get(7)); + assertEquals("Pluto", list2.get(8)); + // + assertEquals(list1, list2); + assertNotSame(list1, list2); + } - @SuppressWarnings("unchecked") - public void testCollection() { - Collection<Integer> collection = new LinkedList<Integer>(); - collection.add(1); - collection.add(2); - collection.add(3); - String output = dump(collection); - assertEquals("[1, 2, 3]\n", output); - Collection<Integer> obj = (Collection<Integer>) load(output); - // System.out.println(obj); - assertEquals(3, obj.size()); - assertTrue("Create ArrayList by default: " + obj.getClass().toString(), - obj instanceof ArrayList); - } + @SuppressWarnings("unchecked") + public void testCollection() { + Collection<Integer> collection = new LinkedList<Integer>(); + collection.add(1); + collection.add(2); + collection.add(3); + String output = dump(collection); + assertEquals("[1, 2, 3]\n", output); + Collection<Integer> obj = (Collection<Integer>) load(output); + // System.out.println(obj); + assertEquals(3, obj.size()); + assertTrue("Create ArrayList by default: " + obj.getClass().toString(), + obj instanceof ArrayList); + } - public void testArray() { - Integer[] array = new Integer[3]; - array[0] = new Integer(1); - array[1] = new Integer(1); - array[2] = new Integer(2); - String output = dump(array); - assertEquals("[1, 1, 2]\n", output); - } + public void testArray() { + Integer[] array = new Integer[3]; + array[0] = Integer.valueOf(1); + array[1] = Integer.valueOf(1); + array[2] = Integer.valueOf(2); + String output = dump(array); + assertEquals("[1, 1, 2]\n", output); + } - public void testStringArray() { - String[] array = new String[] { "aaa", "bbb", "ccc" }; - String output = dump(array); - assertEquals("[aaa, bbb, ccc]\n", output); - } + public void testStringArray() { + String[] array = new String[] {"aaa", "bbb", "ccc"}; + String output = dump(array); + assertEquals("[aaa, bbb, ccc]\n", output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/SetTagTest.java b/src/test/java/org/yaml/snakeyaml/types/SetTagTest.java index add9b59b..50547355 100644 --- a/src/test/java/org/yaml/snakeyaml/types/SetTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/SetTagTest.java @@ -1,45 +1,52 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; import java.util.Map; import java.util.Set; - +import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.YamlDocument; /** - * @see <a href="http://yaml.org/type/set.html"></a> + * @see <a href="http://yaml.org/type/set.html">set</a> */ public class SetTagTest extends AbstractTest { - @SuppressWarnings("unchecked") - public void testSet() { - YamlDocument document = new YamlDocument("types/set.yaml"); - Map<String, Set<String>> map = (Map<String, Set<String>>) document.getNativeData(); - assertEquals(2, map.size()); - Set<String> set1 = (Set<String>) map.get("baseball players"); - assertEquals(3, set1.size()); - assertTrue(set1.contains("Mark McGwire")); - assertTrue(set1.contains("Sammy Sosa")); - assertTrue(set1.contains("Ken Griffey")); - // - Set<String> set2 = (Set<String>) map.get("baseball teams"); - assertEquals(3, set2.size()); - assertTrue(set2.contains("Boston Red Sox")); - assertTrue(set2.contains("Detroit Tigers")); - assertTrue(set2.contains("New York Yankees")); - } + @SuppressWarnings("unchecked") + public void testSet() { + YamlDocument document = new YamlDocument("types/set.yaml"); + Map<String, Set<String>> map = (Map<String, Set<String>>) document.getNativeData(); + assertEquals(2, map.size()); + Set<String> set1 = map.get("baseball players"); + assertEquals(3, set1.size()); + assertTrue(set1.contains("Mark McGwire")); + assertTrue(set1.contains("Sammy Sosa")); + assertTrue(set1.contains("Ken Griffey")); + // + Set<String> set2 = map.get("baseball teams"); + assertEquals(3, set2.size()); + assertTrue(set2.contains("Boston Red Sox")); + assertTrue(set2.contains("Detroit Tigers")); + assertTrue(set2.contains("New York Yankees")); + } + + public void testSetNull() { + Yaml yaml = new Yaml(); + Set<Object> set = yaml.load("!!set {1, 2, null}"); + assertTrue(set.contains(1)); + assertTrue(set.contains(2)); + assertTrue(set.contains(null)); + assertEquals(set.size(), 3); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/StrTagTest.java b/src/test/java/org/yaml/snakeyaml/types/StrTagTest.java index 600bd5ba..c9f1f83c 100644 --- a/src/test/java/org/yaml/snakeyaml/types/StrTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/StrTagTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; @@ -20,154 +18,157 @@ import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.ScalarStyle; import org.yaml.snakeyaml.Yaml; /** - * @see <a href="http://yaml.org/type/str.html"></a> + * @see <a href="http://yaml.org/type/str.html">str</a> */ public class StrTagTest extends AbstractTest { - private String getData(String data, String key) { - return (String) getMapValue(data, key); - } - - public void testString() { - assertEquals("abcd", getData("string: abcd", "string")); - } - - public void testStringShorthand() { - assertEquals("abcd", getData("string: !!str abcd", "string")); - } - - public void testStringTag() { - assertEquals("abcd", getData("string: !<tag:yaml.org,2002:str> abcd", "string")); - } - - public void testUnicode() { - // escaped 8-bit unicode character (u-umlaut): - assertEquals("\u00fc", load("\"\\xfc\"")); - assertEquals("\\xfc", load("\\xfc")); - - // 2 escaped 8-bit unicode characters (u-umlaut following by e-grave): - assertEquals("\u00fc\u00e8", load("\"\\xfc\\xe8\"")); - - // escaped 16-bit unicode character (em dash): - assertEquals("\u2014", load("\"\\u2014\"")); - - // UTF-32 encoding is explicitly not supported - assertEquals("\\U2014AAAA", load("'\\U2014AAAA'")); - - // (and I don't have a surrogate pair handy at the moment) - // raw unicode characters in the stream (em dash) - assertEquals("\u2014", load("\u2014")); - } - - /** - * @see <a href="http://code.google.com/p/jvyamlb/issues/detail?id=6"></a> - */ - @SuppressWarnings("unchecked") - public void testIssueId6() { - Map<String, String> map = (Map<String, String>) load("---\ntest: |-\n \"Test\r\r (* error here)\""); - assertEquals("\"Test\n\n(* error here)\"", map.get("test")); - } - - public void testStrDump() { - assertEquals("abc\n", dump("abc")); - } - - public void testUnicodeDump() { - assertEquals("\\u263a\n", dump("\\u263a")); - assertEquals("The leading zero must be preserved.", "\\u063a\n", dump("\\u063a")); - } - - public void testStringIntOut() { - Map<String, String> map = new HashMap<String, String>(); - map.put("number", "1"); - String output = dump(map); - assertTrue(output, output.contains("number: '1'")); - } - - public void testStringFloatOut() { - Map<String, String> map = new HashMap<String, String>(); - map.put("number", "1.1"); - String output = dump(map); - assertTrue(output, output.contains("number: '1.1'")); - } - - public void testStringBoolOut() { - Map<String, String> map = new HashMap<String, String>(); - map.put("number", "True"); - String output = dump(map); - assertTrue(output, output.contains("number: 'True'")); - } - - public void testEmitLongString() { - String str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - String output = dump(str); - assertEquals(str + "\n", output); - } - - public void testEmitLongStringWithCR() { - String str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n"; - String output = dump(str); - assertEquals("|+\n " + str, output); - } - - public void testEmitDoubleQuoted() { - String str = "\"xx\""; - String output = dump(str); - assertEquals("'" + str + "'\n", output); - } - - /** - * http://pyyaml.org/ticket/196 - */ - public void testEmitQuoted() { - List<String> list = new ArrayList<String>(3); - list.add("This is an 'example'."); - list.add("This is an \"example\"."); - list.add("123"); - String output = dump(list); - assertEquals("[This is an 'example'., This is an \"example\"., '123']\n", output); - // single quoted - DumperOptions options = new DumperOptions(); - options.setDefaultScalarStyle(ScalarStyle.SINGLE_QUOTED); - Yaml yaml = new Yaml(options); - String output2 = yaml.dump(list); - // System.out.println(output2); - assertEquals("- 'This is an ''example''.'\n- 'This is an \"example\".'\n- '123'\n", output2); - // double quoted - DumperOptions options2 = new DumperOptions(); - options2.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); - yaml = new Yaml(options2); - String output3 = yaml.dump(list); - // System.out.println(output2); - assertEquals("- \"This is an 'example'.\"\n- \"This is an \\\"example\\\".\"\n- \"123\"\n", - output3); - } - - public void testEmitEndOfLine() { - String str = "xxxxxxx\n"; - String output = dump(str); - assertEquals("|\n " + str, output); - } - - public void testDumpUtf16() throws UnsupportedEncodingException { - String str = "xxx"; - assertEquals(3, str.toString().length()); - Yaml yaml = new Yaml(); - Charset charset = Charset.forName("UTF-16"); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - Writer writer = new OutputStreamWriter(stream, charset); - yaml.dump(str, writer); - assertEquals(str + "\n", stream.toString("UTF-16")); - assertEquals("Must include BOM: " + stream.toString(), (1 + 3 + 1) * 2, stream.toString() - .length()); - } + + private String getData(String data, String key) { + return (String) getMapValue(data, key); + } + + public void testString() { + assertEquals("abcd", getData("string: abcd", "string")); + } + + public void testStringShorthand() { + assertEquals("abcd", getData("string: !!str abcd", "string")); + } + + public void testStringTag() { + assertEquals("abcd", getData("string: !<tag:yaml.org,2002:str> abcd", "string")); + } + + public void testUnicode() { + // escaped 8-bit unicode character (u-umlaut): + assertEquals("\u00fc", load("\"\\xfc\"")); + assertEquals("\\xfc", load("\\xfc")); + + // 2 escaped 8-bit unicode characters (u-umlaut following by e-grave): + assertEquals("\u00fc\u00e8", load("\"\\xfc\\xe8\"")); + + // escaped 16-bit unicode character (em dash): + assertEquals("\u2014", load("\"\\u2014\"")); + + // UTF-32 encoding is explicitly not supported + assertEquals("\\U2014AAAA", load("'\\U2014AAAA'")); + + // (and I don't have a surrogate pair handy at the moment) + // raw unicode characters in the stream (em dash) + assertEquals("\u2014", load("\u2014")); + } + + /** + * @see <a href="http://code.google.com/p/jvyamlb/issues/detail?id=6">issue 6</a> + */ + @SuppressWarnings("unchecked") + public void testIssueId6() { + Map<String, String> map = + (Map<String, String>) load("---\ntest: |-\n \"Test\r\r (* error here)\""); + assertEquals("\"Test\n\n(* error here)\"", map.get("test")); + } + + public void testStrDump() { + assertEquals("abc\n", dump("abc")); + } + + public void testUnicodeDump() { + assertEquals("\\u263a\n", dump("\\u263a")); + assertEquals("The leading zero must be preserved.", "\\u063a\n", dump("\\u063a")); + } + + public void testStringIntOut() { + Map<String, String> map = new HashMap<String, String>(); + map.put("number", "1"); + String output = dump(map); + assertTrue(output, output.contains("number: '1'")); + } + + public void testStringFloatOut() { + Map<String, String> map = new HashMap<String, String>(); + map.put("number", "1.1"); + String output = dump(map); + assertTrue(output, output.contains("number: '1.1'")); + } + + public void testStringBoolOut() { + Map<String, String> map = new HashMap<String, String>(); + map.put("number", "True"); + String output = dump(map); + assertTrue(output, output.contains("number: 'True'")); + } + + public void testEmitLongString() { + String str = + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; + String output = dump(str); + assertEquals(str + "\n", output); + } + + public void testEmitLongStringWithCR() { + String str = + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n"; + String output = dump(str); + assertEquals("|+\n " + str, output); + } + + public void testEmitDoubleQuoted() { + String str = "\"xx\""; + String output = dump(str); + assertEquals("'" + str + "'\n", output); + } + + /** + * http://pyyaml.org/ticket/196 + */ + public void testEmitQuoted() { + List<String> list = new ArrayList<String>(3); + list.add("This is an 'example'."); + list.add("This is an \"example\"."); + list.add("123"); + String output = dump(list); + assertEquals("[This is an 'example'., This is an \"example\"., '123']\n", output); + // single quoted + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.SINGLE_QUOTED); + Yaml yaml = new Yaml(options); + String output2 = yaml.dump(list); + // System.out.println(output2); + assertEquals("- 'This is an ''example''.'\n- 'This is an \"example\".'\n- '123'\n", output2); + // double quoted + DumperOptions options2 = new DumperOptions(); + options2.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED); + yaml = new Yaml(options2); + String output3 = yaml.dump(list); + // System.out.println(output2); + assertEquals("- \"This is an 'example'.\"\n- \"This is an \\\"example\\\".\"\n- \"123\"\n", + output3); + } + + public void testEmitEndOfLine() { + String str = "xxxxxxx\n"; + String output = dump(str); + assertEquals("|\n " + str, output); + } + + public void testDumpUtf16() throws UnsupportedEncodingException { + String str = "xxx"; + assertEquals(3, str.length()); + Yaml yaml = new Yaml(); + Charset charset = StandardCharsets.UTF_16; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Writer writer = new OutputStreamWriter(stream, charset); + yaml.dump(str, writer); + assertEquals(str + "\n", stream.toString("UTF-16")); + assertEquals("Must include BOM: " + stream, (1 + 3 + 1) * 2, stream.toString().length()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/TimestampTagTest.java b/src/test/java/org/yaml/snakeyaml/types/TimestampTagTest.java index 5e889d16..5d8d4adf 100644 --- a/src/test/java/org/yaml/snakeyaml/types/TimestampTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/TimestampTagTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; @@ -22,102 +20,149 @@ import java.util.Map; import java.util.TimeZone; /** - * @see <a href="http://yaml.org/type/timestamp.html"></a> + * @see <a href="http://yaml.org/type/timestamp.html">timestamp</a> */ public class TimestampTagTest extends AbstractTest { - public void testTimestamp() { - assertEquals("2001-12-15 at 2:59:43 (100)", - getText("canonical: 2001-12-15T02:59:43.1Z", "canonical")); - // zero miliseconds - assertEquals("2001-12-15 at 2:59:43 (0)", - getText("canonical: 2001-12-15T02:59:43.000Z", "canonical")); - assertEquals("2001-12-15 at 2:59:43 (100)", - getText("valid iso8601: 2001-12-14t21:59:43.10-05:00", "valid iso8601")); - // half hour time zone - assertEquals("2001-12-14 at 22:29:43 (100)", - getText("valid iso8601: 2001-12-14t21:59:43.10-0:30", "valid iso8601")); - // + time zone - assertEquals("2001-12-14 at 19:59:43 (100)", - getText("valid iso8601: 2001-12-14t21:59:43.10+2:00", "valid iso8601")); - assertEquals("2001-12-15 at 2:59:43 (100)", - getText("space separated: 2001-12-14 21:59:43.10 -5", "space separated")); - assertEquals("2001-12-15 at 2:59:43 (100)", - getText("no time zone (Z): 2001-12-15 2:59:43.10", "no time zone (Z)")); - assertEquals("2002-12-14 at 0:0:0 (0)", - getText("date (00:00:00Z): 2002-12-14", "date (00:00:00Z)")); - assertEquals("2010-5-16 at 3:6:11 (3)", - getText("milliseconds: 2010-05-16 03:06:11.003", "milliseconds")); - assertEquals("2010-5-16 at 3:6:11 (7)", - getText("milliseconds: 2010-05-16 03:06:11.0068", "milliseconds")); - assertEquals("2010-5-16 at 3:6:11 (0)", - getText("milliseconds: 2010-05-16 03:06:11.0000", "milliseconds")); - assertEquals("2010-5-16 at 3:6:11 (0)", - getText("milliseconds: 2010-05-16 03:06:11.0004", "milliseconds")); - assertEquals("2010-5-16 at 3:6:11 (25)", - getText("milliseconds: 2010-05-16 03:06:11.0250", "milliseconds")); - } + public void testTimestamp() { + assertEquals("2001-12-15 at 2:59:43 (100)", + getText("canonical: 2001-12-15T02:59:43.1Z", "canonical")); + // zero miliseconds + assertEquals("2001-12-15 at 2:59:43 (0)", + getText("canonical: 2001-12-15T02:59:43.000Z", "canonical")); + assertEquals("2001-12-15 at 2:59:43 (100)", + getText("valid iso8601: 2001-12-14t21:59:43.10-05:00", "valid iso8601")); + // half hour time zone + assertEquals("2001-12-14 at 22:29:43 (100)", + getText("valid iso8601: 2001-12-14t21:59:43.10-0:30", "valid iso8601")); + // + time zone + assertEquals("2001-12-14 at 19:59:43 (100)", + getText("valid iso8601: 2001-12-14t21:59:43.10+2:00", "valid iso8601")); + assertEquals("2001-12-15 at 2:59:43 (100)", + getText("space separated: 2001-12-14 21:59:43.10 -5", "space separated")); + assertEquals("2001-12-15 at 2:59:43 (100)", + getText("no time zone (Z): 2001-12-15 2:59:43.10", "no time zone (Z)")); + assertEquals("2002-12-14 at 0:0:0 (0)", + getText("date (00:00:00Z): 2002-12-14", "date (00:00:00Z)")); + assertEquals("2010-5-16 at 3:6:11 (3)", + getText("milliseconds: 2010-05-16 03:06:11.003", "milliseconds")); + assertEquals("2010-5-16 at 3:6:11 (7)", + getText("milliseconds: 2010-05-16 03:06:11.0068", "milliseconds")); + assertEquals("2010-5-16 at 3:6:11 (0)", + getText("milliseconds: 2010-05-16 03:06:11.0000", "milliseconds")); + assertEquals("2010-5-16 at 3:6:11 (0)", + getText("milliseconds: 2010-05-16 03:06:11.0004", "milliseconds")); + assertEquals("2010-5-16 at 3:6:11 (25)", + getText("milliseconds: 2010-05-16 03:06:11.0250", "milliseconds")); + } - public void testTimestampShorthand() { - assertTrue(getMapValue("canonical: !!timestamp 2001-12-15T02:59:43.1Z", "canonical") instanceof Date); - } + public void testTimestampShorthand() { + assertTrue( + getMapValue("canonical: !!timestamp 2001-12-15T02:59:43.1Z", "canonical") instanceof Date); + } - public void testTimestampTag() { - assertTrue(getMapValue("canonical: !<tag:yaml.org,2002:timestamp> 2001-12-15T02:59:43.1Z", - "canonical") instanceof Date); - } + public void testTimestampTag() { + assertTrue(getMapValue("canonical: !<tag:yaml.org,2002:timestamp> 2001-12-15T02:59:43.1Z", + "canonical") instanceof Date); + } - public void testTimestampOut() { - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow")); - cal.clear(); - cal.set(2008, 8, 23, 14, 35, 4); - Date date = cal.getTime(); - String output = dump(date); - assertEquals("2008-09-23T10:35:04Z\n", output); - } + public void testTimestampOut() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow")); + cal.clear(); + cal.set(2008, 8, 23, 14, 35, 4); + Date date = cal.getTime(); + String output = dump(date); + assertEquals("2008-09-23T10:35:04Z\n", output); + } - public void testTimestampOutMap() { - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow")); - cal.clear(); - cal.set(2008, 8, 23, 14, 35, 4); - Date date = cal.getTime(); - Map<String, Date> map = new HashMap<String, Date>(); - map.put("canonical", date); - String output = dump(map); - assertEquals("{canonical: !!timestamp '2008-09-23T10:35:04Z'}\n", output); - } + public void testTimestampOutMap() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow")); + cal.clear(); + cal.set(2008, 8, 23, 14, 35, 4); + Date date = cal.getTime(); + Map<String, Date> map = new HashMap<String, Date>(); + map.put("canonical", date); + String output = dump(map); + assertEquals("{canonical: !!timestamp '2008-09-23T10:35:04Z'}\n", output); + } - private String getText(String yaml, String key) { - Date date = (Date) getMapValue(yaml, key); - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - cal.setTime(date); - int years = cal.get(Calendar.YEAR); - int months = cal.get(Calendar.MONTH) + 1; // 0..12 - int days = cal.get(Calendar.DAY_OF_MONTH); // 1..31 - int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..24 - int minutes = cal.get(Calendar.MINUTE); // 0..59 - int seconds = cal.get(Calendar.SECOND); // 0..59 - int millis = cal.get(Calendar.MILLISECOND); - String result = String.valueOf(years) + "-" + String.valueOf(months) + "-" - + String.valueOf(days) + " at " + String.valueOf(hour24) + ":" - + String.valueOf(minutes) + ":" + String.valueOf(seconds) + " (" - + String.valueOf(millis) + ")"; - return result; - } + public void testTimestampNegativeTimezoneOffset() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-01:15")); + cal.clear(); + cal.set(2008, 8, 23, 14, 35, 4); + Map<String, Calendar> map = new HashMap<String, Calendar>(); + map.put("canonical", cal); + String output = dump(map); + assertEquals("{canonical: !!timestamp '2008-09-23T14:35:04-01:15'}\n", output); + } - public void testTimestampReadWrite() { - Date date = (Date) getMapValue("Time: 2001-11-23 15:01:42 -5", "Time"); - Map<String, Date> map = new HashMap<String, Date>(); - map.put("canonical", date); - String output = dump(map); - assertEquals("{canonical: !!timestamp '2001-11-23T20:01:42Z'}\n", output); - } + public void testTimestampDoubleDigitsForOffset() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+00:30")); + cal.clear(); + cal.set(2008, 8, 23, 14, 35, 4); + Map<String, Calendar> map = new HashMap<String, Calendar>(); + map.put("canonical", cal); + String output = dump(map); + assertEquals("{canonical: !!timestamp '2008-09-23T14:35:04+00:30'}\n", output); + } - public void testSqlDate() { - java.sql.Date date = new java.sql.Date(1000000000000L); - Map<String, java.sql.Date> map = new HashMap<String, java.sql.Date>(); - map.put("canonical", date); - String output = dump(map); - assertEquals("{canonical: !!timestamp '2001-09-09T01:46:40Z'}\n", output); - } + public void testTimestampGMTNoOffset() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+00:00")); + cal.clear(); + cal.set(2008, 8, 23, 14, 35, 4); + Map<String, Calendar> map = new HashMap<String, Calendar>(); + map.put("canonical", cal); + String output = dump(map); + assertEquals("{canonical: !!timestamp '2008-09-23T14:35:04Z'}\n", output); + } + + public void testTimestampEpoch() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + cal.setTimeInMillis(0); + Map<String, Calendar> map = new HashMap<String, Calendar>(); + map.put("canonical", cal); + String output = dump(map); + assertEquals("{canonical: !!timestamp '1970-01-01T00:00:00Z'}\n", output); + } + + public void testTimestampEpochWithOffset() { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-01:00")); + cal.setTimeInMillis(0); + Map<String, Calendar> map = new HashMap<String, Calendar>(); + map.put("canonical", cal); + String output = dump(map); + assertEquals("{canonical: !!timestamp '1969-12-31T23:00:00-01:00'}\n", output); + } + + private String getText(String yaml, String key) { + Date date = (Date) getMapValue(yaml, key); + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + cal.setTime(date); + int years = cal.get(Calendar.YEAR); + int months = cal.get(Calendar.MONTH) + 1; // 0..12 + int days = cal.get(Calendar.DAY_OF_MONTH); // 1..31 + int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..24 + int minutes = cal.get(Calendar.MINUTE); // 0..59 + int seconds = cal.get(Calendar.SECOND); // 0..59 + int millis = cal.get(Calendar.MILLISECOND); + String result = years + "-" + months + "-" + days + " at " + hour24 + ":" + minutes + ":" + + seconds + " (" + millis + ")"; + return result; + } + + public void testTimestampReadWrite() { + Date date = (Date) getMapValue("Time: 2001-11-23 15:01:42 -5", "Time"); + Map<String, Date> map = new HashMap<String, Date>(); + map.put("canonical", date); + String output = dump(map); + assertEquals("{canonical: !!timestamp '2001-11-23T20:01:42Z'}\n", output); + } + + public void testSqlDate() { + java.sql.Date date = new java.sql.Date(1000000000000L); + Map<String, java.sql.Date> map = new HashMap<String, java.sql.Date>(); + map.put("canonical", date); + String output = dump(map); + assertEquals("{canonical: !!timestamp '2001-09-09T01:46:40Z'}\n", output); + } } diff --git a/src/test/java/org/yaml/snakeyaml/types/ValueTagTest.java b/src/test/java/org/yaml/snakeyaml/types/ValueTagTest.java index 7490b1db..46ada0dc 100644 --- a/src/test/java/org/yaml/snakeyaml/types/ValueTagTest.java +++ b/src/test/java/org/yaml/snakeyaml/types/ValueTagTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.types; @@ -19,42 +17,40 @@ import java.io.InputStream; import java.util.Iterator; import java.util.List; import java.util.Map; - import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.YamlDocument; /** - * @see <a href="http://yaml.org/type/value.html"></a> + * @see <a href="http://yaml.org/type/value.html">value</a> */ public class ValueTagTest extends AbstractTest { - /** - * The 'value' tag does not work as defined in the specification but exactly - * as in PyYAML - */ - @SuppressWarnings("unchecked") - public void testValue() { - InputStream input = YamlDocument.class.getClassLoader().getResourceAsStream( - YamlDocument.ROOT + "types/value.yaml"); - Yaml yaml = new Yaml(); - Iterator<Object> iter = (Iterator<Object>) yaml.loadAll(input).iterator(); - Map<String, List<String>> oldSchema = (Map<String, List<String>>) iter.next(); - assertEquals(1, oldSchema.size()); - List<String> list = oldSchema.get("link with"); - assertEquals(2, list.size()); - assertEquals("library1.dll", list.get(0)); - assertEquals("library2.dll", list.get(1)); - // - Map<String, List<Map<String, String>>> newSchema = (Map<String, List<Map<String, String>>>) iter - .next(); - assertEquals(1, newSchema.size()); - // - List<Map<String, String>> list2 = newSchema.get("link with"); - assertEquals(2, list2.size()); - Map<String, String> map1 = list2.get(0); - assertEquals(2, map1.size()); - assertEquals("library1.dll", map1.get("=")); - assertEquals(new Double(1.2), map1.get("version")); - assertFalse(iter.hasNext()); - } + /** + * The 'value' tag does not work as defined in the specification but exactly as in PyYAML + */ + @SuppressWarnings("unchecked") + public void testValue() { + InputStream input = YamlDocument.class.getClassLoader() + .getResourceAsStream(YamlDocument.ROOT + "types/value.yaml"); + Yaml yaml = new Yaml(); + Iterator<Object> iter = yaml.loadAll(input).iterator(); + Map<String, List<String>> oldSchema = (Map<String, List<String>>) iter.next(); + assertEquals(1, oldSchema.size()); + List<String> list = oldSchema.get("link with"); + assertEquals(2, list.size()); + assertEquals("library1.dll", list.get(0)); + assertEquals("library2.dll", list.get(1)); + // + Map<String, List<Map<String, String>>> newSchema = + (Map<String, List<Map<String, String>>>) iter.next(); + assertEquals(1, newSchema.size()); + // + List<Map<String, String>> list2 = newSchema.get("link with"); + assertEquals(2, list2.size()); + Map<String, String> map1 = list2.get(0); + assertEquals(2, map1.size()); + assertEquals("library1.dll", map1.get("=")); + assertEquals(Double.valueOf(1.2), map1.get("version")); + assertFalse(iter.hasNext()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/util/ArrayStackTest.java b/src/test/java/org/yaml/snakeyaml/util/ArrayStackTest.java index dd1cebed..a524bb28 100644 --- a/src/test/java/org/yaml/snakeyaml/util/ArrayStackTest.java +++ b/src/test/java/org/yaml/snakeyaml/util/ArrayStackTest.java @@ -1,17 +1,15 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.util; @@ -19,13 +17,13 @@ import junit.framework.TestCase; public class ArrayStackTest extends TestCase { - public void testClear() { - ArrayStack<Integer> stack = new ArrayStack<Integer>(25); - assertTrue(stack.isEmpty()); - stack.push(new Integer(1)); - stack.push(new Integer(2)); - assertFalse(stack.isEmpty()); - stack.clear(); - assertTrue(stack.isEmpty()); - } + public void testClear() { + ArrayStack<Integer> stack = new ArrayStack<Integer>(25); + assertTrue(stack.isEmpty()); + stack.push(Integer.valueOf(1)); + stack.push(Integer.valueOf(2)); + assertFalse(stack.isEmpty()); + stack.clear(); + assertTrue(stack.isEmpty()); + } } diff --git a/src/test/java/org/yaml/snakeyaml/util/ArrayUtilsTest.java b/src/test/java/org/yaml/snakeyaml/util/ArrayUtilsTest.java new file mode 100644 index 00000000..f65d21a1 --- /dev/null +++ b/src/test/java/org/yaml/snakeyaml/util/ArrayUtilsTest.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.util; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + + +public class ArrayUtilsTest { + + @Test + public void testToUnmodifiableCompositeList() { + List<Integer> compositeList = + ArrayUtils.toUnmodifiableCompositeList(new Integer[] {0, 1, 2}, new Integer[] {3, 4, 5}); + Assert.assertEquals(Arrays.asList(0, 1, 2, 3, 4, 5), compositeList); + try { + compositeList.get(6); + Assert.fail("An IndexOutOfBoundsException was expected"); + } catch (IndexOutOfBoundsException e) { + Assert.assertEquals(e.getMessage(), "Index: 6, Size: 6"); + } + } + + @Test + public void testToUnmodifiableCompositeEmpty() { + List<Integer> compositeList = + ArrayUtils.toUnmodifiableCompositeList(new Integer[0], new Integer[0]); + Assert.assertEquals(Collections.emptyList(), compositeList); + } + + @Test + public void testToUnmodifiableCompositeLeftEmpty() { + List<Integer> compositeList = + ArrayUtils.toUnmodifiableCompositeList(new Integer[0], new Integer[] {3, 4, 5}); + Assert.assertEquals(Arrays.asList(3, 4, 5), compositeList); + } + + @Test + public void testToUnmodifiableCompositeRightEmpty() { + List<Integer> compositeList = + ArrayUtils.toUnmodifiableCompositeList(new Integer[] {1, 2, 3}, new Integer[0]); + Assert.assertEquals(Arrays.asList(1, 2, 3), compositeList); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void testToUnmodifiableCompositeException() { + try { + ArrayUtils.toUnmodifiableCompositeList(new Integer[] {1}, new Integer[] {2}).get(2); + } catch (ArrayIndexOutOfBoundsException e) { + Assert.fail("ArrayIndexOutOfBoundsException wasn't expected, but it was thrown"); + } + + } + +} diff --git a/src/test/java/org/yaml/snakeyaml/util/UriEncoderTest.java b/src/test/java/org/yaml/snakeyaml/util/UriEncoderTest.java index babf61b9..a7d0ba12 100644 --- a/src/test/java/org/yaml/snakeyaml/util/UriEncoderTest.java +++ b/src/test/java/org/yaml/snakeyaml/util/UriEncoderTest.java @@ -1,51 +1,48 @@ /** - * Copyright (c) 2008, http://www.snakeyaml.org + * Copyright (c) 2008, SnakeYAML * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package org.yaml.snakeyaml.util; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; - import junit.framework.TestCase; public class UriEncoderTest extends TestCase { - public void testEncode() { - assertEquals("Acad%C3%A9mico", UriEncoder.encode("Acadรฉmico")); - assertEquals("Check http://yaml.org/spec/1.1/#escaping%20in%20URI/", "[]", - UriEncoder.encode("[]")); - } + public void testEncode() { + assertEquals("Acad%C3%A9mico", UriEncoder.encode("Acadรฉmico")); + assertEquals("Check http://yaml.org/spec/1.1/#escaping%20in%20URI/", "[]", + UriEncoder.encode("[]")); + } - public void testDecode() throws CharacterCodingException { - ByteBuffer buff = ByteBuffer.allocate(10); - buff.put((byte) 0x34); - buff.put((byte) 0x35); - buff.flip(); - assertEquals("45", UriEncoder.decode(buff)); - } + public void testDecode() throws CharacterCodingException { + ByteBuffer buff = ByteBuffer.allocate(10); + buff.put((byte) 0x34); + buff.put((byte) 0x35); + buff.flip(); + assertEquals("45", UriEncoder.decode(buff)); + } - public void testFailDecode() throws CharacterCodingException { - ByteBuffer buff = ByteBuffer.allocate(10); - buff.put((byte) 0x34); - buff.put((byte) 0xC1); - buff.flip(); - try { - UriEncoder.decode(buff); - fail("Invalid UTF-8 must not be accepted."); - } catch (Exception e) { - assertEquals("Input length = 1", e.getMessage()); - } + public void testFailDecode() throws CharacterCodingException { + ByteBuffer buff = ByteBuffer.allocate(10); + buff.put((byte) 0x34); + buff.put((byte) 0xC1); + buff.flip(); + try { + UriEncoder.decode(buff); + fail("Invalid UTF-8 must not be accepted."); + } catch (Exception e) { + assertEquals("Input length = 1", e.getMessage()); } + } } diff --git a/src/test/java11/org/yaml/snakeyaml/issues/issue310/DeepThrowableCauseMatcher.java b/src/test/java11/org/yaml/snakeyaml/issues/issue310/DeepThrowableCauseMatcher.java new file mode 100644 index 00000000..c261e884 --- /dev/null +++ b/src/test/java11/org/yaml/snakeyaml/issues/issue310/DeepThrowableCauseMatcher.java @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue310; + +import org.hamcrest.Matcher; +import org.junit.internal.matchers.ThrowableCauseMatcher; + +public class DeepThrowableCauseMatcher extends ThrowableCauseMatcher<Throwable> { + + public DeepThrowableCauseMatcher(Matcher<? extends Throwable> causeMatcher) { + super(causeMatcher); + } + + @Override + protected boolean matchesSafely(Throwable item) { + for (Throwable cause = item; cause != null; cause = cause.getCause()) { + if (super.matchesSafely(cause)) { + return true; + } + } + return false; + } +} diff --git a/src/test/java11/org/yaml/snakeyaml/issues/issue310/Java11OptionalTest.java b/src/test/java11/org/yaml/snakeyaml/issues/issue310/Java11OptionalTest.java new file mode 100644 index 00000000..8c1f58bb --- /dev/null +++ b/src/test/java11/org/yaml/snakeyaml/issues/issue310/Java11OptionalTest.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue310; + +import static org.hamcrest.CoreMatchers.instanceOf; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InaccessibleObjectException; +import java.util.Optional; +import java.util.logging.Logger; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.yaml.snakeyaml.error.YAMLException; + +public class Java11OptionalTest extends OptionalTesting { + + private static Logger log = Logger.getLogger(Java11OptionalTest.class.getPackageName()); + + @BeforeClass + public static void checkIllegalAccess() { + try { + Constructor<?> privateConstructor = Optional.class.getDeclaredConstructor(Object.class); + privateConstructor.setAccessible(true); + privateConstructor.newInstance("OptionalString"); + } catch (InaccessibleObjectException | ReflectiveOperationException | SecurityException e) { + log.warning( + "Expecting exceptions in these tests because reflective access has been denied: " + + e.getLocalizedMessage()); + reflectiveAccessDenied = true; + } + } + + @Rule + public final ExpectedException expectedException = ExpectedException.none(); + + @Before + public void configureExpectedExceptions() { + if (reflectiveAccessDenied) { + expectedException.expect(YAMLException.class); + expectedException.expect( + new DeepThrowableCauseMatcher(instanceOf(InaccessibleObjectException.class))); + } + } + + @Test + public void testJava11OptionalStringLoad() { + loadOptionalString(); + } + + @Test + public void testJava11OptionalDumpLoad() { + dumpLoadOptional(); + } +} diff --git a/src/test/java8/org/yaml/snakeyaml/issues/issue310/Java8OptionalTest.java b/src/test/java8/org/yaml/snakeyaml/issues/issue310/Java8OptionalTest.java new file mode 100644 index 00000000..4d070907 --- /dev/null +++ b/src/test/java8/org/yaml/snakeyaml/issues/issue310/Java8OptionalTest.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue310; + +import java.lang.reflect.Constructor; +import java.util.Optional; +import java.util.logging.Logger; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class Java8OptionalTest extends OptionalTesting { + + @BeforeClass + public static void checkIllegalAccess() { + try { + Constructor<?> privateConstructor = Optional.class.getDeclaredConstructor(Object.class); + privateConstructor.setAccessible(true); + privateConstructor.newInstance("OptionalString"); + } catch (RuntimeException | ReflectiveOperationException e) { + reflectiveAccessDenied = true; + } + } + + @Before + public void skipIfReflectiveAccessDenied() { + org.junit.Assume.assumeFalse(reflectiveAccessDenied); + } + + @Test + public void testJava8OptionalStringLoad() { + loadOptionalString(); + } + + @Test + public void testJava8OptionalDumpLoad() { + dumpLoadOptional(); + } + +} diff --git a/src/test/java8/org/yaml/snakeyaml/issues/issue310/OptionalTesting.java b/src/test/java8/org/yaml/snakeyaml/issues/issue310/OptionalTesting.java new file mode 100644 index 00000000..96230334 --- /dev/null +++ b/src/test/java8/org/yaml/snakeyaml/issues/issue310/OptionalTesting.java @@ -0,0 +1,155 @@ +/** + * Copyright (c) 2008, SnakeYAML + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.yaml.snakeyaml.issues.issue310; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.representer.Represent; +import org.yaml.snakeyaml.representer.Representer; + +public class OptionalTesting { + + public static class Salary { + + private Optional<Double> income = Optional.empty(); + + public Optional<Double> getIncome() { + return income; + } + + public void setIncome(Double income) { + this.income = Optional.of(income); + } + + public void setIncome(Optional<Double> income) { + this.income = income; + } + + @Override + public String toString() { + return "Salary{" + "income=" + income + '}'; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((income == null) ? 0 : income.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Salary other = (Salary) obj; + if (income == null) { + if (other.income != null) + return false; + } else if (!income.equals(other.income)) + return false; + return true; + } + } + + public static class Person { + + private String name; + + private Optional<Salary> salary = Optional.empty(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Optional<Salary> getSalary() { + return salary; + } + + public void setSalary(Optional<Salary> salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "Person{" + "name='" + name + '\'' + ", salary=" + salary + '}'; + } + } + + public static class OptionalRepresenter extends Representer { + public OptionalRepresenter() { + this.representers.put(Optional.class, new RepresentOptional()); + } + + private class RepresentOptional implements Represent { + + public Node representData(Object data) { + Optional<?> opt = (Optional<?>) data; + List<Object> seq = new ArrayList<>(1); + seq.add(opt.get()); + return representSequence(Tag.SEQ, seq, DumperOptions.FlowStyle.FLOW); + } + } + } + + static boolean reflectiveAccessDenied = false; + + protected void loadOptionalString() { + final String yamlStr = "name: Neo Anderson\nsalary: [{income: [123456.78]}]\n"; + final Yaml yamlParser = new Yaml(new OptionalRepresenter()); + Person expectedPerson = new Person(); + Salary s = new Salary(); + s.setIncome(123456.78); + expectedPerson.setName("Neo Anderson"); + expectedPerson.setSalary(Optional.of(s)); + + final Person pFromStr = yamlParser.loadAs(yamlStr, Person.class); + + assertEquals(expectedPerson.getName(), pFromStr.getName()); + assertEquals(expectedPerson.getSalary(), pFromStr.getSalary()); + } + + protected void dumpLoadOptional() { + final Yaml yamlParser = new Yaml(new OptionalRepresenter()); + Person expectedPerson = new Person(); + Salary s = new Salary(); + s.setIncome(123456.78); + expectedPerson.setName("Neo Anderson"); + expectedPerson.setSalary(Optional.of(s)); + + String pDump = yamlParser.dump(expectedPerson); + // System.out.println(pDump); + final Person pFromDump = yamlParser.loadAs(pDump, Person.class); + + assertEquals(expectedPerson.getName(), pFromDump.getName()); + assertEquals(expectedPerson.getSalary(), pFromDump.getSalary()); + } +} diff --git a/src/test/resources/env/docker-compose.yaml b/src/test/resources/env/docker-compose.yaml new file mode 100644 index 00000000..54011838 --- /dev/null +++ b/src/test/resources/env/docker-compose.yaml @@ -0,0 +1,19 @@ +version: '3' +services: + rabbitmq: + container_name: rabbitmq + image: rabbitmq:3.8.2-management-alpine + ports: + - "15672:15672" # Management + - "4369:4369" + - "5671:5671" + - "5672:5672" + - "25672:25672" + environment: + URL1: ${EnvironmentKey1} + URL2: ${EnvironmentEmpty} + URL3: ${EnvironmentEmpty:-server3} + URL4: ${EnvironmentEmpty-server4} + URL5: ${NonExistent:-server5} + URL6: ${NonExistent-server6} + diff --git a/src/test/resources/env/env-493.yaml b/src/test/resources/env/env-493.yaml new file mode 100644 index 00000000..7b2fc861 --- /dev/null +++ b/src/test/resources/env/env-493.yaml @@ -0,0 +1,4 @@ +database: + url: ${DATABASE_URL:-jdbc:postgresql://localhost:5432/server493} + user: ${DATABASE_USER:-user493} + password: ${DATABASE_PASSWORD:-password493}
\ No newline at end of file diff --git a/src/test/resources/fuzzer/YamlFuzzer-4626423186325504 b/src/test/resources/fuzzer/YamlFuzzer-4626423186325504 new file mode 100644 index 00000000..8e5dac81 --- /dev/null +++ b/src/test/resources/fuzzer/YamlFuzzer-4626423186325504 @@ -0,0 +1 @@ +{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{{{{{{[{{
\ No newline at end of file diff --git a/src/test/resources/fuzzer/YamlFuzzer-5110034188599296 b/src/test/resources/fuzzer/YamlFuzzer-5110034188599296 new file mode 100644 index 00000000..78f0e8e0 --- /dev/null +++ b/src/test/resources/fuzzer/YamlFuzzer-5110034188599296 @@ -0,0 +1 @@ +1:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:01:02:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:03:0:+
\ No newline at end of file diff --git a/src/test/resources/fuzzer/YamlFuzzer-5167495132086272 b/src/test/resources/fuzzer/YamlFuzzer-5167495132086272 new file mode 100644 index 00000000..bf67e971 --- /dev/null +++ b/src/test/resources/fuzzer/YamlFuzzer-5167495132086272 @@ -0,0 +1 @@ +E::!!float-1B: &??
!!set
?
*??
E::
*??
E::--1B: &??
!!set
?
*??
?
!!set
?
*??
E::--8586470366B: &??
!!set
?
- *??
?
!!set
?
*??
false: &??
!!set
?
*??
?
!!set
?
*??
0B: &??
!!set
? *??
?
!!set
?
*??
0B: &??
!!set
?
*??
?
*??
?
!!set
?
*??
E::--0B: &??
!!set
?
*??
0b2B: &??
!!set
?
*??
\ No newline at end of file diff --git a/src/test/resources/fuzzer/YamlFuzzer-5427149240139776 b/src/test/resources/fuzzer/YamlFuzzer-5427149240139776 new file mode 100644 index 00000000..e84d07a4 --- /dev/null +++ b/src/test/resources/fuzzer/YamlFuzzer-5427149240139776 @@ -0,0 +1 @@ +- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/src/test/resources/fuzzer/YamlFuzzer-5868638424399872 b/src/test/resources/fuzzer/YamlFuzzer-5868638424399872 new file mode 100644 index 00000000..fa064d7f --- /dev/null +++ b/src/test/resources/fuzzer/YamlFuzzer-5868638424399872 @@ -0,0 +1 @@ +? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
\ No newline at end of file diff --git a/src/test/resources/issues/emoji.yaml b/src/test/resources/issues/emoji.yaml new file mode 100644 index 00000000..1c413d73 --- /dev/null +++ b/src/test/resources/issues/emoji.yaml @@ -0,0 +1,1470 @@ +sizes: + Basic Latin: + ASCII punctuation and symbols: 2 + ASCII digits: 10 + Latin 1 Supplement: + Latin-1 punctuation and symbols: 2 + General Punctuation: + Double punctuation for vertical text: 2 + Letterlike Symbols: + Letterlike symbol: 2 + Arrows: + Simple arrows: 6 + Arrows with modifications: 2 + Miscellaneous Technical: + User interface symbols: 16 + Keyboard symbol: 1 + Keyboard and UI symbols: 1 + Enclosed Alphanumerics: + Circled Latin letters: 1 + Geometric Shapes: + Geometric shapes: 8 + Miscellaneous Symbols: + Weather and astrological symbols: 5 + Miscellaneous mark: 10 + Weather symbol: 1 + Pointing hand symbols: 1 + Warning signs: 3 + Religious and political symbols: 4 + Emoticons: 2 + Astrological signs: 2 + Zodiacal symbol: 13 + Playing card symbols: 4 + Recycling symbols: 1 + Dictionary and map symbols: 8 + Circles: 2 + Genealogical symbols: 2 + Sport symbols: 2 + Weather symbols from ARIB STD B24: 3 + Traffic sign from ARIB STD B24: 4 + Map symbol from ARIB STD B24: 13 + Dingbats: + Miscellaneous: 20 + Crosses: 1 + Stars and asterisks: 4 + Stars, asterisks and snowflakes: 2 + Punctuation mark ornaments: 2 + Heavy variants of arithmetic symbols: 3 + Dingbat arrow: 1 + Supplemental Arrows B: + Miscellaneous curved arrows: 2 + Miscellaneous Symbols And Arrows: + White and black arrows: 3 + Squares: 2 + Stars: 1 + Traffic sign from ARIB STD B24: 1 + CJK Symbols And Punctuation: + CJK symbols: 1 + CJK Symbols And Punctuation: + Other CJK punctuation: 1 + Enclosed CJK Letters And Months: + Circled ideographs: 2 + Mahjong Tiles: + Dragon tiles: 1 + Playing Cards: + Joker: 1 + Enclosed Alphanumeric Supplement: + White on black squared Latin letters: 5 + Squared Latin letter sequences: 10 + Regional indicator symbols: 26 + Enclosed Ideographic Supplement: + Squared katakana: 2 + Squared ideographs and kana from ARIB STD B24: 2 + Squared ideographs: 9 + Circled ideographs: 2 + Miscellaneous Symbols And Pictographs: + Weather, landscape, and sky symbols: 13 + Globe symbols: 4 + Moon, sun, and star symbols: 16 + Weather symbol: 10 + Food symbol: 36 + Plant symbols: 21 + Fruit and vegetable symbols: 15 + Beverage symbols: 8 + Accommodation symbol: 1 + Beverage and food symbols: 2 + Celebration symbols: 22 + Musical symbols: 11 + Entertainment symbols: 16 + Game symbol: 8 + Sport symbols: 25 + Building and map symbols: 29 + Flag symbols: 2 + Rosettes: 1 + Miscellaneous mark: 12 + Emoji modifiers: 5 + Animal symbols: 49 + Animal faces: 17 + Facial parts symbols: 6 + Hand symbols: 14 + Clothing and accessories: 19 + Portrait and role symbols: 20 + Fairy tale symbols: 9 + Role symbol: 4 + Personal care symbols: 5 + Medical symbols: 2 + Romance symbols: 8 + Heart symbol: 14 + Comic style symbols: 14 + Japanese school grade symbols: 2 + Money symbols: 10 + Office symbols: 36 + Communication symbols: 31 + Audio and video symbols: 7 + Religious symbol: 7 + User interface symbols: 37 + Words with arrows: 5 + Enclosed alphanumeric symbols: 2 + User interface input status symbols: 5 + Tool symbols: 10 + Geometric shapes: 8 + Clock face symbols: 24 + Computer symbols: 4 + Rating symbols: 2 + Bubble symbols: 2 + Ballot symbols: 1 + Map symbol: 1 + Cultural symbols: 5 + Emoticons: + Faces: 60 + Cat faces: 9 + Gesture symbols: 11 + Transport And Map Symbols: + Vehicles: 48 + Traffic signs: 4 + Signage and other symbols: 32 + Accommodation symbol: 5 + Miscellaneous mark: 5 + Supplemental Symbols And Pictographs: + Emoticon faces: 24 + Hand symbols: 8 + Portrait and role symbols: 30 + Miscellaneous mark: 19 + Food symbol: 29 + Animal symbols: 24 +values: + Basic Latin: + ASCII punctuation and symbols: + - "#" # U+0023 NUMBER SIGN + - "*" # U+002A ASTERISK + ASCII digits: + - 0 # U+0030 DIGIT ZERO + - 1 # U+0031 DIGIT ONE + - 2 # U+0032 DIGIT TWO + - 3 # U+0033 DIGIT THREE + - 4 # U+0034 DIGIT FOUR + - 5 # U+0035 DIGIT FIVE + - 6 # U+0036 DIGIT SIX + - 7 # U+0037 DIGIT SEVEN + - 8 # U+0038 DIGIT EIGHT + - 9 # U+0039 DIGIT NINE + Latin 1 Supplement: + Latin-1 punctuation and symbols: + - ยฉ๏ธ # U+00A9 COPYRIGHT SIGN + - ยฎ๏ธ # U+00AE REGISTERED SIGN + General Punctuation: + Double punctuation for vertical text: + - โผ๏ธ # U+203C DOUBLE EXCLAMATION MARK + - โ๏ธ # U+2049 EXCLAMATION QUESTION MARK + Letterlike Symbols: + Letterlike symbol: + - โข๏ธ # U+2122 TRADE MARK SIGN + - โน # U+2139 INFORMATION SOURCE + Arrows: + Simple arrows: + - โ๏ธ # U+2194 LEFT RIGHT ARROW + - โ๏ธ # U+2195 UP DOWN ARROW + - โ๏ธ # U+2196 NORTH WEST ARROW + - โ๏ธ # U+2197 NORTH EAST ARROW + - โ๏ธ # U+2198 SOUTH EAST ARROW + - โ๏ธ # U+2199 SOUTH WEST ARROW + Arrows with modifications: + - โฉ๏ธ # U+21A9 LEFTWARDS ARROW WITH HOOK + - โช๏ธ # U+21AA RIGHTWARDS ARROW WITH HOOK + Miscellaneous Technical: + User interface symbols: + - โ๏ธ # U+231A WATCH + - โ๏ธ # U+231B HOURGLASS + - โฉ # U+23E9 BLACK RIGHT-POINTING DOUBLE TRIANGLE + - โช # U+23EA BLACK LEFT-POINTING DOUBLE TRIANGLE + - โซ # U+23EB BLACK UP-POINTING DOUBLE TRIANGLE + - โฌ # U+23EC BLACK DOWN-POINTING DOUBLE TRIANGLE + - โญ # U+23ED BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR + - โฎ # U+23EE BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR + - โฏ # U+23EF BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR + - โฐ # U+23F0 ALARM CLOCK + - โฑ # U+23F1 STOPWATCH + - โฒ # U+23F2 TIMER CLOCK + - โณ # U+23F3 HOURGLASS WITH FLOWING SAND + - โธ # U+23F8 DOUBLE VERTICAL BAR + - โน # U+23F9 BLACK SQUARE FOR STOP + - โบ # U+23FA BLACK CIRCLE FOR RECORD + Keyboard symbol: + - โจ # U+2328 KEYBOARD + Keyboard and UI symbols: + - โ # U+23CF EJECT SYMBOL + Enclosed Alphanumerics: + Circled Latin letters: + - โ๏ธ # U+24C2 CIRCLED LATIN CAPITAL LETTER M + Geometric Shapes: + Geometric shapes: + - โช๏ธ # U+25AA BLACK SMALL SQUARE + - โซ๏ธ # U+25AB WHITE SMALL SQUARE + - โถ๏ธ # U+25B6 BLACK RIGHT-POINTING TRIANGLE + - โ๏ธ # U+25C0 BLACK LEFT-POINTING TRIANGLE + - โป๏ธ # U+25FB WHITE MEDIUM SQUARE + - โผ๏ธ # U+25FC BLACK MEDIUM SQUARE + - โฝ๏ธ # U+25FD WHITE MEDIUM SMALL SQUARE + - โพ๏ธ # U+25FE BLACK MEDIUM SMALL SQUARE + Miscellaneous Symbols: + Weather and astrological symbols: + - โ๏ธ # U+2600 BLACK SUN WITH RAYS + - โ๏ธ # U+2601 CLOUD + - โ # U+2602 UMBRELLA + - โ # U+2603 SNOWMAN + - โ # U+2604 COMET + Miscellaneous mark: + - โ๏ธ # U+260E BLACK TELEPHONE + - โ๏ธ # U+2611 BALLOT BOX WITH CHECK + - โ๏ธ # U+2615 HOT BEVERAGE + - โ # U+2618 SHAMROCK + - โธ # U+2638 WHEEL OF DHARMA + - โจ๏ธ # U+2668 HOT SPRINGS + - โฟ๏ธ # U+267F WHEELCHAIR SYMBOL + - โ # U+269C FLEUR-DE-LIS + - โ ๏ธ # U+26A0 WARNING SIGN + - โก๏ธ # U+26A1 HIGH VOLTAGE SIGN + Weather symbol: + - โ๏ธ # U+2614 UMBRELLA WITH RAIN DROPS + Pointing hand symbols: + - โ๏ธ # U+261D WHITE UP POINTING INDEX + Warning signs: + - โ # U+2620 SKULL AND CROSSBONES + - โข # U+2622 RADIOACTIVE SIGN + - โฃ # U+2623 BIOHAZARD SIGN + Religious and political symbols: + - โฆ # U+2626 ORTHODOX CROSS + - โช # U+262A STAR AND CRESCENT + - โฎ # U+262E PEACE SYMBOL + - โฏ # U+262F YIN YANG + Emoticons: + - โน # U+2639 WHITE FROWNING FACE + - โบ๏ธ # U+263A WHITE SMILING FACE + Astrological signs: + - โ # U+2640 FEMALE SIGN + - โ # U+2642 MALE SIGN + Zodiacal symbol: + - โ๏ธ # U+2648 ARIES + - โ๏ธ # U+2649 TAURUS + - โ๏ธ # U+264A GEMINI + - โ๏ธ # U+264B CANCER + - โ๏ธ # U+264C LEO + - โ๏ธ # U+264D VIRGO + - โ๏ธ # U+264E LIBRA + - โ๏ธ # U+264F SCORPIUS + - โ๏ธ # U+2650 SAGITTARIUS + - โ๏ธ # U+2651 CAPRICORN + - โ๏ธ # U+2652 AQUARIUS + - โ๏ธ # U+2653 PISCES + - โ # U+26CE OPHIUCHUS + Playing card symbols: + - โ ๏ธ # U+2660 BLACK SPADE SUIT + - โฃ๏ธ # U+2663 BLACK CLUB SUIT + - โฅ๏ธ # U+2665 BLACK HEART SUIT + - โฆ๏ธ # U+2666 BLACK DIAMOND SUIT + Recycling symbols: + - โป๏ธ # U+267B BLACK UNIVERSAL RECYCLING SYMBOL + Dictionary and map symbols: + - โ # U+2692 HAMMER AND PICK + - โ๏ธ # U+2693 ANCHOR + - โ # U+2694 CROSSED SWORDS + - โ # U+2695 STAFF OF AESCULAPIUS + - โ # U+2696 SCALES + - โ # U+2697 ALEMBIC + - โ # U+2699 GEAR + - โ # U+269B ATOM SYMBOL + Circles: + - โช๏ธ # U+26AA MEDIUM WHITE CIRCLE + - โซ๏ธ # U+26AB MEDIUM BLACK CIRCLE + Genealogical symbols: + - โฐ # U+26B0 COFFIN + - โฑ # U+26B1 FUNERAL URN + Sport symbols: + - โฝ๏ธ # U+26BD SOCCER BALL + - โพ๏ธ # U+26BE BASEBALL + Weather symbols from ARIB STD B24: + - โ๏ธ # U+26C4 SNOWMAN WITHOUT SNOW + - โ
๏ธ # U+26C5 SUN BEHIND CLOUD + - โ # U+26C8 THUNDER CLOUD AND RAIN + Traffic sign from ARIB STD B24: + - โ # U+26CF PICK + - โ # U+26D1 HELMET WITH WHITE CROSS + - โ # U+26D3 CHAINS + - โ๏ธ # U+26D4 NO ENTRY + Map symbol from ARIB STD B24: + - โฉ # U+26E9 SHINTO SHRINE + - โช๏ธ # U+26EA CHURCH + - โฐ # U+26F0 MOUNTAIN + - โฑ # U+26F1 UMBRELLA ON GROUND + - โฒ๏ธ # U+26F2 FOUNTAIN + - โณ๏ธ # U+26F3 FLAG IN HOLE + - โด # U+26F4 FERRY + - โต๏ธ # U+26F5 SAILBOAT + - โท # U+26F7 SKIER + - โธ # U+26F8 ICE SKATE + - โน # U+26F9 PERSON WITH BALL + - โบ๏ธ # U+26FA TENT + - โฝ๏ธ # U+26FD FUEL PUMP + Dingbats: + Miscellaneous: + - โ๏ธ # U+2702 BLACK SCISSORS + - โ
# U+2705 WHITE HEAVY CHECK MARK + - โ๏ธ # U+2708 AIRPLANE + - โ๏ธ # U+2709 ENVELOPE + - โ # U+270A RAISED FIST + - โ # U+270B RAISED HAND + - โ๏ธ # U+270C VICTORY HAND + - โ # U+270D WRITING HAND + - โ๏ธ # U+270F PENCIL + - โ๏ธ # U+2712 BLACK NIB + - โ๏ธ # U+2714 HEAVY CHECK MARK + - โ๏ธ # U+2716 HEAVY MULTIPLICATION X + - โ # U+274C CROSS MARK + - โ # U+274E NEGATIVE SQUARED CROSS MARK + - โ # U+2753 BLACK QUESTION MARK ORNAMENT + - โ # U+2754 WHITE QUESTION MARK ORNAMENT + - โ # U+2755 WHITE EXCLAMATION MARK ORNAMENT + - โ๏ธ # U+2757 HEAVY EXCLAMATION MARK SYMBOL + - โฐ # U+27B0 CURLY LOOP + - โฟ # U+27BF DOUBLE CURLY LOOP + Crosses: + - โ # U+271D LATIN CROSS + Stars and asterisks: + - โก # U+2721 STAR OF DAVID + - โจ # U+2728 SPARKLES + - โณ๏ธ # U+2733 EIGHT SPOKED ASTERISK + - โด๏ธ # U+2734 EIGHT POINTED BLACK STAR + Stars, asterisks and snowflakes: + - โ๏ธ # U+2744 SNOWFLAKE + - โ๏ธ # U+2747 SPARKLE + Punctuation mark ornaments: + - โฃ # U+2763 HEAVY HEART EXCLAMATION MARK ORNAMENT + - โค๏ธ # U+2764 HEAVY BLACK HEART + Heavy variants of arithmetic symbols: + - โ # U+2795 HEAVY PLUS SIGN + - โ # U+2796 HEAVY MINUS SIGN + - โ # U+2797 HEAVY DIVISION SIGN + Dingbat arrow: + - โก๏ธ # U+27A1 BLACK RIGHTWARDS ARROW + Supplemental Arrows B: + Miscellaneous curved arrows: + - โคด๏ธ # U+2934 ARROW POINTING RIGHTWARDS THEN CURVING UPWARDS + - โคต๏ธ # U+2935 ARROW POINTING RIGHTWARDS THEN CURVING DOWNWARDS + Miscellaneous Symbols And Arrows: + White and black arrows: + - โฌ
๏ธ # U+2B05 LEFTWARDS BLACK ARROW + - โฌ๏ธ # U+2B06 UPWARDS BLACK ARROW + - โฌ๏ธ # U+2B07 DOWNWARDS BLACK ARROW + Squares: + - โฌ๏ธ # U+2B1B BLACK LARGE SQUARE + - โฌ๏ธ # U+2B1C WHITE LARGE SQUARE + Stars: + - โญ๏ธ # U+2B50 WHITE MEDIUM STAR + Traffic sign from ARIB STD B24: + - โญ๏ธ # U+2B55 HEAVY LARGE CIRCLE + CJK Symbols And Punctuation: + CJK symbols: + - ใฐ๏ธ # U+3030 WAVY DASH + CJK Symbols And Punctuation: + Other CJK punctuation: + - ใฝ๏ธ # U+303D PART ALTERNATION MARK + Enclosed CJK Letters And Months: + Circled ideographs: + - ใ๏ธ # U+3297 CIRCLED IDEOGRAPH CONGRATULATION + - ใ๏ธ # U+3299 CIRCLED IDEOGRAPH SECRET + Mahjong Tiles: + Dragon tiles: + - ๐๏ธ # U+1F004 MAHJONG TILE RED DRAGON + Playing Cards: + Joker: + - ๐ # U+1F0CF PLAYING CARD BLACK JOKER + Enclosed Alphanumeric Supplement: + White on black squared Latin letters: + - ๐
ฐ๏ธ # U+1F170 NEGATIVE SQUARED LATIN CAPITAL LETTER A + - ๐
ฑ๏ธ # U+1F171 NEGATIVE SQUARED LATIN CAPITAL LETTER B + - ๐
พ๏ธ # U+1F17E NEGATIVE SQUARED LATIN CAPITAL LETTER O + - ๐
ฟ๏ธ # U+1F17F NEGATIVE SQUARED LATIN CAPITAL LETTER P + - ๐ # U+1F18E NEGATIVE SQUARED AB + Squared Latin letter sequences: + - ๐ # U+1F191 SQUARED CL + - ๐ # U+1F192 SQUARED COOL + - ๐ # U+1F193 SQUARED FREE + - ๐ # U+1F194 SQUARED ID + - ๐ # U+1F195 SQUARED NEW + - ๐ # U+1F196 SQUARED NG + - ๐ # U+1F197 SQUARED OK + - ๐ # U+1F198 SQUARED SOS + - ๐ # U+1F199 SQUARED UP WITH EXCLAMATION MARK + - ๐ # U+1F19A SQUARED VS + Regional indicator symbols: + - ๐ฆ # U+1F1E6 REGIONAL INDICATOR SYMBOL LETTER A + - ๐ง # U+1F1E7 REGIONAL INDICATOR SYMBOL LETTER B + - ๐จ # U+1F1E8 REGIONAL INDICATOR SYMBOL LETTER C + - ๐ฉ # U+1F1E9 REGIONAL INDICATOR SYMBOL LETTER D + - ๐ช # U+1F1EA REGIONAL INDICATOR SYMBOL LETTER E + - ๐ซ # U+1F1EB REGIONAL INDICATOR SYMBOL LETTER F + - ๐ฌ # U+1F1EC REGIONAL INDICATOR SYMBOL LETTER G + - ๐ญ # U+1F1ED REGIONAL INDICATOR SYMBOL LETTER H + - ๐ฎ # U+1F1EE REGIONAL INDICATOR SYMBOL LETTER I + - ๐ฏ # U+1F1EF REGIONAL INDICATOR SYMBOL LETTER J + - ๐ฐ # U+1F1F0 REGIONAL INDICATOR SYMBOL LETTER K + - ๐ฑ # U+1F1F1 REGIONAL INDICATOR SYMBOL LETTER L + - ๐ฒ # U+1F1F2 REGIONAL INDICATOR SYMBOL LETTER M + - ๐ณ # U+1F1F3 REGIONAL INDICATOR SYMBOL LETTER N + - ๐ด # U+1F1F4 REGIONAL INDICATOR SYMBOL LETTER O + - ๐ต # U+1F1F5 REGIONAL INDICATOR SYMBOL LETTER P + - ๐ถ # U+1F1F6 REGIONAL INDICATOR SYMBOL LETTER Q + - ๐ท # U+1F1F7 REGIONAL INDICATOR SYMBOL LETTER R + - ๐ธ # U+1F1F8 REGIONAL INDICATOR SYMBOL LETTER S + - ๐น # U+1F1F9 REGIONAL INDICATOR SYMBOL LETTER T + - ๐บ # U+1F1FA REGIONAL INDICATOR SYMBOL LETTER U + - ๐ป # U+1F1FB REGIONAL INDICATOR SYMBOL LETTER V + - ๐ผ # U+1F1FC REGIONAL INDICATOR SYMBOL LETTER W + - ๐ฝ # U+1F1FD REGIONAL INDICATOR SYMBOL LETTER X + - ๐พ # U+1F1FE REGIONAL INDICATOR SYMBOL LETTER Y + - ๐ฟ # U+1F1FF REGIONAL INDICATOR SYMBOL LETTER Z + Enclosed Ideographic Supplement: + Squared katakana: + - ๐ # U+1F201 SQUARED KATAKANA KOKO + - ๐๏ธ # U+1F202 SQUARED KATAKANA SA + Squared ideographs and kana from ARIB STD B24: + - ๐๏ธ # U+1F21A SQUARED CJK UNIFIED IDEOGRAPH-7121 + - ๐ฏ๏ธ # U+1F22F SQUARED CJK UNIFIED IDEOGRAPH-6307 + Squared ideographs: + - ๐ฒ # U+1F232 SQUARED CJK UNIFIED IDEOGRAPH-7981 + - ๐ณ # U+1F233 SQUARED CJK UNIFIED IDEOGRAPH-7A7A + - ๐ด # U+1F234 SQUARED CJK UNIFIED IDEOGRAPH-5408 + - ๐ต # U+1F235 SQUARED CJK UNIFIED IDEOGRAPH-6E80 + - ๐ถ # U+1F236 SQUARED CJK UNIFIED IDEOGRAPH-6709 + - ๐ท๏ธ # U+1F237 SQUARED CJK UNIFIED IDEOGRAPH-6708 + - ๐ธ # U+1F238 SQUARED CJK UNIFIED IDEOGRAPH-7533 + - ๐น # U+1F239 SQUARED CJK UNIFIED IDEOGRAPH-5272 + - ๐บ # U+1F23A SQUARED CJK UNIFIED IDEOGRAPH-55B6 + Circled ideographs: + - ๐ # U+1F250 CIRCLED IDEOGRAPH ADVANTAGE + - ๐ # U+1F251 CIRCLED IDEOGRAPH ACCEPT + Miscellaneous Symbols And Pictographs: + Weather, landscape, and sky symbols: + - ๐ # U+1F300 CYCLONE + - ๐ # U+1F301 FOGGY + - ๐ # U+1F302 CLOSED UMBRELLA + - ๐ # U+1F303 NIGHT WITH STARS + - ๐ # U+1F304 SUNRISE OVER MOUNTAINS + - ๐
# U+1F305 SUNRISE + - ๐ # U+1F306 CITYSCAPE AT DUSK + - ๐ # U+1F307 SUNSET OVER BUILDINGS + - ๐ # U+1F308 RAINBOW + - ๐ # U+1F309 BRIDGE AT NIGHT + - ๐ # U+1F30A WATER WAVE + - ๐ # U+1F30B VOLCANO + - ๐ # U+1F30C MILKY WAY + Globe symbols: + - ๐ # U+1F30D EARTH GLOBE EUROPE-AFRICA + - ๐ # U+1F30E EARTH GLOBE AMERICAS + - ๐ # U+1F30F EARTH GLOBE ASIA-AUSTRALIA + - ๐ # U+1F310 GLOBE WITH MERIDIANS + Moon, sun, and star symbols: + - ๐ # U+1F311 NEW MOON SYMBOL + - ๐ # U+1F312 WAXING CRESCENT MOON SYMBOL + - ๐ # U+1F313 FIRST QUARTER MOON SYMBOL + - ๐ # U+1F314 WAXING GIBBOUS MOON SYMBOL + - ๐ # U+1F315 FULL MOON SYMBOL + - ๐ # U+1F316 WANING GIBBOUS MOON SYMBOL + - ๐ # U+1F317 LAST QUARTER MOON SYMBOL + - ๐ # U+1F318 WANING CRESCENT MOON SYMBOL + - ๐ # U+1F319 CRESCENT MOON + - ๐ # U+1F31A NEW MOON WITH FACE + - ๐ # U+1F31B FIRST QUARTER MOON WITH FACE + - ๐ # U+1F31C LAST QUARTER MOON WITH FACE + - ๐ # U+1F31D FULL MOON WITH FACE + - ๐ # U+1F31E SUN WITH FACE + - ๐ # U+1F31F GLOWING STAR + - ๐ # U+1F320 SHOOTING STAR + Weather symbol: + - ๐ก # U+1F321 THERMOMETER + - ๐ค # U+1F324 WHITE SUN WITH SMALL CLOUD + - ๐ฅ # U+1F325 WHITE SUN BEHIND CLOUD + - ๐ฆ # U+1F326 WHITE SUN BEHIND CLOUD WITH RAIN + - ๐ง # U+1F327 CLOUD WITH RAIN + - ๐จ # U+1F328 CLOUD WITH SNOW + - ๐ฉ # U+1F329 CLOUD WITH LIGHTNING + - ๐ช # U+1F32A CLOUD WITH TORNADO + - ๐ซ # U+1F32B FOG + - ๐ฌ # U+1F32C WIND BLOWING FACE + Food symbol: + - ๐ญ # U+1F32D HOT DOG + - ๐ฎ # U+1F32E TACO + - ๐ฏ # U+1F32F BURRITO + - ๐ # U+1F354 HAMBURGER + - ๐ # U+1F355 SLICE OF PIZZA + - ๐ # U+1F356 MEAT ON BONE + - ๐ # U+1F357 POULTRY LEG + - ๐ # U+1F358 RICE CRACKER + - ๐ # U+1F359 RICE BALL + - ๐ # U+1F35A COOKED RICE + - ๐ # U+1F35B CURRY AND RICE + - ๐ # U+1F35C STEAMING BOWL + - ๐ # U+1F35D SPAGHETTI + - ๐ # U+1F35E BREAD + - ๐ # U+1F35F FRENCH FRIES + - ๐ # U+1F360 ROASTED SWEET POTATO + - ๐ก # U+1F361 DANGO + - ๐ข # U+1F362 ODEN + - ๐ฃ # U+1F363 SUSHI + - ๐ค # U+1F364 FRIED SHRIMP + - ๐ฅ # U+1F365 FISH CAKE WITH SWIRL DESIGN + - ๐ฆ # U+1F366 SOFT ICE CREAM + - ๐ง # U+1F367 SHAVED ICE + - ๐จ # U+1F368 ICE CREAM + - ๐ฉ # U+1F369 DOUGHNUT + - ๐ช # U+1F36A COOKIE + - ๐ซ # U+1F36B CHOCOLATE BAR + - ๐ฌ # U+1F36C CANDY + - ๐ญ # U+1F36D LOLLIPOP + - ๐ฎ # U+1F36E CUSTARD + - ๐ฏ # U+1F36F HONEY POT + - ๐ฐ # U+1F370 SHORTCAKE + - ๐ฑ # U+1F371 BENTO BOX + - ๐ฒ # U+1F372 POT OF FOOD + - ๐ณ # U+1F373 COOKING + - ๐ด # U+1F374 FORK AND KNIFE + Plant symbols: + - ๐ฐ # U+1F330 CHESTNUT + - ๐ฑ # U+1F331 SEEDLING + - ๐ฒ # U+1F332 EVERGREEN TREE + - ๐ณ # U+1F333 DECIDUOUS TREE + - ๐ด # U+1F334 PALM TREE + - ๐ต # U+1F335 CACTUS + - ๐ถ # U+1F336 HOT PEPPER + - ๐ท # U+1F337 TULIP + - ๐ธ # U+1F338 CHERRY BLOSSOM + - ๐น # U+1F339 ROSE + - ๐บ # U+1F33A HIBISCUS + - ๐ป # U+1F33B SUNFLOWER + - ๐ผ # U+1F33C BLOSSOM + - ๐ฝ # U+1F33D EAR OF MAIZE + - ๐พ # U+1F33E EAR OF RICE + - ๐ฟ # U+1F33F HERB + - ๐ # U+1F340 FOUR LEAF CLOVER + - ๐ # U+1F341 MAPLE LEAF + - ๐ # U+1F342 FALLEN LEAF + - ๐ # U+1F343 LEAF FLUTTERING IN WIND + - ๐ # U+1F344 MUSHROOM + Fruit and vegetable symbols: + - ๐
# U+1F345 TOMATO + - ๐ # U+1F346 AUBERGINE + - ๐ # U+1F347 GRAPES + - ๐ # U+1F348 MELON + - ๐ # U+1F349 WATERMELON + - ๐ # U+1F34A TANGERINE + - ๐ # U+1F34B LEMON + - ๐ # U+1F34C BANANA + - ๐ # U+1F34D PINEAPPLE + - ๐ # U+1F34E RED APPLE + - ๐ # U+1F34F GREEN APPLE + - ๐ # U+1F350 PEAR + - ๐ # U+1F351 PEACH + - ๐ # U+1F352 CHERRIES + - ๐ # U+1F353 STRAWBERRY + Beverage symbols: + - ๐ต # U+1F375 TEACUP WITHOUT HANDLE + - ๐ถ # U+1F376 SAKE BOTTLE AND CUP + - ๐ท # U+1F377 WINE GLASS + - ๐ธ # U+1F378 COCKTAIL GLASS + - ๐น # U+1F379 TROPICAL DRINK + - ๐บ # U+1F37A BEER MUG + - ๐ป # U+1F37B CLINKING BEER MUGS + - ๐ผ # U+1F37C BABY BOTTLE + Accommodation symbol: + - ๐ฝ # U+1F37D FORK AND KNIFE WITH PLATE + Beverage and food symbols: + - ๐พ # U+1F37E BOTTLE WITH POPPING CORK + - ๐ฟ # U+1F37F POPCORN + Celebration symbols: + - ๐ # U+1F380 RIBBON + - ๐ # U+1F381 WRAPPED PRESENT + - ๐ # U+1F382 BIRTHDAY CAKE + - ๐ # U+1F383 JACK-O-LANTERN + - ๐ # U+1F384 CHRISTMAS TREE + - ๐
# U+1F385 FATHER CHRISTMAS + - ๐ # U+1F386 FIREWORKS + - ๐ # U+1F387 FIREWORK SPARKLER + - ๐ # U+1F388 BALLOON + - ๐ # U+1F389 PARTY POPPER + - ๐ # U+1F38A CONFETTI BALL + - ๐ # U+1F38B TANABATA TREE + - ๐ # U+1F38C CROSSED FLAGS + - ๐ # U+1F38D PINE DECORATION + - ๐ # U+1F38E JAPANESE DOLLS + - ๐ # U+1F38F CARP STREAMER + - ๐ # U+1F390 WIND CHIME + - ๐ # U+1F391 MOON VIEWING CEREMONY + - ๐ # U+1F392 SCHOOL SATCHEL + - ๐ # U+1F393 GRADUATION CAP + - ๐ # U+1F396 MILITARY MEDAL + - ๐ # U+1F397 REMINDER RIBBON + Musical symbols: + - ๐ # U+1F399 STUDIO MICROPHONE + - ๐ # U+1F39A LEVEL SLIDER + - ๐ # U+1F39B CONTROL KNOBS + - ๐ต # U+1F3B5 MUSICAL NOTE + - ๐ถ # U+1F3B6 MULTIPLE MUSICAL NOTES + - ๐ท # U+1F3B7 SAXOPHONE + - ๐ธ # U+1F3B8 GUITAR + - ๐น # U+1F3B9 MUSICAL KEYBOARD + - ๐บ # U+1F3BA TRUMPET + - ๐ป # U+1F3BB VIOLIN + - ๐ผ # U+1F3BC MUSICAL SCORE + Entertainment symbols: + - ๐ # U+1F39E FILM FRAMES + - ๐ # U+1F39F ADMISSION TICKETS + - ๐ # U+1F3A0 CAROUSEL HORSE + - ๐ก # U+1F3A1 FERRIS WHEEL + - ๐ข # U+1F3A2 ROLLER COASTER + - ๐ฃ # U+1F3A3 FISHING POLE AND FISH + - ๐ค # U+1F3A4 MICROPHONE + - ๐ฅ # U+1F3A5 MOVIE CAMERA + - ๐ฆ # U+1F3A6 CINEMA + - ๐ง # U+1F3A7 HEADPHONE + - ๐จ # U+1F3A8 ARTIST PALETTE + - ๐ฉ # U+1F3A9 TOP HAT + - ๐ช # U+1F3AA CIRCUS TENT + - ๐ซ # U+1F3AB TICKET + - ๐ฌ # U+1F3AC CLAPPER BOARD + - ๐ญ # U+1F3AD PERFORMING ARTS + Game symbol: + - ๐ฎ # U+1F3AE VIDEO GAME + - ๐ฏ # U+1F3AF DIRECT HIT + - ๐ฐ # U+1F3B0 SLOT MACHINE + - ๐ฑ # U+1F3B1 BILLIARDS + - ๐ฒ # U+1F3B2 GAME DIE + - ๐ณ # U+1F3B3 BOWLING + - ๐ด # U+1F3B4 FLOWER PLAYING CARDS + - ๐น # U+1F579 JOYSTICK + Sport symbols: + - ๐ฝ # U+1F3BD RUNNING SHIRT WITH SASH + - ๐พ # U+1F3BE TENNIS RACQUET AND BALL + - ๐ฟ # U+1F3BF SKI AND SKI BOOT + - ๐ # U+1F3C0 BASKETBALL AND HOOP + - ๐ # U+1F3C1 CHEQUERED FLAG + - ๐ # U+1F3C2 SNOWBOARDER + - ๐ # U+1F3C3 RUNNER + - ๐ # U+1F3C4 SURFER + - ๐
# U+1F3C5 SPORTS MEDAL + - ๐ # U+1F3C6 TROPHY + - ๐ # U+1F3C7 HORSE RACING + - ๐ # U+1F3C8 AMERICAN FOOTBALL + - ๐ # U+1F3C9 RUGBY FOOTBALL + - ๐ # U+1F3CA SWIMMER + - ๐ # U+1F3CB WEIGHT LIFTER + - ๐ # U+1F3CC GOLFER + - ๐ # U+1F3CD RACING MOTORCYCLE + - ๐ # U+1F3CE RACING CAR + - ๐ # U+1F3CF CRICKET BAT AND BALL + - ๐ # U+1F3D0 VOLLEYBALL + - ๐ # U+1F3D1 FIELD HOCKEY STICK AND BALL + - ๐ # U+1F3D2 ICE HOCKEY STICK AND PUCK + - ๐ # U+1F3D3 TABLE TENNIS PADDLE AND BALL + - ๐ธ # U+1F3F8 BADMINTON RACQUET AND SHUTTLECOCK + - ๐น # U+1F3F9 BOW AND ARROW + Building and map symbols: + - ๐ # U+1F3D4 SNOW CAPPED MOUNTAIN + - ๐ # U+1F3D5 CAMPING + - ๐ # U+1F3D6 BEACH WITH UMBRELLA + - ๐ # U+1F3D7 BUILDING CONSTRUCTION + - ๐ # U+1F3D8 HOUSE BUILDINGS + - ๐ # U+1F3D9 CITYSCAPE + - ๐ # U+1F3DA DERELICT HOUSE BUILDING + - ๐ # U+1F3DB CLASSICAL BUILDING + - ๐ # U+1F3DC DESERT + - ๐ # U+1F3DD DESERT ISLAND + - ๐ # U+1F3DE NATIONAL PARK + - ๐ # U+1F3DF STADIUM + - ๐ # U+1F3E0 HOUSE BUILDING + - ๐ก # U+1F3E1 HOUSE WITH GARDEN + - ๐ข # U+1F3E2 OFFICE BUILDING + - ๐ฃ # U+1F3E3 JAPANESE POST OFFICE + - ๐ค # U+1F3E4 EUROPEAN POST OFFICE + - ๐ฅ # U+1F3E5 HOSPITAL + - ๐ฆ # U+1F3E6 BANK + - ๐ง # U+1F3E7 AUTOMATED TELLER MACHINE + - ๐จ # U+1F3E8 HOTEL + - ๐ฉ # U+1F3E9 LOVE HOTEL + - ๐ช # U+1F3EA CONVENIENCE STORE + - ๐ซ # U+1F3EB SCHOOL + - ๐ฌ # U+1F3EC DEPARTMENT STORE + - ๐ญ # U+1F3ED FACTORY + - ๐ฎ # U+1F3EE IZAKAYA LANTERN + - ๐ฏ # U+1F3EF JAPANESE CASTLE + - ๐ฐ # U+1F3F0 EUROPEAN CASTLE + Flag symbols: + - ๐ณ # U+1F3F3 WAVING WHITE FLAG + - ๐ด # U+1F3F4 WAVING BLACK FLAG + Rosettes: + - ๐ต # U+1F3F5 ROSETTE + Miscellaneous mark: + - ๐ท # U+1F3F7 LABEL + - ๐บ # U+1F3FA AMPHORA + - ๐ฏ # U+1F52F SIX POINTED STAR WITH MIDDLE DOT + - ๐ฐ # U+1F530 JAPANESE SYMBOL FOR BEGINNER + - ๐ฑ # U+1F531 TRIDENT EMBLEM + - ๐ฏ # U+1F56F CANDLE + - ๐ฐ # U+1F570 MANTELPIECE CLOCK + - ๐ณ # U+1F573 HOLE + - ๐ด # U+1F574 MAN IN BUSINESS SUIT LEVITATING + - ๐ต # U+1F575 SLEUTH OR SPY + - ๐ถ # U+1F576 DARK SUNGLASSES + - ๐ # U+1F5DE ROLLED-UP NEWSPAPER + Emoji modifiers: + - ๐ป # U+1F3FB EMOJI MODIFIER FITZPATRICK TYPE-1-2 + - ๐ผ # U+1F3FC EMOJI MODIFIER FITZPATRICK TYPE-3 + - ๐ฝ # U+1F3FD EMOJI MODIFIER FITZPATRICK TYPE-4 + - ๐พ # U+1F3FE EMOJI MODIFIER FITZPATRICK TYPE-5 + - ๐ฟ # U+1F3FF EMOJI MODIFIER FITZPATRICK TYPE-6 + Animal symbols: + - ๐ # U+1F400 RAT + - ๐ # U+1F401 MOUSE + - ๐ # U+1F402 OX + - ๐ # U+1F403 WATER BUFFALO + - ๐ # U+1F404 COW + - ๐
# U+1F405 TIGER + - ๐ # U+1F406 LEOPARD + - ๐ # U+1F407 RABBIT + - ๐ # U+1F408 CAT + - ๐ # U+1F409 DRAGON + - ๐ # U+1F40A CROCODILE + - ๐ # U+1F40B WHALE + - ๐ # U+1F40C SNAIL + - ๐ # U+1F40D SNAKE + - ๐ # U+1F40E HORSE + - ๐ # U+1F40F RAM + - ๐ # U+1F410 GOAT + - ๐ # U+1F411 SHEEP + - ๐ # U+1F412 MONKEY + - ๐ # U+1F413 ROOSTER + - ๐ # U+1F414 CHICKEN + - ๐ # U+1F415 DOG + - ๐ # U+1F416 PIG + - ๐ # U+1F417 BOAR + - ๐ # U+1F418 ELEPHANT + - ๐ # U+1F419 OCTOPUS + - ๐ # U+1F41A SPIRAL SHELL + - ๐ # U+1F41B BUG + - ๐ # U+1F41C ANT + - ๐ # U+1F41D HONEYBEE + - ๐ # U+1F41E LADY BEETLE + - ๐ # U+1F41F FISH + - ๐ # U+1F420 TROPICAL FISH + - ๐ก # U+1F421 BLOWFISH + - ๐ข # U+1F422 TURTLE + - ๐ฃ # U+1F423 HATCHING CHICK + - ๐ค # U+1F424 BABY CHICK + - ๐ฅ # U+1F425 FRONT-FACING BABY CHICK + - ๐ฆ # U+1F426 BIRD + - ๐ง # U+1F427 PENGUIN + - ๐จ # U+1F428 KOALA + - ๐ฉ # U+1F429 POODLE + - ๐ช # U+1F42A DROMEDARY CAMEL + - ๐ซ # U+1F42B BACTRIAN CAMEL + - ๐ฌ # U+1F42C DOLPHIN + - ๐พ # U+1F43E PAW PRINTS + - ๐ฟ # U+1F43F CHIPMUNK + - ๐ท # U+1F577 SPIDER + - ๐ธ # U+1F578 SPIDER WEB + Animal faces: + - ๐ญ # U+1F42D MOUSE FACE + - ๐ฎ # U+1F42E COW FACE + - ๐ฏ # U+1F42F TIGER FACE + - ๐ฐ # U+1F430 RABBIT FACE + - ๐ฑ # U+1F431 CAT FACE + - ๐ฒ # U+1F432 DRAGON FACE + - ๐ณ # U+1F433 SPOUTING WHALE + - ๐ด # U+1F434 HORSE FACE + - ๐ต # U+1F435 MONKEY FACE + - ๐ถ # U+1F436 DOG FACE + - ๐ท # U+1F437 PIG FACE + - ๐ธ # U+1F438 FROG FACE + - ๐น # U+1F439 HAMSTER FACE + - ๐บ # U+1F43A WOLF FACE + - ๐ป # U+1F43B BEAR FACE + - ๐ผ # U+1F43C PANDA FACE + - ๐ฝ # U+1F43D PIG NOSE + Facial parts symbols: + - ๐ # U+1F440 EYES + - ๐ # U+1F441 EYE + - ๐ # U+1F442 EAR + - ๐ # U+1F443 NOSE + - ๐ # U+1F444 MOUTH + - ๐
# U+1F445 TONGUE + Hand symbols: + - ๐ # U+1F446 WHITE UP POINTING BACKHAND INDEX + - ๐ # U+1F447 WHITE DOWN POINTING BACKHAND INDEX + - ๐ # U+1F448 WHITE LEFT POINTING BACKHAND INDEX + - ๐ # U+1F449 WHITE RIGHT POINTING BACKHAND INDEX + - ๐ # U+1F44A FISTED HAND SIGN + - ๐ # U+1F44B WAVING HAND SIGN + - ๐ # U+1F44C OK HAND SIGN + - ๐ # U+1F44D THUMBS UP SIGN + - ๐ # U+1F44E THUMBS DOWN SIGN + - ๐ # U+1F44F CLAPPING HANDS SIGN + - ๐ # U+1F450 OPEN HANDS SIGN + - ๐ # U+1F590 RAISED HAND WITH FINGERS SPLAYED + - ๐ # U+1F595 REVERSED HAND WITH MIDDLE FINGER EXTENDED + - ๐ # U+1F596 RAISED HAND WITH PART BETWEEN MIDDLE AND RING FINGERS + Clothing and accessories: + - ๐ # U+1F451 CROWN + - ๐ # U+1F452 WOMANS HAT + - ๐ # U+1F453 EYEGLASSES + - ๐ # U+1F454 NECKTIE + - ๐ # U+1F455 T-SHIRT + - ๐ # U+1F456 JEANS + - ๐ # U+1F457 DRESS + - ๐ # U+1F458 KIMONO + - ๐ # U+1F459 BIKINI + - ๐ # U+1F45A WOMANS CLOTHES + - ๐ # U+1F45B PURSE + - ๐ # U+1F45C HANDBAG + - ๐ # U+1F45D POUCH + - ๐ # U+1F45E MANS SHOE + - ๐ # U+1F45F ATHLETIC SHOE + - ๐ # U+1F460 HIGH-HEELED SHOE + - ๐ก # U+1F461 WOMANS SANDAL + - ๐ข # U+1F462 WOMANS BOOTS + - ๐ฃ # U+1F463 FOOTPRINTS + Portrait and role symbols: + - ๐ค # U+1F464 BUST IN SILHOUETTE + - ๐ฅ # U+1F465 BUSTS IN SILHOUETTE + - ๐ฆ # U+1F466 BOY + - ๐ง # U+1F467 GIRL + - ๐จ # U+1F468 MAN + - ๐ฉ # U+1F469 WOMAN + - ๐ช # U+1F46A FAMILY + - ๐ซ # U+1F46B MAN AND WOMAN HOLDING HANDS + - ๐ฌ # U+1F46C TWO MEN HOLDING HANDS + - ๐ญ # U+1F46D TWO WOMEN HOLDING HANDS + - ๐ฎ # U+1F46E POLICE OFFICER + - ๐ฏ # U+1F46F WOMAN WITH BUNNY EARS + - ๐ฐ # U+1F470 BRIDE WITH VEIL + - ๐ฑ # U+1F471 PERSON WITH BLOND HAIR + - ๐ฒ # U+1F472 MAN WITH GUA PI MAO + - ๐ณ # U+1F473 MAN WITH TURBAN + - ๐ด # U+1F474 OLDER MAN + - ๐ต # U+1F475 OLDER WOMAN + - ๐ถ # U+1F476 BABY + - ๐ท # U+1F477 CONSTRUCTION WORKER + Fairy tale symbols: + - ๐ธ # U+1F478 PRINCESS + - ๐น # U+1F479 JAPANESE OGRE + - ๐บ # U+1F47A JAPANESE GOBLIN + - ๐ป # U+1F47B GHOST + - ๐ผ # U+1F47C BABY ANGEL + - ๐ฝ # U+1F47D EXTRATERRESTRIAL ALIEN + - ๐พ # U+1F47E ALIEN MONSTER + - ๐ฟ # U+1F47F IMP + - ๐ # U+1F480 SKULL + Role symbol: + - ๐ # U+1F481 INFORMATION DESK PERSON + - ๐ # U+1F482 GUARDSMAN + - ๐ # U+1F483 DANCER + - ๐บ # U+1F57A MAN DANCING + Personal care symbols: + - ๐ # U+1F484 LIPSTICK + - ๐
# U+1F485 NAIL POLISH + - ๐ # U+1F486 FACE MASSAGE + - ๐ # U+1F487 HAIRCUT + - ๐ # U+1F488 BARBER POLE + Medical symbols: + - ๐ # U+1F489 SYRINGE + - ๐ # U+1F48A PILL + Romance symbols: + - ๐ # U+1F48B KISS MARK + - ๐ # U+1F48C LOVE LETTER + - ๐ # U+1F48D RING + - ๐ # U+1F48E GEM STONE + - ๐ # U+1F48F KISS + - ๐ # U+1F490 BOUQUET + - ๐ # U+1F491 COUPLE WITH HEART + - ๐ # U+1F492 WEDDING + Heart symbol: + - ๐ # U+1F493 BEATING HEART + - ๐ # U+1F494 BROKEN HEART + - ๐ # U+1F495 TWO HEARTS + - ๐ # U+1F496 SPARKLING HEART + - ๐ # U+1F497 GROWING HEART + - ๐ # U+1F498 HEART WITH ARROW + - ๐ # U+1F499 BLUE HEART + - ๐ # U+1F49A GREEN HEART + - ๐ # U+1F49B YELLOW HEART + - ๐ # U+1F49C PURPLE HEART + - ๐ # U+1F49D HEART WITH RIBBON + - ๐ # U+1F49E REVOLVING HEARTS + - ๐ # U+1F49F HEART DECORATION + - ๐ค # U+1F5A4 BLACK HEART + Comic style symbols: + - ๐ # U+1F4A0 DIAMOND SHAPE WITH A DOT INSIDE + - ๐ก # U+1F4A1 ELECTRIC LIGHT BULB + - ๐ข # U+1F4A2 ANGER SYMBOL + - ๐ฃ # U+1F4A3 BOMB + - ๐ค # U+1F4A4 SLEEPING SYMBOL + - ๐ฅ # U+1F4A5 COLLISION SYMBOL + - ๐ฆ # U+1F4A6 SPLASHING SWEAT SYMBOL + - ๐ง # U+1F4A7 DROPLET + - ๐จ # U+1F4A8 DASH SYMBOL + - ๐ฉ # U+1F4A9 PILE OF POO + - ๐ช # U+1F4AA FLEXED BICEPS + - ๐ซ # U+1F4AB DIZZY SYMBOL + - ๐ฌ # U+1F4AC SPEECH BALLOON + - ๐ญ # U+1F4AD THOUGHT BALLOON + Japanese school grade symbols: + - ๐ฎ # U+1F4AE WHITE FLOWER + - ๐ฏ # U+1F4AF HUNDRED POINTS SYMBOL + Money symbols: + - ๐ฐ # U+1F4B0 MONEY BAG + - ๐ฑ # U+1F4B1 CURRENCY EXCHANGE + - ๐ฒ # U+1F4B2 HEAVY DOLLAR SIGN + - ๐ณ # U+1F4B3 CREDIT CARD + - ๐ด # U+1F4B4 BANKNOTE WITH YEN SIGN + - ๐ต # U+1F4B5 BANKNOTE WITH DOLLAR SIGN + - ๐ถ # U+1F4B6 BANKNOTE WITH EURO SIGN + - ๐ท # U+1F4B7 BANKNOTE WITH POUND SIGN + - ๐ธ # U+1F4B8 MONEY WITH WINGS + - ๐น # U+1F4B9 CHART WITH UPWARDS TREND AND YEN SIGN + Office symbols: + - ๐บ # U+1F4BA SEAT + - ๐ป # U+1F4BB PERSONAL COMPUTER + - ๐ผ # U+1F4BC BRIEFCASE + - ๐ฝ # U+1F4BD MINIDISC + - ๐พ # U+1F4BE FLOPPY DISK + - ๐ฟ # U+1F4BF OPTICAL DISC + - ๐ # U+1F4C0 DVD + - ๐ # U+1F4C1 FILE FOLDER + - ๐ # U+1F4C2 OPEN FILE FOLDER + - ๐ # U+1F4C3 PAGE WITH CURL + - ๐ # U+1F4C4 PAGE FACING UP + - ๐
# U+1F4C5 CALENDAR + - ๐ # U+1F4C6 TEAR-OFF CALENDAR + - ๐ # U+1F4C7 CARD INDEX + - ๐ # U+1F4C8 CHART WITH UPWARDS TREND + - ๐ # U+1F4C9 CHART WITH DOWNWARDS TREND + - ๐ # U+1F4CA BAR CHART + - ๐ # U+1F4CB CLIPBOARD + - ๐ # U+1F4CC PUSHPIN + - ๐ # U+1F4CD ROUND PUSHPIN + - ๐ # U+1F4CE PAPERCLIP + - ๐ # U+1F4CF STRAIGHT RULER + - ๐ # U+1F4D0 TRIANGULAR RULER + - ๐ # U+1F4D1 BOOKMARK TABS + - ๐ # U+1F4D2 LEDGER + - ๐ # U+1F4D3 NOTEBOOK + - ๐ # U+1F4D4 NOTEBOOK WITH DECORATIVE COVER + - ๐ # U+1F4D5 CLOSED BOOK + - ๐ # U+1F4D6 OPEN BOOK + - ๐ # U+1F4D7 GREEN BOOK + - ๐ # U+1F4D8 BLUE BOOK + - ๐ # U+1F4D9 ORANGE BOOK + - ๐ # U+1F4DA BOOKS + - ๐ # U+1F4DB NAME BADGE + - ๐ # U+1F4DC SCROLL + - ๐ผ # U+1F5BC FRAME WITH PICTURE + Communication symbols: + - ๐ # U+1F4DD MEMO + - ๐ # U+1F4DE TELEPHONE RECEIVER + - ๐ # U+1F4DF PAGER + - ๐ # U+1F4E0 FAX MACHINE + - ๐ก # U+1F4E1 SATELLITE ANTENNA + - ๐ข # U+1F4E2 PUBLIC ADDRESS LOUDSPEAKER + - ๐ฃ # U+1F4E3 CHEERING MEGAPHONE + - ๐ค # U+1F4E4 OUTBOX TRAY + - ๐ฅ # U+1F4E5 INBOX TRAY + - ๐ฆ # U+1F4E6 PACKAGE + - ๐ง # U+1F4E7 E-MAIL SYMBOL + - ๐จ # U+1F4E8 INCOMING ENVELOPE + - ๐ฉ # U+1F4E9 ENVELOPE WITH DOWNWARDS ARROW ABOVE + - ๐ช # U+1F4EA CLOSED MAILBOX WITH LOWERED FLAG + - ๐ซ # U+1F4EB CLOSED MAILBOX WITH RAISED FLAG + - ๐ฌ # U+1F4EC OPEN MAILBOX WITH RAISED FLAG + - ๐ญ # U+1F4ED OPEN MAILBOX WITH LOWERED FLAG + - ๐ฎ # U+1F4EE POSTBOX + - ๐ฏ # U+1F4EF POSTAL HORN + - ๐ฐ # U+1F4F0 NEWSPAPER + - ๐ฑ # U+1F4F1 MOBILE PHONE + - ๐ฒ # U+1F4F2 MOBILE PHONE WITH RIGHTWARDS ARROW AT LEFT + - ๐ณ # U+1F4F3 VIBRATION MODE + - ๐ด # U+1F4F4 MOBILE PHONE OFF + - ๐ต # U+1F4F5 NO MOBILE PHONES + - ๐ถ # U+1F4F6 ANTENNA WITH BARS + - ๐ # U+1F587 LINKED PAPERCLIPS + - ๐ # U+1F58A LOWER LEFT BALLPOINT PEN + - ๐ # U+1F58B LOWER LEFT FOUNTAIN PEN + - ๐ # U+1F58C LOWER LEFT PAINTBRUSH + - ๐ # U+1F58D LOWER LEFT CRAYON + Audio and video symbols: + - ๐ท # U+1F4F7 CAMERA + - ๐ธ # U+1F4F8 CAMERA WITH FLASH + - ๐น # U+1F4F9 VIDEO CAMERA + - ๐บ # U+1F4FA TELEVISION + - ๐ป # U+1F4FB RADIO + - ๐ผ # U+1F4FC VIDEOCASSETTE + - ๐ฝ # U+1F4FD FILM PROJECTOR + Religious symbol: + - ๐ฟ # U+1F4FF PRAYER BEADS + - ๐ # U+1F549 OM SYMBOL + - ๐ # U+1F54A DOVE OF PEACE + - ๐ # U+1F54B KAABA + - ๐ # U+1F54C MOSQUE + - ๐ # U+1F54D SYNAGOGUE + - ๐ # U+1F54E MENORAH WITH NINE BRANCHES + User interface symbols: + - ๐ # U+1F500 TWISTED RIGHTWARDS ARROWS + - ๐ # U+1F501 CLOCKWISE RIGHTWARDS AND LEFTWARDS OPEN CIRCLE ARROWS + - ๐ # U+1F502 CLOCKWISE RIGHTWARDS AND LEFTWARDS OPEN CIRCLE ARROWS WITH CIRCLED ONE OVERLAY + - ๐ # U+1F503 CLOCKWISE DOWNWARDS AND UPWARDS OPEN CIRCLE ARROWS + - ๐ # U+1F504 ANTICLOCKWISE DOWNWARDS AND UPWARDS OPEN CIRCLE ARROWS + - ๐
# U+1F505 LOW BRIGHTNESS SYMBOL + - ๐ # U+1F506 HIGH BRIGHTNESS SYMBOL + - ๐ # U+1F507 SPEAKER WITH CANCELLATION STROKE + - ๐ # U+1F508 SPEAKER + - ๐ # U+1F509 SPEAKER WITH ONE SOUND WAVE + - ๐ # U+1F50A SPEAKER WITH THREE SOUND WAVES + - ๐ # U+1F50B BATTERY + - ๐ # U+1F50C ELECTRIC PLUG + - ๐ # U+1F50D LEFT-POINTING MAGNIFYING GLASS + - ๐ # U+1F50E RIGHT-POINTING MAGNIFYING GLASS + - ๐ # U+1F50F LOCK WITH INK PEN + - ๐ # U+1F510 CLOSED LOCK WITH KEY + - ๐ # U+1F511 KEY + - ๐ # U+1F512 LOCK + - ๐ # U+1F513 OPEN LOCK + - ๐ # U+1F514 BELL + - ๐ # U+1F515 BELL WITH CANCELLATION STROKE + - ๐ # U+1F516 BOOKMARK + - ๐ # U+1F517 LINK SYMBOL + - ๐ # U+1F518 RADIO BUTTON + - ๐บ # U+1F53A UP-POINTING RED TRIANGLE + - ๐ป # U+1F53B DOWN-POINTING RED TRIANGLE + - ๐ผ # U+1F53C UP-POINTING SMALL RED TRIANGLE + - ๐ฝ # U+1F53D DOWN-POINTING SMALL RED TRIANGLE + - ๐ # U+1F5C2 CARD INDEX DIVIDERS + - ๐ # U+1F5C3 CARD FILE BOX + - ๐ # U+1F5C4 FILE CABINET + - ๐ # U+1F5D1 WASTEBASKET + - ๐ # U+1F5D2 SPIRAL NOTE PAD + - ๐ # U+1F5D3 SPIRAL CALENDAR PAD + - ๐ # U+1F5DC COMPRESSION + - ๐ # U+1F5DD OLD KEY + Words with arrows: + - ๐ # U+1F519 BACK WITH LEFTWARDS ARROW ABOVE + - ๐ # U+1F51A END WITH LEFTWARDS ARROW ABOVE + - ๐ # U+1F51B ON WITH EXCLAMATION MARK WITH LEFT RIGHT ARROW ABOVE + - ๐ # U+1F51C SOON WITH RIGHTWARDS ARROW ABOVE + - ๐ # U+1F51D TOP WITH UPWARDS ARROW ABOVE + Enclosed alphanumeric symbols: + - ๐ # U+1F51E NO ONE UNDER EIGHTEEN SYMBOL + - ๐ # U+1F51F KEYCAP TEN + User interface input status symbols: + - ๐ # U+1F520 INPUT SYMBOL FOR LATIN CAPITAL LETTERS + - ๐ก # U+1F521 INPUT SYMBOL FOR LATIN SMALL LETTERS + - ๐ข # U+1F522 INPUT SYMBOL FOR NUMBERS + - ๐ฃ # U+1F523 INPUT SYMBOL FOR SYMBOLS + - ๐ค # U+1F524 INPUT SYMBOL FOR LATIN LETTERS + Tool symbols: + - ๐ฅ # U+1F525 FIRE + - ๐ฆ # U+1F526 ELECTRIC TORCH + - ๐ง # U+1F527 WRENCH + - ๐จ # U+1F528 HAMMER + - ๐ฉ # U+1F529 NUT AND BOLT + - ๐ช # U+1F52A HOCHO + - ๐ซ # U+1F52B PISTOL + - ๐ฌ # U+1F52C MICROSCOPE + - ๐ญ # U+1F52D TELESCOPE + - ๐ฎ # U+1F52E CRYSTAL BALL + Geometric shapes: + - ๐ฒ # U+1F532 BLACK SQUARE BUTTON + - ๐ณ # U+1F533 WHITE SQUARE BUTTON + - ๐ด # U+1F534 LARGE RED CIRCLE + - ๐ต # U+1F535 LARGE BLUE CIRCLE + - ๐ถ # U+1F536 LARGE ORANGE DIAMOND + - ๐ท # U+1F537 LARGE BLUE DIAMOND + - ๐ธ # U+1F538 SMALL ORANGE DIAMOND + - ๐น # U+1F539 SMALL BLUE DIAMOND + Clock face symbols: + - ๐ # U+1F550 CLOCK FACE ONE OCLOCK + - ๐ # U+1F551 CLOCK FACE TWO OCLOCK + - ๐ # U+1F552 CLOCK FACE THREE OCLOCK + - ๐ # U+1F553 CLOCK FACE FOUR OCLOCK + - ๐ # U+1F554 CLOCK FACE FIVE OCLOCK + - ๐ # U+1F555 CLOCK FACE SIX OCLOCK + - ๐ # U+1F556 CLOCK FACE SEVEN OCLOCK + - ๐ # U+1F557 CLOCK FACE EIGHT OCLOCK + - ๐ # U+1F558 CLOCK FACE NINE OCLOCK + - ๐ # U+1F559 CLOCK FACE TEN OCLOCK + - ๐ # U+1F55A CLOCK FACE ELEVEN OCLOCK + - ๐ # U+1F55B CLOCK FACE TWELVE OCLOCK + - ๐ # U+1F55C CLOCK FACE ONE-THIRTY + - ๐ # U+1F55D CLOCK FACE TWO-THIRTY + - ๐ # U+1F55E CLOCK FACE THREE-THIRTY + - ๐ # U+1F55F CLOCK FACE FOUR-THIRTY + - ๐ # U+1F560 CLOCK FACE FIVE-THIRTY + - ๐ก # U+1F561 CLOCK FACE SIX-THIRTY + - ๐ข # U+1F562 CLOCK FACE SEVEN-THIRTY + - ๐ฃ # U+1F563 CLOCK FACE EIGHT-THIRTY + - ๐ค # U+1F564 CLOCK FACE NINE-THIRTY + - ๐ฅ # U+1F565 CLOCK FACE TEN-THIRTY + - ๐ฆ # U+1F566 CLOCK FACE ELEVEN-THIRTY + - ๐ง # U+1F567 CLOCK FACE TWELVE-THIRTY + Computer symbols: + - ๐ฅ # U+1F5A5 DESKTOP COMPUTER + - ๐จ # U+1F5A8 PRINTER + - ๐ฑ # U+1F5B1 THREE BUTTON MOUSE + - ๐ฒ # U+1F5B2 TRACKBALL + Rating symbols: + - ๐ก # U+1F5E1 DAGGER KNIFE + - ๐ฃ # U+1F5E3 SPEAKING HEAD IN SILHOUETTE + Bubble symbols: + - ๐จ # U+1F5E8 LEFT SPEECH BUBBLE + - ๐ฏ # U+1F5EF RIGHT ANGER BUBBLE + Ballot symbols: + - ๐ณ # U+1F5F3 BALLOT BOX WITH BALLOT + Map symbol: + - ๐บ # U+1F5FA WORLD MAP + Cultural symbols: + - ๐ป # U+1F5FB MOUNT FUJI + - ๐ผ # U+1F5FC TOKYO TOWER + - ๐ฝ # U+1F5FD STATUE OF LIBERTY + - ๐พ # U+1F5FE SILHOUETTE OF JAPAN + - ๐ฟ # U+1F5FF MOYAI + Emoticons: + Faces: + - ๐ # U+1F600 GRINNING FACE + - ๐ # U+1F601 GRINNING FACE WITH SMILING EYES + - ๐ # U+1F602 FACE WITH TEARS OF JOY + - ๐ # U+1F603 SMILING FACE WITH OPEN MOUTH + - ๐ # U+1F604 SMILING FACE WITH OPEN MOUTH AND SMILING EYES + - ๐
# U+1F605 SMILING FACE WITH OPEN MOUTH AND COLD SWEAT + - ๐ # U+1F606 SMILING FACE WITH OPEN MOUTH AND TIGHTLY-CLOSED EYES + - ๐ # U+1F607 SMILING FACE WITH HALO + - ๐ # U+1F608 SMILING FACE WITH HORNS + - ๐ # U+1F609 WINKING FACE + - ๐ # U+1F60A SMILING FACE WITH SMILING EYES + - ๐ # U+1F60B FACE SAVOURING DELICIOUS FOOD + - ๐ # U+1F60C RELIEVED FACE + - ๐ # U+1F60D SMILING FACE WITH HEART-SHAPED EYES + - ๐ # U+1F60E SMILING FACE WITH SUNGLASSES + - ๐ # U+1F60F SMIRKING FACE + - ๐ # U+1F610 NEUTRAL FACE + - ๐ # U+1F611 EXPRESSIONLESS FACE + - ๐ # U+1F612 UNAMUSED FACE + - ๐ # U+1F613 FACE WITH COLD SWEAT + - ๐ # U+1F614 PENSIVE FACE + - ๐ # U+1F615 CONFUSED FACE + - ๐ # U+1F616 CONFOUNDED FACE + - ๐ # U+1F617 KISSING FACE + - ๐ # U+1F618 FACE THROWING A KISS + - ๐ # U+1F619 KISSING FACE WITH SMILING EYES + - ๐ # U+1F61A KISSING FACE WITH CLOSED EYES + - ๐ # U+1F61B FACE WITH STUCK-OUT TONGUE + - ๐ # U+1F61C FACE WITH STUCK-OUT TONGUE AND WINKING EYE + - ๐ # U+1F61D FACE WITH STUCK-OUT TONGUE AND TIGHTLY-CLOSED EYES + - ๐ # U+1F61E DISAPPOINTED FACE + - ๐ # U+1F61F WORRIED FACE + - ๐ # U+1F620 ANGRY FACE + - ๐ก # U+1F621 POUTING FACE + - ๐ข # U+1F622 CRYING FACE + - ๐ฃ # U+1F623 PERSEVERING FACE + - ๐ค # U+1F624 FACE WITH LOOK OF TRIUMPH + - ๐ฅ # U+1F625 DISAPPOINTED BUT RELIEVED FACE + - ๐ฆ # U+1F626 FROWNING FACE WITH OPEN MOUTH + - ๐ง # U+1F627 ANGUISHED FACE + - ๐จ # U+1F628 FEARFUL FACE + - ๐ฉ # U+1F629 WEARY FACE + - ๐ช # U+1F62A SLEEPY FACE + - ๐ซ # U+1F62B TIRED FACE + - ๐ฌ # U+1F62C GRIMACING FACE + - ๐ญ # U+1F62D LOUDLY CRYING FACE + - ๐ฎ # U+1F62E FACE WITH OPEN MOUTH + - ๐ฏ # U+1F62F HUSHED FACE + - ๐ฐ # U+1F630 FACE WITH OPEN MOUTH AND COLD SWEAT + - ๐ฑ # U+1F631 FACE SCREAMING IN FEAR + - ๐ฒ # U+1F632 ASTONISHED FACE + - ๐ณ # U+1F633 FLUSHED FACE + - ๐ด # U+1F634 SLEEPING FACE + - ๐ต # U+1F635 DIZZY FACE + - ๐ถ # U+1F636 FACE WITHOUT MOUTH + - ๐ท # U+1F637 FACE WITH MEDICAL MASK + - ๐ # U+1F641 SLIGHTLY FROWNING FACE + - ๐ # U+1F642 SLIGHTLY SMILING FACE + - ๐ # U+1F643 UPSIDE-DOWN FACE + - ๐ # U+1F644 FACE WITH ROLLING EYES + Cat faces: + - ๐ธ # U+1F638 GRINNING CAT FACE WITH SMILING EYES + - ๐น # U+1F639 CAT FACE WITH TEARS OF JOY + - ๐บ # U+1F63A SMILING CAT FACE WITH OPEN MOUTH + - ๐ป # U+1F63B SMILING CAT FACE WITH HEART-SHAPED EYES + - ๐ผ # U+1F63C CAT FACE WITH WRY SMILE + - ๐ฝ # U+1F63D KISSING CAT FACE WITH CLOSED EYES + - ๐พ # U+1F63E POUTING CAT FACE + - ๐ฟ # U+1F63F CRYING CAT FACE + - ๐ # U+1F640 WEARY CAT FACE + Gesture symbols: + - ๐
# U+1F645 FACE WITH NO GOOD GESTURE + - ๐ # U+1F646 FACE WITH OK GESTURE + - ๐ # U+1F647 PERSON BOWING DEEPLY + - ๐ # U+1F648 SEE-NO-EVIL MONKEY + - ๐ # U+1F649 HEAR-NO-EVIL MONKEY + - ๐ # U+1F64A SPEAK-NO-EVIL MONKEY + - ๐ # U+1F64B HAPPY PERSON RAISING ONE HAND + - ๐ # U+1F64C PERSON RAISING BOTH HANDS IN CELEBRATION + - ๐ # U+1F64D PERSON FROWNING + - ๐ # U+1F64E PERSON WITH POUTING FACE + - ๐ # U+1F64F PERSON WITH FOLDED HANDS + Transport And Map Symbols: + Vehicles: + - ๐ # U+1F680 ROCKET + - ๐ # U+1F681 HELICOPTER + - ๐ # U+1F682 STEAM LOCOMOTIVE + - ๐ # U+1F683 RAILWAY CAR + - ๐ # U+1F684 HIGH-SPEED TRAIN + - ๐
# U+1F685 HIGH-SPEED TRAIN WITH BULLET NOSE + - ๐ # U+1F686 TRAIN + - ๐ # U+1F687 METRO + - ๐ # U+1F688 LIGHT RAIL + - ๐ # U+1F689 STATION + - ๐ # U+1F68A TRAM + - ๐ # U+1F68B TRAM CAR + - ๐ # U+1F68C BUS + - ๐ # U+1F68D ONCOMING BUS + - ๐ # U+1F68E TROLLEYBUS + - ๐ # U+1F68F BUS STOP + - ๐ # U+1F690 MINIBUS + - ๐ # U+1F691 AMBULANCE + - ๐ # U+1F692 FIRE ENGINE + - ๐ # U+1F693 POLICE CAR + - ๐ # U+1F694 ONCOMING POLICE CAR + - ๐ # U+1F695 TAXI + - ๐ # U+1F696 ONCOMING TAXI + - ๐ # U+1F697 AUTOMOBILE + - ๐ # U+1F698 ONCOMING AUTOMOBILE + - ๐ # U+1F699 RECREATIONAL VEHICLE + - ๐ # U+1F69A DELIVERY TRUCK + - ๐ # U+1F69B ARTICULATED LORRY + - ๐ # U+1F69C TRACTOR + - ๐ # U+1F69D MONORAIL + - ๐ # U+1F69E MOUNTAIN RAILWAY + - ๐ # U+1F69F SUSPENSION RAILWAY + - ๐ # U+1F6A0 MOUNTAIN CABLEWAY + - ๐ก # U+1F6A1 AERIAL TRAMWAY + - ๐ข # U+1F6A2 SHIP + - ๐ฃ # U+1F6A3 ROWBOAT + - ๐ค # U+1F6A4 SPEEDBOAT + - ๐ฅ # U+1F6E5 MOTOR BOAT + - ๐ฉ # U+1F6E9 SMALL AIRPLANE + - ๐ซ # U+1F6EB AIRPLANE DEPARTURE + - ๐ฌ # U+1F6EC AIRPLANE ARRIVING + - ๐ฐ # U+1F6F0 SATELLITE + - ๐ณ # U+1F6F3 PASSENGER SHIP + - ๐ด # U+1F6F4 SCOOTER + - ๐ต # U+1F6F5 MOTOR SCOOTER + - ๐ถ # U+1F6F6 CANOE + - ๐ท # U+1F6F7 SLED + - ๐ธ # U+1F6F8 FLYING SAUCER + Traffic signs: + - ๐ฅ # U+1F6A5 HORIZONTAL TRAFFIC LIGHT + - ๐ฆ # U+1F6A6 VERTICAL TRAFFIC LIGHT + - ๐ง # U+1F6A7 CONSTRUCTION SIGN + - ๐จ # U+1F6A8 POLICE CARS REVOLVING LIGHT + Signage and other symbols: + - ๐ฉ # U+1F6A9 TRIANGULAR FLAG ON POST + - ๐ช # U+1F6AA DOOR + - ๐ซ # U+1F6AB NO ENTRY SIGN + - ๐ฌ # U+1F6AC SMOKING SYMBOL + - ๐ญ # U+1F6AD NO SMOKING SYMBOL + - ๐ฎ # U+1F6AE PUT LITTER IN ITS PLACE SYMBOL + - ๐ฏ # U+1F6AF DO NOT LITTER SYMBOL + - ๐ฐ # U+1F6B0 POTABLE WATER SYMBOL + - ๐ฑ # U+1F6B1 NON-POTABLE WATER SYMBOL + - ๐ฒ # U+1F6B2 BICYCLE + - ๐ณ # U+1F6B3 NO BICYCLES + - ๐ด # U+1F6B4 BICYCLIST + - ๐ต # U+1F6B5 MOUNTAIN BICYCLIST + - ๐ถ # U+1F6B6 PEDESTRIAN + - ๐ท # U+1F6B7 NO PEDESTRIANS + - ๐ธ # U+1F6B8 CHILDREN CROSSING + - ๐น # U+1F6B9 MENS SYMBOL + - ๐บ # U+1F6BA WOMENS SYMBOL + - ๐ป # U+1F6BB RESTROOM + - ๐ผ # U+1F6BC BABY SYMBOL + - ๐ฝ # U+1F6BD TOILET + - ๐พ # U+1F6BE WATER CLOSET + - ๐ฟ # U+1F6BF SHOWER + - ๐ # U+1F6C0 BATH + - ๐ # U+1F6C1 BATHTUB + - ๐ # U+1F6C2 PASSPORT CONTROL + - ๐ # U+1F6C3 CUSTOMS + - ๐ # U+1F6C4 BAGGAGE CLAIM + - ๐
# U+1F6C5 LEFT LUGGAGE + - ๐ # U+1F6D0 PLACE OF WORSHIP + - ๐ # U+1F6D1 OCTAGONAL SIGN + - ๐ # U+1F6D2 SHOPPING TROLLEY + Accommodation symbol: + - ๐ # U+1F6CB COUCH AND LAMP + - ๐ # U+1F6CC SLEEPING ACCOMMODATION + - ๐ # U+1F6CD SHOPPING BAGS + - ๐ # U+1F6CE BELLHOP BELL + - ๐ # U+1F6CF BED + Miscellaneous mark: + - ๐ # U+1F6E0 HAMMER AND WRENCH + - ๐ก # U+1F6E1 SHIELD + - ๐ข # U+1F6E2 OIL DRUM + - ๐ฃ # U+1F6E3 MOTORWAY + - ๐ค # U+1F6E4 RAILWAY TRACK + Supplemental Symbols And Pictographs: + Emoticon faces: + - ๐ค # U+1F910 ZIPPER-MOUTH FACE + - ๐ค # U+1F911 MONEY-MOUTH FACE + - ๐ค # U+1F912 FACE WITH THERMOMETER + - ๐ค # U+1F913 NERD FACE + - ๐ค # U+1F914 THINKING FACE + - ๐ค # U+1F915 FACE WITH HEAD-BANDAGE + - ๐ค # U+1F916 ROBOT FACE + - ๐ค # U+1F917 HUGGING FACE + - ๐ค # U+1F920 FACE WITH COWBOY HAT + - ๐คก # U+1F921 CLOWN FACE + - ๐คข # U+1F922 NAUSEATED FACE + - ๐คฃ # U+1F923 ROLLING ON THE FLOOR LAUGHING + - ๐คค # U+1F924 DROOLING FACE + - ๐คฅ # U+1F925 LYING FACE + - ๐คฆ # U+1F926 FACE PALM + - ๐คง # U+1F927 SNEEZING FACE + - ๐คจ # U+1F928 FACE WITH ONE EYEBROW RAISED + - ๐คฉ # U+1F929 GRINNING FACE WITH STAR EYES + - ๐คช # U+1F92A GRINNING FACE WITH ONE LARGE AND ONE SMALL EYE + - ๐คซ # U+1F92B FACE WITH FINGER COVERING CLOSED LIPS + - ๐คฌ # U+1F92C SERIOUS FACE WITH SYMBOLS COVERING MOUTH + - ๐คญ # U+1F92D SMILING FACE WITH SMILING EYES AND HAND COVERING MOUTH + - ๐คฎ # U+1F92E FACE WITH OPEN MOUTH VOMITING + - ๐คฏ # U+1F92F SHOCKED FACE WITH EXPLODING HEAD + Hand symbols: + - ๐ค # U+1F918 SIGN OF THE HORNS + - ๐ค # U+1F919 CALL ME HAND + - ๐ค # U+1F91A RAISED BACK OF HAND + - ๐ค # U+1F91B LEFT-FACING FIST + - ๐ค # U+1F91C RIGHT-FACING FIST + - ๐ค # U+1F91D HANDSHAKE + - ๐ค # U+1F91E HAND WITH INDEX AND MIDDLE FINGERS CROSSED + - ๐ค # U+1F91F I LOVE YOU HAND SIGN + Portrait and role symbols: + - ๐คฐ # U+1F930 PREGNANT WOMAN + - ๐คฑ # U+1F931 BREAST-FEEDING + - ๐คฒ # U+1F932 PALMS UP TOGETHER + - ๐คณ # U+1F933 SELFIE + - ๐คด # U+1F934 PRINCE + - ๐คต # U+1F935 MAN IN TUXEDO + - ๐คถ # U+1F936 MOTHER CHRISTMAS + - ๐คท # U+1F937 SHRUG + - ๐คธ # U+1F938 PERSON DOING CARTWHEEL + - ๐คน # U+1F939 JUGGLING + - ๐คบ # U+1F93A FENCER + - ๐คผ # U+1F93C WRESTLERS + - ๐คฝ # U+1F93D WATER POLO + - ๐คพ # U+1F93E HANDBALL + - ๐ง # U+1F9D0 FACE WITH MONOCLE + - ๐ง # U+1F9D1 ADULT + - ๐ง # U+1F9D2 CHILD + - ๐ง # U+1F9D3 OLDER ADULT + - ๐ง # U+1F9D4 BEARDED PERSON + - ๐ง # U+1F9D5 PERSON WITH HEADSCARF + - ๐ง # U+1F9D6 PERSON IN STEAMY ROOM + - ๐ง # U+1F9D7 PERSON CLIMBING + - ๐ง # U+1F9D8 PERSON IN LOTUS POSITION + - ๐ง # U+1F9D9 MAGE + - ๐ง # U+1F9DA FAIRY + - ๐ง # U+1F9DB VAMPIRE + - ๐ง # U+1F9DC MERPERSON + - ๐ง # U+1F9DD ELF + - ๐ง # U+1F9DE GENIE + - ๐ง # U+1F9DF ZOMBIE + Miscellaneous mark: + - ๐ฅ # U+1F940 WILTED FLOWER + - ๐ฅ # U+1F941 DRUM WITH DRUMSTICKS + - ๐ฅ # U+1F942 CLINKING GLASSES + - ๐ฅ # U+1F943 TUMBLER GLASS + - ๐ฅ # U+1F944 SPOON + - ๐ฅ
# U+1F945 GOAL NET + - ๐ฅ # U+1F947 FIRST PLACE MEDAL + - ๐ฅ # U+1F948 SECOND PLACE MEDAL + - ๐ฅ # U+1F949 THIRD PLACE MEDAL + - ๐ฅ # U+1F94A BOXING GLOVE + - ๐ฅ # U+1F94B MARTIAL ARTS UNIFORM + - ๐ฅ # U+1F94C CURLING STONE + - ๐ง # U+1F9E0 BRAIN + - ๐งก # U+1F9E1 ORANGE HEART + - ๐งข # U+1F9E2 BILLED CAP + - ๐งฃ # U+1F9E3 SCARF + - ๐งค # U+1F9E4 GLOVES + - ๐งฅ # U+1F9E5 COAT + - ๐งฆ # U+1F9E6 SOCKS + Food symbol: + - ๐ฅ # U+1F950 CROISSANT + - ๐ฅ # U+1F951 AVOCADO + - ๐ฅ # U+1F952 CUCUMBER + - ๐ฅ # U+1F953 BACON + - ๐ฅ # U+1F954 POTATO + - ๐ฅ # U+1F955 CARROT + - ๐ฅ # U+1F956 BAGUETTE BREAD + - ๐ฅ # U+1F957 GREEN SALAD + - ๐ฅ # U+1F958 SHALLOW PAN OF FOOD + - ๐ฅ # U+1F959 STUFFED FLATBREAD + - ๐ฅ # U+1F95A EGG + - ๐ฅ # U+1F95B GLASS OF MILK + - ๐ฅ # U+1F95C PEANUTS + - ๐ฅ # U+1F95D KIWIFRUIT + - ๐ฅ # U+1F95E PANCAKES + - ๐ฅ # U+1F95F DUMPLING + - ๐ฅ # U+1F960 FORTUNE COOKIE + - ๐ฅก # U+1F961 TAKEOUT BOX + - ๐ฅข # U+1F962 CHOPSTICKS + - ๐ฅฃ # U+1F963 BOWL WITH SPOON + - ๐ฅค # U+1F964 CUP WITH STRAW + - ๐ฅฅ # U+1F965 COCONUT + - ๐ฅฆ # U+1F966 BROCCOLI + - ๐ฅง # U+1F967 PIE + - ๐ฅจ # U+1F968 PRETZEL + - ๐ฅฉ # U+1F969 CUT OF MEAT + - ๐ฅช # U+1F96A SANDWICH + - ๐ฅซ # U+1F96B CANNED FOOD + - ๐ง # U+1F9C0 CHEESE WEDGE + Animal symbols: + - ๐ฆ # U+1F980 CRAB + - ๐ฆ # U+1F981 LION FACE + - ๐ฆ # U+1F982 SCORPION + - ๐ฆ # U+1F983 TURKEY + - ๐ฆ # U+1F984 UNICORN FACE + - ๐ฆ
# U+1F985 EAGLE + - ๐ฆ # U+1F986 DUCK + - ๐ฆ # U+1F987 BAT + - ๐ฆ # U+1F988 SHARK + - ๐ฆ # U+1F989 OWL + - ๐ฆ # U+1F98A FOX FACE + - ๐ฆ # U+1F98B BUTTERFLY + - ๐ฆ # U+1F98C DEER + - ๐ฆ # U+1F98D GORILLA + - ๐ฆ # U+1F98E LIZARD + - ๐ฆ # U+1F98F RHINOCEROS + - ๐ฆ # U+1F990 SHRIMP + - ๐ฆ # U+1F991 SQUID + - ๐ฆ # U+1F992 GIRAFFE FACE + - ๐ฆ # U+1F993 ZEBRA FACE + - ๐ฆ # U+1F994 HEDGEHOG + - ๐ฆ # U+1F995 SAUROPOD + - ๐ฆ # U+1F996 T-REX + - ๐ฆ # U+1F997 CRICKET diff --git a/src/test/resources/issues/issue307-order.yaml b/src/test/resources/issues/issue307-order.yaml new file mode 100644 index 00000000..cb024deb --- /dev/null +++ b/src/test/resources/issues/issue307-order.yaml @@ -0,0 +1,7 @@ +name: tian +type: + x: 254 + y: 255 + z: 256 +age: 22 +text: omit
\ No newline at end of file diff --git a/src/test/resources/issues/issue337-duplicate-keys-javabean-property.yaml b/src/test/resources/issues/issue337-duplicate-keys-javabean-property.yaml new file mode 100644 index 00000000..1cecad08 --- /dev/null +++ b/src/test/resources/issues/issue337-duplicate-keys-javabean-property.yaml @@ -0,0 +1,9 @@ +name: no-dup-keys +map: + someitem: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: aead4b16-4b61-4eff-b241-6eff26eaa778 + url: http://test.com/sample/v1/foobar + someitem1: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: daaf8911-36e4-4e92-86ea-eb77ac2c1e91 + url: http://test.com/sample/v55/foobar +name: has-dup-keys
\ No newline at end of file diff --git a/src/test/resources/issues/issue337-duplicate-keys-no-dups.yaml b/src/test/resources/issues/issue337-duplicate-keys-no-dups.yaml new file mode 100644 index 00000000..52717ab3 --- /dev/null +++ b/src/test/resources/issues/issue337-duplicate-keys-no-dups.yaml @@ -0,0 +1,11 @@ +name: no-dups-test +map: + someitem1: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: aead4b16-4b61-4eff-b241-6eff26eaa778 + url: http://test.com/sample/v1/foobar + someitem2: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: d8118e55-28a5-4674-addf-0d1d847e68f6 + url: http://test.com/sample/v77/foobar + someitem3: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: daaf8911-36e4-4e92-86ea-eb77ac2c1e91 + url: http://test.com/sample/v55/foobar diff --git a/src/test/resources/issues/issue337-duplicate-keys.yaml b/src/test/resources/issues/issue337-duplicate-keys.yaml new file mode 100644 index 00000000..58cd2361 --- /dev/null +++ b/src/test/resources/issues/issue337-duplicate-keys.yaml @@ -0,0 +1,11 @@ +name: has-dup-keys +map: + someitem: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: aead4b16-4b61-4eff-b241-6eff26eaa778 + url: http://test.com/sample/v1/foobar + someitem: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: d8118e55-28a5-4674-addf-0d1d847e68f6 + url: http://test.com/sample/v77/foobar + someitem: !!org.yaml.snakeyaml.issues.issue337.DuplicateKeyTest$FooEntry + id: daaf8911-36e4-4e92-86ea-eb77ac2c1e91 + url: http://test.com/sample/v55/foobar diff --git a/src/test/resources/issues/issue348.yaml b/src/test/resources/issues/issue348.yaml new file mode 100644 index 00000000..750452d9 --- /dev/null +++ b/src/test/resources/issues/issue348.yaml @@ -0,0 +1,6 @@ +foo: + - &foo !!org.yaml.snakeyaml.issues.issue348.model.Foo ["foo"] +bar: + - &bar !!org.yaml.snakeyaml.issues.issue348.model.Bar [*foo] +baz: + - &baz !!org.yaml.snakeyaml.issues.issue348.model.Baz [*bar] diff --git a/src/test/resources/issues/issue349-1.yaml b/src/test/resources/issues/issue349-1.yaml new file mode 100644 index 00000000..06d099cf --- /dev/null +++ b/src/test/resources/issues/issue349-1.yaml @@ -0,0 +1,8 @@ +--- +picture: !!binary + "R0lGODlhDAAMAIQAAP//9/X\ + 17unp5WZmZgAAAOfn515eXv\ + Pz7Y6OjuDg4J+fn5OTk6enp\ + 56enmleECcgggoBADs=" + + diff --git a/src/test/resources/issues/issue349-2.yaml b/src/test/resources/issues/issue349-2.yaml new file mode 100644 index 00000000..551f79b1 --- /dev/null +++ b/src/test/resources/issues/issue349-2.yaml @@ -0,0 +1,6 @@ +--- +picture: !!binary + R0lGODlhDAAMAIQAAP//9/X + 17unp5WZmZgAAAOfn515eXv + Pz7Y6OjuDg4J+fn5OTk6enp + 56enmleECcgggoBADs= diff --git a/src/test/resources/issues/issue349-3.yaml b/src/test/resources/issues/issue349-3.yaml new file mode 100644 index 00000000..7c8ed72d --- /dev/null +++ b/src/test/resources/issues/issue349-3.yaml @@ -0,0 +1,6 @@ +--- +picture: !!binary | + R0lGODlhDAAMAIQAAP//9/X + 17unp5WZmZgAAAOfn515eXv + Pz7Y6OjuDg4J+fn5OTk6enp + 56enmleECcgggoBADs= diff --git a/src/test/resources/issues/issue351_1.yaml b/src/test/resources/issues/issue351_1.yaml new file mode 100644 index 00000000..cda81060 --- /dev/null +++ b/src/test/resources/issues/issue351_1.yaml @@ -0,0 +1,6 @@ +prize_cashBack_fixture: &cashBackPrize + "[prizes][0][bonusPrize]": "9" + "[prizes][0][options][19][value]": "25" + "[prizes][0][options][20][value]": "3" +prize_cashBack_sendEmail_fixture: + <<: *cashBackPrize diff --git a/src/test/resources/issues/issue354.yaml b/src/test/resources/issues/issue354.yaml new file mode 100644 index 00000000..e9c480d0 --- /dev/null +++ b/src/test/resources/issues/issue354.yaml @@ -0,0 +1,7 @@ +foo: | + This is + `a literal + +bar: | + And + @this
\ No newline at end of file diff --git a/src/test/resources/issues/issue386-duplicate-keys-order.yaml b/src/test/resources/issues/issue386-duplicate-keys-order.yaml new file mode 100644 index 00000000..b646edf3 --- /dev/null +++ b/src/test/resources/issues/issue386-duplicate-keys-order.yaml @@ -0,0 +1,8 @@ +key1: "1st-1" +key2: "2nd-1" +lostone: "Not meeee!!!" +key3: "3rd-1" +key2: "2nd-2" +key3: "3rd-2" +key1: "1st-2" +key3: "3rd-3"
\ No newline at end of file diff --git a/src/test/resources/issues/issue416-1.yaml b/src/test/resources/issues/issue416-1.yaml new file mode 100644 index 00000000..44142eed --- /dev/null +++ b/src/test/resources/issues/issue416-1.yaml @@ -0,0 +1,8 @@ +company:
+ developers:
+ - name: Fred
+ role: creator
+ - name: John
+ role: committer
+ name: Yet Another Company
+ location: Maastricht
diff --git a/src/test/resources/issues/issue416-2.yaml b/src/test/resources/issues/issue416-2.yaml new file mode 100644 index 00000000..430e4b91 --- /dev/null +++ b/src/test/resources/issues/issue416-2.yaml @@ -0,0 +1,8 @@ +company:
+ developers:
+ - name: Fred
+ role: creator
+ - name: John
+ role: committer
+ name: Yet Another Company
+ location: Maastricht
diff --git a/src/test/resources/issues/issue416_3.yml b/src/test/resources/issues/issue416_3.yml new file mode 100644 index 00000000..ac96da0f --- /dev/null +++ b/src/test/resources/issues/issue416_3.yml @@ -0,0 +1,8 @@ +company: + developers: + - name: Fred + role: creator + - name: John + role: committer + name: Yet Another Company + location: Maastricht
\ No newline at end of file diff --git a/src/test/resources/issues/issue479-1.yaml b/src/test/resources/issues/issue479-1.yaml new file mode 100644 index 00000000..e3f79c9b --- /dev/null +++ b/src/test/resources/issues/issue479-1.yaml @@ -0,0 +1,22 @@ +.default: &default + test1: 1 + mysql: &mysql_default + db_host: mysql.avatar2.test + db_port: 3306 + db_user: &mysql_default_user default + db_password: &mysql_default_password secret + redis: &redis_default + cluster: + node: + - host: rediscluster.avatar2.test + port: 7000 + - host: rediscluster.avatar2.test + port: 7001 + +system: + erp: + <<: *default + test1: 2 + mysql: + <<: *mysql_default + db_name: erp diff --git a/src/test/resources/issues/issue479-output.yaml b/src/test/resources/issues/issue479-output.yaml new file mode 100644 index 00000000..0452e4b2 --- /dev/null +++ b/src/test/resources/issues/issue479-output.yaml @@ -0,0 +1,13 @@ +.default: + test1: 1 + mysql: {db_host: mysql.avatar2.test, db_port: 3306, db_user: default, db_password: secret} + redis: &id001 + cluster: + node: + - {host: rediscluster.avatar2.test, port: 7000} + - {host: rediscluster.avatar2.test, port: 7001} +system: + erp: + test1: 2 + mysql: {db_name: erp} + redis: *id001 diff --git a/src/test/resources/issues/issue479.yaml b/src/test/resources/issues/issue479.yaml new file mode 100644 index 00000000..52463d9e --- /dev/null +++ b/src/test/resources/issues/issue479.yaml @@ -0,0 +1,21 @@ +.default: &default + test1: 1 + mysql: &mysql_default + db_host: mysql.avatar2.test + db_port: 3306 + db_user: &mysql_default_user default + db_password: &mysql_default_password secret + redis: &redis_default + cluster: + node: + - host: rediscluster.avatar2.test + port: 7000 + - host: rediscluster.avatar2.test + port: 7001 + +system: + erp: + <<: *default + test1: 2 + mysql: + db_name: erp diff --git a/src/test/resources/issues/issue481.yaml b/src/test/resources/issues/issue481.yaml new file mode 100644 index 00000000..c5b0ddf5 --- /dev/null +++ b/src/test/resources/issues/issue481.yaml @@ -0,0 +1,17 @@ +defines: + serverPattern1: &server_HighPerformance + type: t3 + strage: 500 + serverPattern2: &server_LowPerformance + type: t2 + strage: 250 + lbPattern1: &lb_Public + name: lbForPublic + vpc: vpc1 + lbPattern2: &lb_Internal + name: lbForInternal + vpc: vpc1 +current: + assenbled1: + server: *server_HighPerformance + lb: *lb_Public diff --git a/src/test/resources/issues/issue512.yaml b/src/test/resources/issues/issue512.yaml new file mode 100644 index 00000000..e7cc5f1a --- /dev/null +++ b/src/test/resources/issues/issue512.yaml @@ -0,0 +1,7 @@ +# on list +[ + # first + 'first entry', + # second + 'second entry' +]
\ No newline at end of file diff --git a/src/test/resources/pyyaml/invalid-anchor-1.loader-error b/src/test/resources/pyyaml/invalid-anchor-1.loader-error index fcf7d0f6..c3cf3433 100644 --- a/src/test/resources/pyyaml/invalid-anchor-1.loader-error +++ b/src/test/resources/pyyaml/invalid-anchor-1.loader-error @@ -1 +1 @@ ---- &? foo # we allow only ascii and numeric characters in anchor names. +--- &[ foo # we do not allow special characters in anchor names - YAML 1.2 diff --git a/src/test/resources/representer/scalar-style1.yaml b/src/test/resources/representer/scalar-style1.yaml index a1c68425..5eeee0ce 100644 --- a/src/test/resources/representer/scalar-style1.yaml +++ b/src/test/resources/representer/scalar-style1.yaml @@ -3,4 +3,7 @@ address: |- Name Street Number Country -description: 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 0000000000 +description: 1111111111 2222222222 + 3333333333 4444444444 5555555555 + 6666666666 7777777777 8888888888 + 9999999999 0000000000 |