groovy-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From sun...@apache.org
Subject groovy git commit: GROOVY-8794: Add groovy-yaml subproject to support parsing and building yaml(closes #797)
Date Fri, 21 Sep 2018 21:00:02 GMT
Repository: groovy
Updated Branches:
  refs/heads/master 5f156f2e8 -> 16b24b8c4


GROOVY-8794: Add groovy-yaml subproject to support parsing and building yaml(closes #797)


Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/16b24b8c
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/16b24b8c
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/16b24b8c

Branch: refs/heads/master
Commit: 16b24b8c4044b7aff2bc1451ffb76cfe94baff81
Parents: 5f156f2
Author: Daniel Sun <sunlan@apache.org>
Authored: Sat Sep 22 04:59:59 2018 +0800
Committer: Daniel Sun <sunlan@apache.org>
Committed: Sat Sep 22 04:59:59 2018 +0800

----------------------------------------------------------------------
 gradle/binarycompatibility.gradle               |   2 +-
 gradle/upload.gradle                            |   3 +-
 settings.gradle                                 |   1 +
 subprojects/groovy-yaml/build.gradle            |  31 ++
 .../src/main/java/groovy/yaml/YamlBuilder.java  | 301 +++++++++++++++++++
 .../java/groovy/yaml/YamlRuntimeException.java  |  40 +++
 .../src/main/java/groovy/yaml/YamlSlurper.java  |  59 ++++
 .../java/groovy/yaml/util/YamlConverter.java    |  66 ++++
 .../src/spec/doc/yaml-userguide.adoc            |  98 ++++++
 .../test/groovy/yaml/YamlBuilderTest.groovy     |  54 ++++
 .../spec/test/groovy/yaml/YamlParserTest.groovy |  79 +++++
 11 files changed, 732 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/gradle/binarycompatibility.gradle
----------------------------------------------------------------------
diff --git a/gradle/binarycompatibility.gradle b/gradle/binarycompatibility.gradle
index 45b951d..20a4ace 100644
--- a/gradle/binarycompatibility.gradle
+++ b/gradle/binarycompatibility.gradle
@@ -37,7 +37,7 @@ check.dependsOn(checkBinaryCompatibility)
 // for comparing between versions with different modules, set excludeModules to differing
modules, e.g.
 def excludeModules = [
         'groovy-cli-picocli', 'groovy-cli-commons', 'groovy-dateutil', 'groovy-datetime',
'groovy-jaxb',
-        'groovy-macro', 'groovy-json-direct', 'groovy-test-junit5', 'performance', 'tests-vm8'
+        'groovy-macro', 'groovy-json-direct', 'groovy-test-junit5', 'groovy-yaml', 'performance',
'tests-vm8'
 ]
 //def excludeModules = []
 

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/gradle/upload.gradle
----------------------------------------------------------------------
diff --git a/gradle/upload.gradle b/gradle/upload.gradle
index 30533f8..61bbeb1 100644
--- a/gradle/upload.gradle
+++ b/gradle/upload.gradle
@@ -205,7 +205,8 @@ def optionalModules = [
         'groovy-bsf',
         'groovy-cli-commons',
         'groovy-dateutil',
-        'groovy-jaxb'
+        'groovy-jaxb',
+        'groovy-yaml'
 ]
 
 ext.pomAll = {

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/settings.gradle
----------------------------------------------------------------------
diff --git a/settings.gradle b/settings.gradle
index 603370a..ca4cab3 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -40,6 +40,7 @@ def subprojects = ['groovy-ant',
         'groovy-testng',
         'groovy-xml',
         'groovy-macro',
+        'groovy-yaml',
         'performance'
 ]
 

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/build.gradle
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/build.gradle b/subprojects/groovy-yaml/build.gradle
new file mode 100644
index 0000000..ea24a4b
--- /dev/null
+++ b/subprojects/groovy-yaml/build.gradle
@@ -0,0 +1,31 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this 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.
+ */
+
+ext {
+    jacksondataformatyamlVersion = '2.9.6'
+    jacksondatabindVersion = '2.9.6'
+}
+
+dependencies {
+    compile rootProject
+    compile "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:$jacksondataformatyamlVersion"
+    compile "com.fasterxml.jackson.core:jackson-databind:$jacksondatabindVersion"
+    compile project(':groovy-json')
+    testCompile project(':groovy-test')
+}

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlBuilder.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlBuilder.java b/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlBuilder.java
new file mode 100644
index 0000000..ef9cf6a
--- /dev/null
+++ b/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlBuilder.java
@@ -0,0 +1,301 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this 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 groovy.yaml;
+
+import groovy.json.JsonBuilder;
+import groovy.lang.Closure;
+import groovy.lang.GroovyObjectSupport;
+import groovy.lang.Writable;
+import groovy.yaml.util.YamlConverter;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.Writer;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ *  A builder for creating YAML payloads.
+ *
+ *  @since 3.0.0
+ */
+public class YamlBuilder extends GroovyObjectSupport implements Writable {
+    private JsonBuilder jsonBuilder;
+
+    public YamlBuilder() {
+        this.jsonBuilder = new JsonBuilder();
+    }
+
+    public Object getContent() {
+        return jsonBuilder.getContent();
+    }
+
+    /**
+     * Named arguments can be passed to the YAML builder instance to create a root YAML object
+     * <p>
+     * Example:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * yaml name: "Guillaume", age: 33
+     *
+     * assert yaml.toString() == '''---
+     * name: "Guillaume"
+     * age: 33
+     * '''
+     * </code></pre>
+     *
+     * @param m a map of key / value pairs
+     * @return a map of key / value pairs
+     */
+    public Object call(Map m) {
+        return jsonBuilder.call(m);
+    }
+
+    /**
+     * A list of elements as arguments to the YAML builder creates a root YAML array
+     * <p>
+     * Example:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * def result = yaml([1, 2, 3])
+     *
+     * assert result instanceof List
+     * assert yaml.toString() == '''---
+     * - 1
+     * - 2
+     * - 3
+     * '''
+     * </code></pre>
+     *
+     * @param l a list of values
+     * @return a list of values
+     */
+    public Object call(List l) {
+        return jsonBuilder.call(l);
+    }
+
+    /**
+     * Varargs elements as arguments to the YAML builder create a root YAML array
+     * <p>
+     * Example:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * def result = yaml 1, 2, 3
+     *
+     * assert result instanceof List
+     * assert yaml.toString() == '''---
+     * - 1
+     * - 2
+     * - 3
+     * '''
+     * </code></pre>
+     *
+     * @param args an array of values
+     * @return a list of values
+     */
+    public Object call(Object... args) {
+        return jsonBuilder.call(args);
+    }
+
+    /**
+     * A collection and closure passed to a YAML builder will create a root YAML array applying
+     * the closure to each object in the collection
+     * <p>
+     * Example:
+     * <pre><code class="groovyTestCase">
+     * class Author {
+     *      String name
+     * }
+     * def authors = [new Author (name: "Guillaume"), new Author (name: "Jochen"), new Author
(name: "Paul")]
+     *
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * yaml authors, { Author author ->
+     *      name author.name
+     * }
+     *
+     * assert yaml.toString() == '''---
+     * - name: "Guillaume"
+     * - name: "Jochen"
+     * - name: "Paul"
+     * '''
+     * </code></pre>
+     * @param coll a collection
+     * @param c a closure used to convert the objects of coll
+     * @return a list of values
+     */
+    public Object call(Iterable coll, Closure c) {
+        return jsonBuilder.call(coll, c);
+    }
+
+    /**
+     * Delegates to {@link #call(Iterable, Closure)}
+     * @param coll
+     * @param c
+     */
+    public Object call(Collection coll, Closure c) {
+        return jsonBuilder.call(coll, c);
+    }
+
+    /**
+     * A closure passed to a YAML builder will create a root YAML object
+     * <p>
+     * Example:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * def result = yaml {
+     *      name "Guillaume"
+     *      age 33
+     * }
+     *
+     * assert result instanceof Map
+     * assert yaml.toString() == '''---
+     * name: "Guillaume"
+     * age: 33
+     * '''
+     * </code></pre>
+     *
+     * @param c a closure whose method call statements represent key / values of a YAML object
+     * @return a map of key / value pairs
+     */
+    public Object call(Closure c) {
+        return jsonBuilder.call(c);
+    }
+
+    /**
+     * A method call on the YAML builder instance will create a root object with only one
key
+     * whose name is the name of the method being called.
+     * This method takes as arguments:
+     * <ul>
+     *     <li>a closure</li>
+     *     <li>a map (ie. named arguments)</li>
+     *     <li>a map and a closure</li>
+     *     <li>or no argument at all</li>
+     * </ul>
+     * <p>
+     * Example with a classical builder-style:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * def result = yaml.person {
+     *      name "Guillaume"
+     *      age 33
+     * }
+     *
+     * assert result instanceof Map
+     * assert yaml.toString() == '''---
+     * person:
+     *   name: "Guillaume"
+     *   age: 33
+     * '''
+     * </code></pre>
+     *
+     * Or alternatively with a method call taking named arguments:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * yaml.person name: "Guillaume", age: 33
+     *
+     * assert yaml.toString() == '''---
+     * person:
+     *   name: "Guillaume"
+     *   age: 33
+     * '''
+     * </code></pre>
+     *
+     * If you use named arguments and a closure as last argument,
+     * the key/value pairs of the map (as named arguments)
+     * and the key/value pairs represented in the closure
+     * will be merged together &mdash;
+     * the closure properties overriding the map key/values
+     * in case the same key is used.
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * yaml.person(name: "Guillaume", age: 33) { town "Paris" }
+     *
+     * assert yaml.toString() == '''---
+     * person:
+     *   name: "Guillaume"
+     *   age: 33
+     *   town: "Paris"
+     * '''
+     * </code></pre>
+     *
+     * The empty args call will create a key whose value will be an empty YAML object:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * yaml.person()
+     *
+     * assert yaml.toString() == '''---
+     * person: {}
+     * '''
+     * </code></pre>
+     *
+     * @param name the single key
+     * @param args the value associated with the key
+     * @return a map with a single key
+     */
+    @Override
+    public Object invokeMethod(String name, Object args) {
+        return jsonBuilder.invokeMethod(name, args);
+    }
+
+    /**
+     * Serializes the internal data structure built with the builder to a conformant YAML
payload string
+     * <p>
+     * Example:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * yaml { temperature 37 }
+     *
+     * assert yaml.toString() == '''---
+     * temperature: 37
+     * '''
+     * </code></pre>
+     *
+     * @return a YAML output
+     */
+    @Override
+    public String toString() {
+        return YamlConverter.convertJsonToYaml(new StringReader(jsonBuilder.toString()));
+    }
+
+    /**
+     * The YAML builder implements the <code>Writable</code> interface,
+     * so that you can have the builder serialize itself the YAML payload to a writer.
+     * <p>
+     * Example:
+     * <pre><code class="groovyTestCase">
+     * def yaml = new groovy.yaml.YamlBuilder()
+     * yaml { temperature 37 }
+     *
+     * def out = new StringWriter()
+     * out << yaml
+     *
+     * assert out.toString() == '''---
+     * temperature: 37
+     * '''
+     * </code></pre>
+     *
+     * @param out a writer on which to serialize the YAML payload
+     * @return the writer
+     */
+    @Override
+    public Writer writeTo(Writer out) throws IOException {
+        return out.append(toString());
+    }
+}

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlRuntimeException.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlRuntimeException.java b/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlRuntimeException.java
new file mode 100644
index 0000000..9d31a0f
--- /dev/null
+++ b/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlRuntimeException.java
@@ -0,0 +1,40 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this 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 groovy.yaml;
+
+import groovy.lang.GroovyRuntimeException;
+
+/**
+ * Represents runtime exception occurred when parsing or building YAML
+ *
+ * @since 3.0.0
+ */
+public class YamlRuntimeException extends GroovyRuntimeException {
+    public YamlRuntimeException(String msg) {
+        super(msg);
+    }
+
+    public YamlRuntimeException(Throwable cause) {
+        super(cause);
+    }
+
+    public YamlRuntimeException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlSlurper.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlSlurper.java b/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlSlurper.java
new file mode 100644
index 0000000..057b94c
--- /dev/null
+++ b/subprojects/groovy-yaml/src/main/java/groovy/yaml/YamlSlurper.java
@@ -0,0 +1,59 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this 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 groovy.yaml;
+
+import groovy.json.JsonSlurper;
+import groovy.yaml.util.YamlConverter;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+
+/**
+ *  Represents a YAML parser
+ *
+ *  @since 3.0.0
+ */
+public class YamlSlurper {
+    private JsonSlurper jsonSlurper;
+
+    public YamlSlurper() {
+        this.jsonSlurper = new JsonSlurper();
+    }
+
+    /**
+     * Parse the content of the specified yaml into a tree of Nodes.
+     *
+     * @param yaml the content of yaml
+     * @return the root node of the parsed tree of Nodes
+     */
+    public Object parseText(String yaml) {
+        return this.parse(new StringReader(yaml));
+    }
+
+    /**
+     * Parse the content of the specified reader into a tree of Nodes.
+     *
+     * @param reader the reader of yaml
+     * @return the root node of the parsed tree of Nodes
+     */
+    public Object parse(Reader reader) {
+        return jsonSlurper.parse(new StringReader(YamlConverter.convertYamlToJson(reader)));
+    }
+}

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/src/main/java/groovy/yaml/util/YamlConverter.java
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/src/main/java/groovy/yaml/util/YamlConverter.java b/subprojects/groovy-yaml/src/main/java/groovy/yaml/util/YamlConverter.java
new file mode 100644
index 0000000..41192d2
--- /dev/null
+++ b/subprojects/groovy-yaml/src/main/java/groovy/yaml/util/YamlConverter.java
@@ -0,0 +1,66 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this 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 groovy.yaml.util;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
+import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
+import groovy.yaml.YamlRuntimeException;
+
+import java.io.IOException;
+import java.io.Reader;
+
+/**
+ *  A converter for converting YAML to JSON, vice versa
+ *  @since 3.0.0
+ */
+public class YamlConverter {
+    /**
+     * Convert yaml to json
+     * @param yamlReader the reader of yaml
+     * @return the text of json
+     */
+    public static String convertYamlToJson(Reader yamlReader) {
+        try (Reader reader = yamlReader) {
+            Object yaml = new ObjectMapper(new YAMLFactory()).readValue(reader, Object.class);
+
+            return new ObjectMapper().writeValueAsString(yaml);
+        } catch (IOException e) {
+            throw new YamlRuntimeException(e);
+        }
+    }
+
+    /**
+     * Convert json to yaml
+     * @param jsonReader the reader of json
+     * @return the text of yaml
+     */
+    public static String convertJsonToYaml(Reader jsonReader) {
+        try (Reader reader = jsonReader) {
+            JsonNode json = new ObjectMapper().readTree(reader);
+
+            return new YAMLMapper().writeValueAsString(json);
+        } catch (IOException e) {
+            throw new YamlRuntimeException(e);
+        }
+    }
+
+    private YamlConverter() {}
+}

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/src/spec/doc/yaml-userguide.adoc
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/src/spec/doc/yaml-userguide.adoc b/subprojects/groovy-yaml/src/spec/doc/yaml-userguide.adoc
new file mode 100644
index 0000000..586783d
--- /dev/null
+++ b/subprojects/groovy-yaml/src/spec/doc/yaml-userguide.adoc
@@ -0,0 +1,98 @@
+//////////////////////////////////////////
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this 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.
+
+//////////////////////////////////////////
+
+= Processing YAML
+
+Groovy has an optional `groovy-yaml` module which provides support for converting between
Groovy objects and YAML. The classes dedicated to
+YAML serialisation and parsing are found in the `groovy.yaml` package.
+
+[[yaml_yamlslurper]]
+== YamlSlurper
+
+`YamlSlurper` is a class that parses YAML text or reader content into Groovy data structures
(objects) such as maps, lists and
+primitive types like `Integer`, `Double`, `Boolean` and `String`.
+
+The class comes with a bunch of overloaded `parse` methods plus some special methods such
as `parseText`
+and others. For the next example we will use the `parseText` method. It parses a YAML `String`
and recursively converts it to a
+list or map of objects. The other `parse*` methods are similar in that they return a YAML
`String` but for different parameter
+types.
+
+[source,groovy]
+----
+include::{rootProjectDir}/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlParserTest.groovy[tags=parse_text,indent=0]
+----
+
+Notice the result is a plain map and can be handled like a normal Groovy object instance.
`YamlSlurper` parses the
+given YAML as defined by the http://yaml.org/spec/1.2/spec.html[YAML Ain’t Markup Language
(YAML™)].
+
+
+As `YamlSlurper` is returning pure Groovy object instances without any special YAML classes
in the back, its usage
+is transparent. In fact, `YamlSlurper` results conform to GPath expressions. GPath is a powerful
expression language
+that is supported by multiple slurpers for different data formats (`XmlSlurper` for XML being
one example).
+
+[NOTE]
+For more details please have a look at the section on <<core-semantics.adoc#gpath_expressions,GPath
expressions>>.
+
+The following table gives an overview of the YAML types and the corresponding Groovy data
types:
+
+[cols="1,3" options="header"]
+|===
+|YAML
+|Groovy
+
+|string
+|`java.lang.String`
+
+|number
+|`java.lang.BigDecimal` or `java.lang.Integer`
+
+|object
+|`java.util.LinkedHashMap`
+
+|array
+|`java.util.ArrayList`
+
+|true
+|`true`
+
+|false
+|`false`
+
+|null
+|`null`
+
+|date
+|`java.util.Date` based on the `yyyy-MM-dd'T'HH:mm:ssZ` date format
+|===
+
+[NOTE]
+Whenever a value in YAML is `null`, `YamlSlurper` supplements it with the Groovy `null` value.
This is in contrast to other
+YAML parsers that represent a `null` value with a library-provided singleton object.
+
+=== Builders
+
+Another way to create YAML from Groovy is to use `YamlBuilder`. The builder provide a
+DSL which allows to formulate an object graph which is then converted to YAML.
+
+[source,groovy]
+----
+include::{rootProjectDir}/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlBuilderTest.groovy[tags=build_text,indent=0]
+----

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlBuilderTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlBuilderTest.groovy b/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlBuilderTest.groovy
new file mode 100644
index 0000000..f590d6f
--- /dev/null
+++ b/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlBuilderTest.groovy
@@ -0,0 +1,54 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this 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 groovy.yaml
+
+class YamlBuilderTest extends GroovyTestCase {
+
+    void testBuild() {
+        // tag::build_text[]
+        def builder = new YamlBuilder()
+        builder.records {
+            car {
+                name 'HSV Maloo'
+                make 'Holden'
+                year 2006
+                country 'Australia'
+                homepage new URL('http://example.org')
+                record {
+                    type 'speed'
+                    description 'production pickup truck with speed of 271kph'
+                }
+            }
+        }
+
+        assert builder.toString() == '''---
+records:
+  car:
+    name: "HSV Maloo"
+    make: "Holden"
+    year: 2006
+    country: "Australia"
+    homepage: "http://example.org"
+    record:
+      type: "speed"
+      description: "production pickup truck with speed of 271kph"
+'''
+        // end::build_text[]
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/groovy/blob/16b24b8c/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlParserTest.groovy
----------------------------------------------------------------------
diff --git a/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlParserTest.groovy b/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlParserTest.groovy
new file mode 100644
index 0000000..74b6593
--- /dev/null
+++ b/subprojects/groovy-yaml/src/spec/test/groovy/yaml/YamlParserTest.groovy
@@ -0,0 +1,79 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this 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 groovy.yaml
+
+class YamlParserTest extends GroovyTestCase {
+
+    void testParse() {
+        // tag::parse_text[]
+        def ys = new YamlSlurper()
+        def yaml = ys.parseText '''
+language: groovy
+sudo: required
+dist: trusty
+
+matrix:
+  include:
+#    - jdk: oraclejdk11
+    - jdk: openjdk10
+    - jdk: oraclejdk9
+    - jdk: oraclejdk8
+
+before_script:
+  - |
+    unset _JAVA_OPTIONS
+
+        '''
+
+        assert 'groovy' == yaml.language
+        assert 'required' == yaml.sudo
+        assert 'trusty' == yaml.dist
+        assert ['openjdk10', 'oraclejdk9', 'oraclejdk8'] ==  yaml.matrix.include.jdk
+        assert ['unset _JAVA_OPTIONS'] == yaml.before_script*.trim()
+        // end::parse_text[]
+    }
+
+    void testBuildAndParse() {
+        def builder = new YamlBuilder()
+        builder.records {
+            car {
+                name 'HSV Maloo'
+                make 'Holden'
+                year 2006
+                country 'Australia'
+                homepage new URL('http://example.org')
+                record {
+                    type 'speed'
+                    description 'production pickup truck with speed of 271kph'
+                }
+            }
+        }
+
+        def ys = new YamlSlurper()
+        def yaml = ys.parseText(builder.toString())
+
+        assert 'HSV Maloo' == yaml.records.car.name
+        assert 'Holden' == yaml.records.car.make
+        assert 2006 == yaml.records.car.year
+        assert 'Australia' == yaml.records.car.country
+        assert 'http://example.org' == yaml.records.car.homepage
+        assert 'speed' == yaml.records.car.record.type
+        assert 'production pickup truck with speed of 271kph' == yaml.records.car.record.description
+    }
+}
\ No newline at end of file


Mime
View raw message