You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2017/09/24 18:34:24 UTC
[1/3] incubator-juneau git commit: YAML prototype.
Repository: incubator-juneau
Updated Branches:
refs/heads/master b89cb9823 -> ab8f0faaa
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/package.html
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/package.html b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/package.html
new file mode 100644
index 0000000..3c3e845
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/package.html
@@ -0,0 +1,1005 @@
+<!DOCTYPE HTML>
+<!--
+/***************************************************************************************************************************
+ * 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.
+ *
+ ***************************************************************************************************************************/
+ -->
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <style type="text/css">
+ /* For viewing in Page Designer */
+ @IMPORT url("../../../../../../javadoc.css");
+
+ /* For viewing in REST interface */
+ @IMPORT url("../htdocs/javadoc.css");
+ body {
+ margin: 20px;
+ }
+ </style>
+ <script>
+ /* Replace all @code and @link tags. */
+ window.onload = function() {
+ document.body.innerHTML = document.body.innerHTML.replace(/\{\@code ([^\}]+)\}/g, '<code>$1</code>');
+ document.body.innerHTML = document.body.innerHTML.replace(/\{\@link (([^\}]+)\.)?([^\.\}]+)\}/g, '<code>$3</code>');
+ }
+ </script>
+</head>
+<body>
+<p>JSON serialization and parsing support</p>
+<script>
+ function toggle(x) {
+ var div = x.nextSibling;
+ while (div != null && div.nodeType != 1)
+ div = div.nextSibling;
+ if (div != null) {
+ var d = div.style.display;
+ if (d == 'block' || d == '') {
+ div.style.display = 'none';
+ x.className += " closed";
+ } else {
+ div.style.display = 'block';
+ x.className = x.className.replace(/(?:^|\s)closed(?!\S)/g , '' );
+ }
+ }
+ }
+</script>
+
+<a id='TOC'></a><h5 class='toc'>Table of Contents</h5>
+<ol class='toc'>
+ <li><p><a class='doclink' href='#Overview'>JSON support overview</a></p>
+ <ol>
+ <li><p><a class='doclink' href='#OverviewExample'>Example</a></p>
+ </ol>
+ <li><p><a class='doclink' href='#JsonSerializer'>JsonSerializer class</a></p>
+ <ol>
+ <li><p><a class='doclink' href='#BeanAnnotations'>@Bean and @BeanProperty annotations</a></p>
+ <li><p><a class='doclink' href='#Collections'>Collections</a></p>
+ <li><p><a class='doclink' href='#JsonSchemaSupport'>JSON-Schema support</a></p>
+ <li><p><a class='doclink' href='#Recursion'> Non-tree models and recursion detection</a></p>
+ <li><p><a class='doclink' href='#SerializerConfigurableProperties'>Configurable properties</a></p>
+ <li><p><a class='doclink' href='#SerializerOtherNotes'>Other notes</a></p>
+ </ol>
+ <li><p><a class='doclink' href='#JsonParser'>JsonParser class</a></p>
+ <ol>
+ <li><p><a class='doclink' href='#GenericParsing'>Parsing into generic POJO models</a></p>
+ <li><p><a class='doclink' href='#ParserConfigurableProperties'>Configurable properties</a></p>
+ <li><p><a class='doclink' href='#ParserOtherNotes'>Other notes</a></p>
+ </ol>
+</ol>
+
+<!-- ======================================================================================================== -->
+<a id="Overview"></a>
+<h2 class='topic' onclick='toggle(this)'>1 -JSON support overview</h2>
+<div class='topic'>
+ <p>
+ Juneau supports converting arbitrary POJOs to and from JSON using ultra-efficient serializers and parsers.
+ <br>The JSON serializer converts POJOs directly to JSON without the need for intermediate DOM objects using a
+ highly-efficient state machine.
+ <br>Likewise, the JSON parser creates POJOs directly from JSON without the need for intermediate DOM objects.
+ </p>
+ <p>
+ Juneau can serialize and parse instances of any of the following POJO types:
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ Java primitives and primitive objects (e.g. <code>String</code>, <code>Integer</code>, <code>Boolean</code>,
+ <code>Float</code>).
+ <li>
+ Java Collections Framework objects (e.g. <code>HashSet</code>, <code>TreeMap</code>) containing anything on
+ this list.
+ <li>
+ Multi-dimensional arrays of any type on this list.
+ <li>
+ Java Beans with properties of any type on this list.
+ <li>
+ Classes with standard transformations to and from <code>Strings</code> (e.g. classes containing
+ <code>toString()</code>, <code>fromString()</code>, <code>valueOf()</code>, <code>constructor(String)</code>).
+ <li>
+ Non-serializable classes and properties with associated <code>PojoSwaps</code> that convert them to
+ serializable forms.
+ </ul>
+ <p>
+ Refer to <a href='../../../../overview-summary.html#juneau-marshall.PojoCategories' class='doclink'>POJO Categories</a>
+ for a complete definition of supported POJOs.
+ </p>
+
+ <h6 class='topic'>Prerequisites</h6>
+ <p>
+ The Juneau JSON serialization and parsing support does not require any external prerequisites.
+ It only requires Java 1.6 or above.
+ </p>
+
+ <!-- ======================================================================================================== -->
+ <a id="OverviewExample"></a>
+ <h3 class='topic' onclick='toggle(this)'>1.1 - JSON support overview - example</h3>
+ <div class='topic'>
+ <p>
+ The example shown here is from the Address Book resource located in the
+ <code>org.apache.juneau.sample.war</code> application.
+ <br>The POJO model consists of a <code>List</code> of <code>Person</code> beans, with each <code>Person</code>
+ containing zero or more <code>Address</code> beans.
+ </p>
+ <p>
+ When you point a browser at <code>/sample/addressBook</code>, the POJO is rendered as HTML:
+ </p>
+ <img class='bordered' src="doc-files/Example_HTML.png">
+ <p>
+ By appending <code>?Accept=<i>mediaType</i>&plainText=true</code> to the URL, you can view the data in
+ the various supported JSON formats:
+ </p>
+
+ <h6 class='figure'>Normal JSON</h6>
+ <img class='bordered' src="doc-files/Example_JSON.png">
+
+ <h6 class='figure'>Simple JSON</h6>
+ <img class='bordered' src="doc-files/Example_JSONSimple.png">
+
+ <p>
+ In addition to serializing POJOs to JSON, Juneau includes support for serializing POJO metamodels to
+ JSON Schema.
+ </p>
+
+ <h6 class='figure'>JSON Schema</h6>
+ <img class='bordered' src="doc-files/Example_JSONSchema.png">
+
+ <p>
+ The JSON data type produced depends on the Java object type being serialized.
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ Primitives and primitive objects are converted to JSON primitives.
+ <li>
+ Beans and Maps are converted to JSON objects.
+ <li>
+ Collections and arrays are converted to JSON arrays.
+ <li>
+ Anything else is converted to JSON strings.
+ </ul>
+
+ <h6 class='topic'>Examples:</h6>
+ <table class='styled'>
+ <tr>
+ <th>POJO type</th>
+ <th>Example</th>
+ <th>Serialized form</th>
+ </tr>
+ <tr>
+ <td>String</td>
+ <td><code>serializer.serialize(<js>"foobar"</js>);</code></td>
+ <td><code><js>'foobar'</js></code>
+ </tr>
+ <tr>
+ <td>Number</td>
+ <td><code>serializer.serialize(123);</code></td>
+ <td><code><jk>123</jk></code>
+ </tr>
+ <tr>
+ <td>Boolean</td>
+ <td><code>serializer.serialize(<jk>true</jk>);</code></td>
+ <td><code><jk>true</jk></code>
+ </tr>
+ <tr>
+ <td>Null</td>
+ <td><code>serializer.serialize(<jk>null</jk>);</code></td>
+ <td><code><jk>null</jk></code>
+ </tr>
+ <tr>
+ <td>Beans with properties of any type on this list</td>
+ <td><code>serializer.serialize(<jk>new</jk> MyBean());</code></td>
+ <td><code>{p1:<js>'val1'</js>,p2:<jk>true</jk>}</code>
+ </tr>
+ <tr>
+ <td>Maps with values of any type on this list</td>
+ <td><code>serializer.serialize(<jk>new</jk> TreeMap());</code></td>
+ <td><code>{key1:<js>'val1'</js>,key2:<jk>true</jk>}</code>
+ </tr>
+ <tr>
+ <td>Collections and arrays of any type on this list</td>
+ <td><code>serializer.serialize(<jk>new</jk> Object[]{1,<js>"foo"</js>,<jk>true</jk>});</code></td>
+ <td><code>[1,'foo',true]</code>
+ </tr>
+ </table>
+ <p>
+ In addition, swaps can be used to convert non-serializable POJOs into serializable forms, such as converting
+ <code>Calendar</code> object to ISO8601 strings, or <code><jk>byte</jk>[]</code> arrays to Base-64
+ encoded strings.
+ <br>These swaps can be associated at various levels:
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ On serializer and parser instances to handle all objects of the class type globally.
+ <li>
+ On classes through the <code><ja>@Bean</ja></code> annotation.
+ <li>
+ On bean properties through the <code><ja>@BeanProperty</ja></code> annotations.
+ </ul>
+ <p>
+ For more information about transforms, refer to <a class='doclink'
+ href='../transform/package-summary.html#TOC'>org.apache.juneau.transform</a>.
+ </p>
+ </div>
+</div>
+
+<!-- ======================================================================================================== -->
+<a id="JsonSerializer"></a>
+<h2 class='topic' onclick='toggle(this)'>2 - JsonSerializer class</h2>
+<div class='topic'>
+ <p>
+ {@link org.apache.juneau.json.JsonSerializer} is the class used to convert POJOs to JSON.
+ <br>{@link org.apache.juneau.json.JsonSchemaSerializer} is the class used to generate JSON-Schema from POJOs.
+ </p>
+ <p>
+ The JSON serializer includes several configurable settings.
+ <br>Static reusable instances of Json serializers are provided with commonly-used settings:
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ {@link org.apache.juneau.json.JsonSerializer#DEFAULT} - All default settings
+ <li>
+ {@link org.apache.juneau.json.JsonSerializer#DEFAULT_LAX} - Single quotes, only quote attributes when
+ necessary.
+ <li>
+ {@link org.apache.juneau.json.JsonSerializer#DEFAULT_LAX_READABLE} - Readable output.
+ </ul>
+
+ <h6 class='topic'>Notes about examples</h6>
+ <p>
+ The examples shown in this document will use single-quote, readable settings.
+ <br>For brevity, the examples will use public fields instead of getters/setters to reduce the size of the examples.
+ <br>In the real world, you'll typically want to use standard bean getters and setters.
+ </p>
+ <p>
+ To start off simple, we'll begin with the following simplified bean and build upon it.
+ </p>
+ <p class='bcode'>
+ <jk>public class</jk> Person {
+ <jc>// Bean properties</jc>
+ <jk>public int</jk> <jf>id</jf>;
+ <jk>public</jk> String <jf>name</jf>;
+
+ <jc>// Bean constructor (needed by parser)</jc>
+ <jk>public</jk> Person() {}
+
+ <jc>// Normal constructor</jc>
+ <jk>public</jk> Person(<jk>int</jk> id, String name) {
+ <jk>this</jk>.<jf>id</jf> = id;
+ <jk>this</jk>.<jf>name</jf> = name;
+ }
+ }
+ </p>
+ <p>
+ The following code shows how to convert this to simple JSON:
+ </p>
+ <p class='bcode'>
+ <jc>// Use serializer with readable output, simple mode.</jc>
+ JsonSerializer s = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>;
+
+ <jc>// Create our bean.</jc>
+ Person p = <jk>new</jk> Person(1, <js>"John Smith"</js>);
+
+ <jc>// Serialize the bean to JSON.</jc>
+ String json = s.serialize(p);
+ </p>
+ <p>
+ We could have also created a new serializer with the same settings using the following code:
+ </p>
+ <p class='bcode'>
+ JsonSerializer s = <jk>new</jk> JsonSerializerBuilder().simple().ws().sq().build();
+ </p>
+
+ <p>
+ The code above produces the following output:
+ </p>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>
+ }
+ </p>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="BeanAnnotations"></a>
+ <h3 class='topic' onclick='toggle(this)'>2.1 - @Bean and @BeanProperty annotations</h3>
+ <div class='topic'>
+ <p>
+ The {@link org.apache.juneau.annotation.Bean @Bean} and
+ {@link org.apache.juneau.annotation.BeanProperty @BeanProperty} annotations are used to customize the
+ behavior of beans across the entire framework.
+ <br>They have various uses:
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ Hiding bean properties.
+ <li>
+ Specifying the ordering of bean properties.
+ <li>
+ Overriding the names of bean properties.
+ <li>
+ Associating swaps at both the class and property level (to convert non-serializable POJOs to
+ serializable forms).
+ </ul>
+ <p>
+ For example, we now add a <code>birthDate</code> property, and associate a swap with it to transform it to
+ an ISO8601 date-time string in GMT time.
+ <br>We'll also add a couple of <code>URI</code> properties.
+ <br>By default, <code>Calendars</code> are treated as beans by the framework, which is usually not how you
+ want them serialized.
+ <br>Using swaps, we can convert them to standardized string forms.
+ </p>
+ <p class='bcode'>
+ <jk>public class</jk> Person {
+ <jc>// Bean properties</jc>
+ <jk>public int</jk> <jf>id</jf>;
+ <jk>public</jk> String <jf>name</jf>;
+ <jk>public</jk> URI <jf>uri</jf>;
+ <jk>public</jk> URI <jf>addressBookUri</jf>;
+
+ <ja>@BeanProperty</ja>(swap=CalendarSwap.ISO8601DTZ.<jk>class</jk>) <jk>public</jk> Calendar <jf>birthDate</jf>;
+
+
+ <jc>// Bean constructor (needed by parser)</jc>
+ <jk>public</jk> Person() {}
+
+ <jc>// Normal constructor</jc>
+ <jk>public</jk> Person(<jk>int</jk> id, String name, String uri, String addressBookUri, String birthDate) <jk>throws</jk> Exception {
+ <jk>this</jk>.<jf>id</jf> = id;
+ <jk>this</jk>.<jf>name</jf> = name;
+ <jk>this</jk>.<jf>uri</jf> = <jk>new</jk> URI(uri);
+ <jk>this</jk>.<jf>addressBookUri</jf> = <jk>new</jk> URI(addressBookUri);
+ <jk>this</jk>.<jf>birthDate</jf> = <jk>new</jk> GregorianCalendar();
+ <jk>this</jk>.<jf>birthDate</jf>.setTime(DateFormat.<jsm>getDateInstance</jsm>(DateFormat.<jsf>MEDIUM</jsf>).parse(birthDate));
+ }
+ }
+ </p>
+ <p>
+ Next, we alter our code to pass in the birthdate:
+ </p>
+ <p class='bcode'>
+ <jc>// Create our bean.</jc>
+ Person p = <jk>new</jk> Person(1, <js>"John Smith"</js>, <js>"http://sample/addressBook/person/1"</js>,
+ <js>"http://sample/addressBook"</js>, <js>"Aug 12, 1946"</js>);
+ </p>
+ <p>
+ Now when we rerun the sample code, we'll get the following:
+ </p>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>,
+ uri: <js>'http://sample/addressBook/person/1'</js>,
+ addressBookUri: <js>'http://sample/addressBook'</js>,
+ birthDate: <js>'1946-08-12T00:00:00Z'</js>
+ }
+ </p>
+ <p>
+ Another useful feature is the {@link org.apache.juneau.annotation.Bean#propertyNamer()} annotation that
+ allows you to plug in your own logic for determining bean property names.
+ <br>The {@link org.apache.juneau.PropertyNamerDLC} is an example of an alternate property namer.
+ It converts bean property names to lowercase-dashed format.
+ </p>
+
+ <h6 class='topic'>Example:</h6>
+ <p class='bcode'>
+ <ja>@Bean</ja>(propertyNamer=PropertyNamerDLC.<jk>class</jk>)
+ <jk>public class</jk> Person {
+ ...
+ </p>
+
+ <h6 class='figure'>Results</h6>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>,
+ uri: <js>'http://sample/addressBook/person/1'</js>,
+ <js>'address-book-uri'</js>: <js>'http://sample/addressBook'</js>,
+ <js>'birth-date'</js>: <js>'1946-08-12T00:00:00Z'</js>
+ }
+ </p>
+ </div>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="Collections"></a>
+ <h3 class='topic' onclick='toggle(this)'>2.2 - Collections</h3>
+ <div class='topic'>
+ <p>
+ In our example, let's add a list-of-beans property to our sample class:
+ </p>
+ <p class='bcode'>
+ <jk>public class</jk> Person {
+
+ <jc>// Bean properties</jc>
+ <jk>public</jk> LinkedList<Address> <jf>addresses</jf> = <jk>new</jk> LinkedList<Address>();
+ ...
+ }
+ </p>
+ <p>
+ The <code>Address</code> class has the following properties defined:
+ </p>
+ <p class='bcode'>
+ <jk>public class</jk> Address {
+
+ <jc>// Bean properties</jc>
+ <jk>public</jk> URI <jf>uri</jf>;
+ <jk>public</jk> URI <jf>personUri</jf>;
+ <jk>public int</jk> <jf>id</jf>;
+ <jk>public</jk> String <jf>street</jf>, <jf>city</jf>, <jf>state</jf>;
+ <jk>public int</jk> <jf>zip</jf>;
+ <jk>public boolean</jk> <jf>isCurrent</jf>;
+ }
+ </p>
+ <p>
+ Next, add some quick-and-dirty code to add an address to our person bean:
+ </p>
+ <p class='bcode'>
+ <jc>// Use serializer with readable output, simple mode.</jc>
+ JsonSerializer s = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>;
+
+ <jc>// Create our bean.</jc>
+ Person p = <jk>new</jk> Person(1, <js>"John Smith"</js>, <js>"http://sample/addressBook/person/1"</js>,
+ <js>"http://sample/addressBook"</js>, <js>"Aug 12, 1946"</js>);
+ Address a = <jk>new</jk> Address();
+ a.<jf>uri</jf> = <jk>new</jk> URI(<js>"http://sample/addressBook/address/1"</js>);
+ a.<jf>personUri</jf> = <jk>new</jk> URI(<js>"http://sample/addressBook/person/1"</js>);
+ a.<jf>id</jf> = 1;
+ a.<jf>street</jf> = <js>"100 Main Street"</js>;
+ a.<jf>city</jf> = <js>"Anywhereville"</js>;
+ a.<jf>state</jf> = <js>"NY"</js>;
+ a.<jf>zip</jf> = 12345;
+ a.<jf>isCurrent</jf> = <jk>true</jk>;
+ p.<jf>addresses</jf>.add(a);
+ </p>
+ <p>
+ Now when we run the sample code, we get the following:
+ </p>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>,
+ uri: <js>'http://sample/addressBook/person/1'</js>,
+ addressBookUri: <js>'http://sample/addressBook'</js>,
+ birthDate: <js>'1946-08-12T00:00:00Z'</js>,
+ addresses: [
+ {
+ uri: <js>'http://sample/addressBook/address/1'</js>,
+ personUri: <js>'http://sample/addressBook/person/1'</js>,
+ id: <jk>1</jk>,
+ street: <js>'100 Main Street'</js>,
+ city: <js>'Anywhereville'</js>,
+ state: <js>'NY'</js>,
+ zip: <jk>12345</jk>,
+ isCurrent: <jk>true</jk>
+ }
+ ]
+ }
+ </p>
+ </div>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="JsonSchemaSupport"></a>
+ <h3 class='topic' onclick='toggle(this)'>2.3 - JSON-Schema support</h3>
+ <div class='topic'>
+ <p>
+ Juneau provides the {@link org.apache.juneau.json.JsonSchemaSerializer} class for generating JSON-Schema
+ documents that describe the output generated by the {@link org.apache.juneau.json.JsonSerializer} class.
+ <br>This class shares the same properties as <code>JsonSerializer</code>.
+ <br>For convenience the {@link org.apache.juneau.json.JsonSerializer#getSchemaSerializer()} method has been
+ added for creating instances of schema serializers from the regular serializer instance.
+ </p>
+ <p>
+ <i>Note:</i> As of this writing, JSON-Schema has not been standardized, so the output generated by the
+ schema serializer may be subject to future modifications.
+ </p>
+ <p>
+ Lets start with the classes from the previous examples:
+ </p>
+ <p class='bcode'>
+ <jk>public class</jk> Person {
+ <jc>// Bean properties</jc>
+ <jk>public int</jk> <jf>id</jf>;
+ <jk>public</jk> String <jf>name</jf>;
+ <jk>public</jk> URI <jf>uri</jf>;
+ <jk>public</jk> URI <jf>addressBookUri</jf>;
+ <ja>@BeanProperty</ja>(swap=CalendarSwap.ISO8601DTZ.<jk>class</jk>) <jk>public</jk> Calendar <jf>birthDate</jf>;
+ <jk>public</jk> LinkedList<Address> <jf>addresses</jf> = <jk>new</jk> LinkedList<Address>();
+
+ <jc>// Bean constructor (needed by parser)</jc>
+ <jk>public</jk> Person() {}
+
+ <jc>// Normal constructor</jc>
+ <jk>public</jk> Person(<jk>int</jk> id, String name, String uri, String addressBookUri, String birthDate) <jk>throws</jk> Exception {
+ <jk>this</jk>.<jf>id</jf> = id;
+ <jk>this</jk>.<jf>name</jf> = name;
+ <jk>this</jk>.<jf>uri</jf> = <jk>new</jk> URI(uri);
+ <jk>this</jk>.<jf>addressBookUri</jf> = <jk>new</jk> URI(addressBookUri);
+ <jk>this</jk>.<jf>birthDate</jf> = <jk>new</jk> GregorianCalendar();
+ <jk>this</jk>.<jf>birthDate</jf>.setTime(DateFormat.getDateInstance(DateFormat.<jsf>MEDIUM</jsf>).parse(birthDate));
+ }
+ }
+
+ <jk>public class</jk> Address {
+ <jc>// Bean properties</jc>
+ <jk>public</jk> URI <jf>uri</jf>;
+ <jk>public</jk> URI <jf>personUri</jf>;
+ <jk>public int</jk> <jf>id</jf>;
+ <jk>public</jk> String <jf>street</jf>, <jf>city</jf>, <jf>state</jf>;
+ <jk>public int</jk> <jf>zip</jf>;
+ <jk>public boolean</jk> <jf>isCurrent</jf>;
+ }
+ </p>
+ <p>
+ The code for creating our POJO model and generating JSON-Schema is shown below:
+ </p>
+ <p class='bcode'>
+ <jc>// Get the schema serializer for one of the default JSON serializers.</jc>
+ JsonSchemaSerializer s = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>.getSchemaSerializer();
+
+ <jc>// Create our bean.</jc>
+ Person p = <jk>new</jk> Person(1, <js>"John Smith"</js>, <js>"http://sample/addressBook/person/1"</js>,
+ <js>"http://sample/addressBook"</js>, <js>"Aug 12, 1946"</js>);
+ Address a = <jk>new</jk> Address();
+ a.<jf>uri</jf> = <jk>new</jk> URI(<js>"http://sample/addressBook/address/1"</js>);
+ a.<jf>personUri</jf> = <jk>new</jk> URI(<js>"http://sample/addressBook/person/1"</js>);
+ a.<jf>id</jf> = 1;
+ a.<jf>street</jf> = <js>"100 Main Street"</js>;
+ a.<jf>city</jf> = <js>"Anywhereville"</js>;
+ a.<jf>state</jf> = <js>"NY"</js>;
+ a.<jf>zip</jf> = 12345;
+ a.<jf>isCurrent</jf> = <jk>true</jk>;
+ p.<jf>addresses</jf>.add(a);
+
+ <jc>// Get the JSON Schema corresponding to the JSON generated above.</jc>
+ String jsonSchema = s.serialize(p);
+ </p>
+
+ <h6 class='figure'>Results</h6>
+ <p class='bcode'>
+ {
+ type: <js>'object'</js>,
+ description: <js>'org.apache.juneau.sample.Person'</js>,
+ properties: {
+ id: {
+ type: <js>'number'</js>,
+ description: <js>'int'</js>
+ },
+ name: {
+ type: <js>'string'</js>,
+ description: <js>'java.lang.String'</js>
+ },
+ uri: {
+ type: <js>'any'</js>,
+ description: <js>'java.net.URI'</js>
+ },
+ addressBookUri: {
+ type: <js>'any'</js>,
+ description: <js>'java.net.URI'</js>
+ },
+ birthDate: {
+ type: <js>'any'</js>,
+ description: <js>'java.util.Calendar'</js>
+ },
+ addresses: {
+ type: <js>'array'</js>,
+ description: <js>'java.util.LinkedList<org.apache.juneau.sample.Address>'</js>,
+ items: {
+ type: <js>'object'</js>,
+ description: <js>'org.apache.juneau.sample.Address'</js>,
+ properties: {
+ uri: {
+ type: <js>'any'</js>,
+ description: <js>'java.net.URI'</js>
+ },
+ personUri: {
+ type: <js>'any'</js>,
+ description: <js>'java.net.URI'</js>
+ },
+ id: {
+ type: <js>'number'</js>,
+ description: <js>'int'</js>
+ },
+ street: {
+ type: <js>'string'</js>,
+ description: <js>'java.lang.String'</js>
+ },
+ city: {
+ type: <js>'string'</js>,
+ description: <js>'java.lang.String'</js>
+ },
+ state: {
+ type: <js>'string'</js>,
+ description: <js>'java.lang.String'</js>
+ },
+ zip: {
+ type: <js>'number'</js>,
+ description: <js>'int'</js>
+ },
+ isCurrent: {
+ type: <js>'boolean'</js>,
+ description: <js>'boolean'</js>
+ }
+ }
+ }
+ }
+ }
+ }
+ </p>
+ </div>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="Recursion"></a>
+ <h3 class='topic' onclick='toggle(this)'>2.4 - Non-tree models and recursion detection</h3>
+ <div class='topic'>
+ <p>
+ The JSON serializer is designed to be used against POJO tree structures.
+ <br>It expects that there not be loops in the POJO model (e.g. children with references to parents, etc...).
+ <br>If you try to serialize models with loops, you will usually cause a <code>StackOverflowError</code> to
+ be thrown (if {@link org.apache.juneau.serializer.SerializerContext#SERIALIZER_maxDepth} is not reached
+ first).
+ </p>
+ <p>
+ If you still want to use the JSON serializer on such models, Juneau provides the
+ {@link org.apache.juneau.serializer.SerializerContext#SERIALIZER_detectRecursions} setting.
+ <br>It tells the serializer to look for instances of an object in the current branch of the tree and skip
+ serialization when a duplicate is encountered.
+ </p>
+ <p>
+ For example, let's make a POJO model out of the following classes:
+ </p>
+ <p class='bcode'>
+ <jk>public class</jk> A {
+ <jk>public</jk> B b;
+ }
+
+ <jk>public class</jk> B {
+ <jk>public</jk> C c;
+ }
+
+ <jk>public class</jk> C {
+ <jk>public</jk> A a;
+ }
+ </p>
+ <p>
+ Now we create a model with a loop and serialize the results.
+ </p>
+ <p class='bcode'>
+ <jc>// Clone an existing serializer and set property for detecting recursions.</jc>
+ JsonSerializer s = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>.builder().detectRecursions(<jk>true</jk>).build();
+
+ <jc>// Create a recursive loop.</jc>
+ A a = <jk>new</jk> A();
+ a.<jf>b</jf> = <jk>new</jk> B();
+ a.<jf>b</jf>.<jf>c</jf> = <jk>new</jk> C();
+ a.<jf>b</jf>.<jf>c</jf>.<jf>a</jf> = a;
+
+ <jc>// Serialize to JSON.</jc>
+ String json = s.serialize(a);
+ </p>
+ <p>
+ What we end up with is the following, which does not serialize the contents of the <code>c</code> field:
+ </p>
+ <p class='bcode'>
+ {
+ b: {
+ c: {
+ }
+ }
+ }
+ </p>
+ <p>
+ Without recursion detection enabled, this would cause a stack-overflow error.
+ </p>
+ <p>
+ Recursion detection introduces a performance penalty of around 20%.
+ <br>For this reason the setting is disabled by default.
+ </p>
+ </div>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="SerializerConfigurableProperties"></a>
+ <h3 class='topic' onclick='toggle(this)'>2.5 - Configurable properties</h3>
+ <div class='topic'>
+ <p>
+ See the following classes for all configurable properties that can be used on this serializer:
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ {@link org.apache.juneau.BeanContext} - Bean context properties.
+ <li>
+ {@link org.apache.juneau.json.JsonSerializerContext} - Serializer context properties.
+ </ul>
+ </div>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="SerializerOtherNotes"></a>
+ <h3 class='topic' onclick='toggle(this)'>2.6 - Other notes</h3>
+ <div class='topic'>
+ <ul class='spaced-list'>
+ <li>
+ Like all other Juneau serializers, the JSON serializer is thread safe and maintains an internal cache
+ of bean classes encountered.
+ <br>For performance reasons, it's recommended that serializers be reused whenever possible instead of
+ always creating new instances.
+ </ul>
+ </div>
+</div>
+
+
+<!-- ======================================================================================================== -->
+<a id="JsonParser"></a>
+<h2 class='topic' onclick='toggle(this)'>3 - JsonParser class</h2>
+<div class='topic'>
+ <p>
+ The {@link org.apache.juneau.json.JsonParser} class is the class used to parse JSON back into POJOs.
+ </p>
+ <p>
+ The JSON parser supports ALL valid JSON, including:
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ Javascript comments.
+ <li>
+ Single or double quoted values.
+ <li>
+ Quoted (strict) or unquoted (non-strict) attributes.
+ <li>
+ JSON fragments (such as string, numeric, or boolean primitive values).
+ <li>
+ Concatenated strings.
+ </ul>
+ <p>
+ A static reusable instance of <code>JsonParser</code> is also provided for convenience:
+ </p>
+ <ul>
+ <li>{@link org.apache.juneau.json.JsonParser#DEFAULT}
+ </ul>
+ <p>
+ Let's build upon the previous example and parse the generated JSON back into the original bean.
+ <br>We start with the JSON that was generated.
+ </p>
+ <p class='bcode'>
+ <jc>// Use serializer with readable output, simple mode.</jc>
+ JsonSerializer s = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>;
+
+ <jc>// Create our bean.</jc>
+ Person p = <jk>new</jk> Person(1, <js>"John Smith"</js>, <js>"http://sample/addressBook/person/1"</js>,
+ <js>"http://sample/addressBook"</js>, <js>"Aug 12, 1946"</js>);
+ Address a = <jk>new</jk> Address();
+ a.<jf>uri</jf> = <jk>new</jk> URI(<js>"http://sample/addressBook/address/1"</js>);
+ a.<jf>personUri</jf> = <jk>new</jk> URI(<js>"http://sample/addressBook/person/1"</js>);
+ a.<jf>id</jf> = 1;
+ a.<jf>street</jf> = <js>"100 Main Street"</js>;
+ a.<jf>city</jf> = <js>"Anywhereville"</js>;
+ a.<jf>state</jf> = <js>"NY"</js>;
+ a.<jf>zip</jf> = 12345;
+ a.<jf>isCurrent</jf> = <jk>true</jk>;
+ p.<jf>addresses</jf>.add(a);
+
+ <jc>// Serialize the bean to JSON.</jc>
+ String json = s.serialize(p);
+ </p>
+ <p>
+ This code produced the following:
+ </p>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>,
+ uri: <js>'http://sample/addressBook/person/1'</js>,
+ addressBookUri: <js>'http://sample/addressBook'</js>,
+ birthDate: <js>'1946-08-12T00:00:00Z'</js>,
+ addresses: [
+ {
+ uri: <js>'http://sample/addressBook/address/1'</js>,
+ personUri: <js>'http://sample/addressBook/person/1'</js>,
+ id: <jk>1</jk>,
+ street: <js>'100 Main Street'</js>,
+ city: <js>'Anywhereville'</js>,
+ state: <js>'NY'</js>,
+ zip: <jk>12345</jk>,
+ isCurrent: <jk>true</jk>
+ }
+ ]
+ }
+ </p>
+ <p>
+ The code to convert this back into a bean is:
+ </p>
+ <p class='bcode'>
+ <jc>// Parse it back into a bean using the reusable JSON parser.</jc>
+ Person p = JsonParser.<jsf>DEFAULT</jsf>.parse(json, Person.<jk>class</jk>);
+
+ <jc>// Render it back as JSON.</jc>
+ json = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>.serialize(p);
+ </p>
+ <p>
+ We print it back out to JSON to show that all the data has been preserved:
+ </p>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>,
+ uri: <js>'http://sample/addressBook/person/1'</js>,
+ addressBookUri: <js>'http://sample/addressBook'</js>,
+ birthDate: <js>'1946-08-12T00:00:00Z'</js>,
+ addresses: [
+ {
+ uri: <js>'http://sample/addressBook/address/1'</js>,
+ personUri: <js>'http://sample/addressBook/person/1'</js>,
+ id: <jk>1</jk>,
+ street: <js>'100 Main Street'</js>,
+ city: <js>'Anywhereville'</js>,
+ state: <js>'NY'</js>,
+ zip: <jk>12345</jk>,
+ isCurrent: <jk>true</jk>
+ }
+ ]
+ }
+ </p>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="GenericParsing"></a>
+ <h3 class='topic' onclick='toggle(this)'>3.1 - Parsing into generic POJO models</h3>
+ <div class='topic'>
+ <p>
+ The JSON parser is not limited to parsing back into the original bean classes.
+ <br>If the bean classes are not available on the parsing side, the parser can also be used to
+ parse into a generic model consisting of <code>Maps</code>, <code>Collections</code>, and primitive
+ objects.
+ </p>
+ <p>
+ You can parse into any <code>Map</code> type (e.g. <code>HashMap</code>, <code>TreeMap</code>), but
+ using {@link org.apache.juneau.ObjectMap} is recommended since it has many convenience methods
+ for converting values to various types.
+ <br>The same is true when parsing collections. You can use any Collection (e.g. <code>HashSet</code>,
+ <code>LinkedList</code>) or array (e.g. <code>Object[]</code>, <code>String[]</code>,
+ <code>String[][]</code>), but using {@link org.apache.juneau.ObjectList} is recommended.
+ </p>
+ <p>
+ When the map or list type is not specified, or is the abstract <code>Map</code>, <code>Collection</code>,
+ or <code>List</code> types, the parser will use <code>ObjectMap</code> and <code>ObjectList</code> by
+ default.
+ </p>
+ <p>
+ Starting back with our original JSON:
+ </p>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>,
+ uri: <js>'http://sample/addressBook/person/1'</js>,
+ addressBookUri: <js>'http://sample/addressBook'</js>,
+ birthDate: <js>'1946-08-12T00:00:00Z'</js>,
+ addresses: [
+ {
+ uri: <js>'http://sample/addressBook/address/1'</js>,
+ personUri: <js>'http://sample/addressBook/person/1'</js>,
+ id: <jk>1</jk>,
+ street: <js>'100 Main Street'</js>,
+ city: <js>'Anywhereville'</js>,
+ state: <js>'NY'</js>,
+ zip: <jk>12345</jk>,
+ isCurrent: <jk>true</jk>
+ }
+ ]
+ }
+ </p>
+ <p>
+ We can parse this into a generic <code>ObjectMap</code>:
+ </p>
+ <p class='bcode'>
+ <jc>// Parse JSON into a generic POJO model.</jc>
+ ObjectMap m = JsonParser.<jsf>DEFAULT</jsf>.parse(json, ObjectMap.<jk>class</jk>);
+
+ <jc>// Convert it back to JSON.</jc>
+ String json = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>.serialize(m);
+ </p>
+ <p>
+ What we end up with is the exact same output.
+ <br>Even the numbers and booleans are preserved because they are parsed into <code>Number</code> and
+ <code>Boolean</code> objects when parsing into generic models.
+ </p>
+ <p class='bcode'>
+ {
+ id: <jk>1</jk>,
+ name: <js>'John Smith'</js>,
+ uri: <js>'http://sample/addressBook/person/1'</js>,
+ addressBookUri: <js>'http://sample/addressBook'</js>,
+ birthDate: <js>'1946-08-12T00:00:00Z'</js>,
+ addresses: [
+ {
+ uri: <js>'http://sample/addressBook/address/1'</js>,
+ personUri: <js>'http://sample/addressBook/person/1'</js>,
+ id: <jk>1</jk>,
+ street: <js>'100 Main Street'</js>,
+ city: <js>'Anywhereville'</js>,
+ state: <js>'NY'</js>,
+ zip: <jk>12345</jk>,
+ isCurrent: <jk>true</jk>
+ }
+ ]
+ }
+ </p>
+ <p>
+ Once parsed into a generic model, various convenience methods are provided on the <code>ObjectMap</code>
+ and <code>ObjectList</code> classes to retrieve values:
+ </p>
+ <p class='bcode'>
+ <jc>// Parse JSON into a generic POJO model.</jc>
+ ObjectMap m = JsonParser.<jsf>DEFAULT</jsf>.parse(json, ObjectMap.<jk>class</jk>);
+
+ <jc>// Get some simple values.</jc>
+ String name = m.getString(<js>"name"</js>);
+ <jk>int</jk> id = m.getInt(<js>"id"</js>);
+
+ <jc>// Get a value convertable from a String.</jc>
+ URI uri = m.get(URI.<jk>class</jk>, <js>"uri"</js>);
+
+ <jc>// Get a value using a swap.</jc>
+ CalendarSwap swap = <jk>new</jk> CalendarSwap.ISO8601DTZ();
+ Calendar birthDate = m.get(swap, <js>"birthDate"</js>);
+
+ <jc>// Get the addresses.</jc>
+ ObjectList addresses = m.getObjectList(<js>"addresses"</js>);
+
+ <jc>// Get the first address and convert it to a bean.</jc>
+ Address address = addresses.get(Address.<jk>class</jk>, 0);
+ </p>
+
+ <p>
+ As a general rule, parsing into beans is often more efficient than parsing into generic models.
+ <br>And working with beans is often less error prone than working with generic models.
+ </p>
+ </div>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="ParserConfigurableProperties"></a>
+ <h3 class='topic' onclick='toggle(this)'>3.2 - Configurable properties</h3>
+ <div class='topic'>
+ <p>
+ See the following classes for all configurable properties that can be used on this parser:
+ </p>
+ <ul class='spaced-list'>
+ <li>
+ {@link org.apache.juneau.BeanContext} - Bean context properties.
+ <li>
+ {@link org.apache.juneau.json.JsonParserContext} - Serializer context properties.
+ </ul>
+ </div>
+
+
+ <!-- ======================================================================================================== -->
+ <a id="ParserOtherNotes"></a>
+ <h3 class='topic' onclick='toggle(this)'>3.3 - Other notes</h3>
+ <div class='topic'>
+ <ul class='spaced-list'>
+ <li>
+ Like all other Juneau parsers, the JSON parser is thread safe and maintains an internal cache of bean
+ classes encountered.
+ <br>For performance reasons, it's recommended that parser be reused whenever possible instead of always
+ creating new instances.
+ </ul>
+ </div>
+
+</div>
+<p align="center"><i><b>*** fín ***</b></i></p>
+
+</body>
+</html>
\ No newline at end of file
[2/3] incubator-juneau git commit: YAML prototype.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserSession.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserSession.java
new file mode 100644
index 0000000..62de10e
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserSession.java
@@ -0,0 +1,669 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import static org.apache.juneau.internal.StringUtils.*;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.transform.*;
+
+/**
+ * Session object that lives for the duration of a single use of {@link YamlParser}.
+ *
+ * <p>
+ * This class is NOT thread safe.
+ * It is typically discarded after one-time use although it can be reused against multiple inputs.
+ */
+@SuppressWarnings({ "unchecked", "rawtypes" })
+public final class YamlParserSession extends ReaderParserSession {
+
+ private static final AsciiSet decChars = new AsciiSet("0123456789");
+
+ /**
+ * Create a new session using properties specified in the context.
+ *
+ * @param ctx
+ * The context creating this session object.
+ * The context contains all the configuration settings for this object.
+ * @param args
+ * Runtime session arguments.
+ */
+ protected YamlParserSession(YamlParserContext ctx, ParserSessionArgs args) {
+ super(ctx, args);
+ }
+
+ /**
+ * Returns <jk>true</jk> if the specified character is whitespace.
+ *
+ * <p>
+ * The definition of whitespace is different for strict vs lax mode.
+ * Strict mode only interprets 0x20 (space), 0x09 (tab), 0x0A (line feed) and 0x0D (carriage return) as whitespace.
+ * Lax mode uses {@link Character#isWhitespace(int)} to make the determination.
+ *
+ * @param cp The codepoint.
+ * @return <jk>true</jk> if the specified character is whitespace.
+ */
+ protected final boolean isWhitespace(int cp) {
+ if (isStrict())
+ return cp <= 0x20 && (cp == 0x09 || cp == 0x0A || cp == 0x0D || cp == 0x20);
+ return Character.isWhitespace(cp);
+ }
+
+ /**
+ * Returns <jk>true</jk> if the specified character is whitespace or '/'.
+ *
+ * @param cp The codepoint.
+ * @return <jk>true</jk> if the specified character is whitespace or '/'.
+ */
+ protected final boolean isCommentOrWhitespace(int cp) {
+ if (cp == '/')
+ return true;
+ if (isStrict())
+ return cp <= 0x20 && (cp == 0x09 || cp == 0x0A || cp == 0x0D || cp == 0x20);
+ return Character.isWhitespace(cp);
+ }
+
+ @Override /* ParserSession */
+ protected <T> T doParse(ParserPipe pipe, ClassMeta<T> type) throws Exception {
+ ParserReader r = pipe.getParserReader();
+ if (r == null)
+ return null;
+ T o = parseAnything(type, r, getOuter(), null);
+ validateEnd(r);
+ return o;
+ }
+
+ @Override /* ReaderParserSession */
+ protected <K,V> Map<K,V> doParseIntoMap(ParserPipe pipe, Map<K,V> m, Type keyType, Type valueType) throws Exception {
+ ParserReader r = pipe.getParserReader();
+ m = parseIntoMap2(r, m, (ClassMeta<K>)getClassMeta(keyType), (ClassMeta<V>)getClassMeta(valueType), null);
+ validateEnd(r);
+ return m;
+ }
+
+ @Override /* ReaderParserSession */
+ protected <E> Collection<E> doParseIntoCollection(ParserPipe pipe, Collection<E> c, Type elementType) throws Exception {
+ ParserReader r = pipe.getParserReader();
+ c = parseIntoCollection2(r, c, getClassMeta(elementType), null);
+ validateEnd(r);
+ return c;
+ }
+
+ private <T> T parseAnything(ClassMeta<T> eType, ParserReader r, Object outer, BeanPropertyMeta pMeta) throws Exception {
+
+ if (eType == null)
+ eType = (ClassMeta<T>)object();
+ PojoSwap<T,Object> swap = (PojoSwap<T,Object>)eType.getPojoSwap(this);
+ ClassMeta<?> sType = swap == null ? eType : swap.getSwapClassMeta(this);
+ setCurrentClass(sType);
+
+ Object o = null;
+
+ skipCommentsAndSpace(r);
+ int c = r.peek();
+ if (c == -1) {
+ if (isStrict())
+ throw new ParseException(r.getLocation(this), "Empty input.");
+ // Let o be null.
+ } else if ((c == ',' || c == '}' || c == ']')) {
+ if (isStrict())
+ throw new ParseException(r.getLocation(this), "Missing value detected.");
+ // Handle bug in Cognos 10.2.1 that can product non-existent values.
+ // Let o be null;
+ } else if (c == 'n') {
+ parseKeyword("null", r);
+ } else if (sType.isObject()) {
+ if (c == '{') {
+ ObjectMap m2 = new ObjectMap(this);
+ parseIntoMap2(r, m2, string(), object(), pMeta);
+ o = cast(m2, pMeta, eType);
+ } else if (c == '[') {
+ o = parseIntoCollection2(r, new ObjectList(this), object(), pMeta);
+ } else if (c == '\'' || c == '"') {
+ o = parseString(r);
+ if (sType.isChar())
+ o = o.toString().charAt(0);
+ } else if (c >= '0' && c <= '9' || c == '-' || c == '.') {
+ o = parseNumber(r, null);
+ } else if (c == 't') {
+ parseKeyword("true", r);
+ o = Boolean.TRUE;
+ } else {
+ parseKeyword("false", r);
+ o = Boolean.FALSE;
+ }
+ } else if (sType.isBoolean()) {
+ o = parseBoolean(r);
+ } else if (sType.isCharSequence()) {
+ o = parseString(r);
+ } else if (sType.isChar()) {
+ o = parseString(r).charAt(0);
+ } else if (sType.isNumber()) {
+ o = parseNumber(r, (Class<? extends Number>)sType.getInnerClass());
+ } else if (sType.isMap()) {
+ Map m = (sType.canCreateNewInstance(outer) ? (Map)sType.newInstance(outer) : new ObjectMap(this));
+ o = parseIntoMap2(r, m, sType.getKeyType(), sType.getValueType(), pMeta);
+ } else if (sType.isCollection()) {
+ if (c == '{') {
+ ObjectMap m = new ObjectMap(this);
+ parseIntoMap2(r, m, string(), object(), pMeta);
+ o = cast(m, pMeta, eType);
+ } else {
+ Collection l = (sType.canCreateNewInstance(outer) ? (Collection)sType.newInstance() : new ObjectList(this));
+ o = parseIntoCollection2(r, l, sType, pMeta);
+ }
+ } else if (sType.canCreateNewBean(outer)) {
+ BeanMap m = newBeanMap(outer, sType.getInnerClass());
+ o = parseIntoBeanMap2(r, m).getBean();
+ } else if (sType.canCreateNewInstanceFromString(outer) && (c == '\'' || c == '"')) {
+ o = sType.newInstanceFromString(outer, parseString(r));
+ } else if (sType.canCreateNewInstanceFromNumber(outer) && isFirstNumberChar((char)c)) {
+ o = sType.newInstanceFromNumber(this, outer, parseNumber(r, sType.getNewInstanceFromNumberClass()));
+ } else if (sType.isArray() || sType.isArgs()) {
+ if (c == '{') {
+ ObjectMap m = new ObjectMap(this);
+ parseIntoMap2(r, m, string(), object(), pMeta);
+ o = cast(m, pMeta, eType);
+ } else {
+ ArrayList l = (ArrayList)parseIntoCollection2(r, new ArrayList(), sType, pMeta);
+ o = toArray(sType, l);
+ }
+ } else if (c == '{') {
+ Map m = new ObjectMap(this);
+ parseIntoMap2(r, m, sType.getKeyType(), sType.getValueType(), pMeta);
+ if (m.containsKey(getBeanTypePropertyName(eType)))
+ o = cast((ObjectMap)m, pMeta, eType);
+ else
+ throw new ParseException(r.getLocation(this), "Class ''{0}'' could not be instantiated. Reason: ''{1}''",
+ sType.getInnerClass().getName(), sType.getNotABeanReason());
+ } else if (sType.canCreateNewInstanceFromString(outer) && ! isStrict()) {
+ o = sType.newInstanceFromString(outer, parseString(r));
+ } else {
+ throw new ParseException(r.getLocation(this), "Unrecognized syntax for class type ''{0}'', starting character ''{1}''",
+ sType, (char)c);
+ }
+
+ if (swap != null && o != null)
+ o = swap.unswap(this, o, eType);
+
+ if (outer != null)
+ setParent(eType, o, outer);
+
+ return (T)o;
+ }
+
+ private Number parseNumber(ParserReader r, Class<? extends Number> type) throws Exception {
+ int c = r.peek();
+ if (c == '\'' || c == '"')
+ return parseNumber(r, parseString(r), type);
+ return parseNumber(r, parseNumberString(r), type);
+ }
+
+ private Number parseNumber(ParserReader r, String s, Class<? extends Number> type) throws Exception {
+
+ // JSON has slightly different number rules from Java.
+ // Strict mode enforces these different rules, lax does not.
+ if (isStrict()) {
+
+ // Lax allows blank strings to represent 0.
+ // Strict does not allow blank strings.
+ if (s.length() == 0)
+ throw new ParseException(r.getLocation(this), "Invalid JSON number: ''{0}''", s);
+
+ // Need to weed out octal and hexadecimal formats: 0123,-0123,0x123,-0x123.
+ // Don't weed out 0 or -0.
+ boolean isNegative = false;
+ char c = s.charAt(0);
+ if (c == '-') {
+ isNegative = true;
+ c = (s.length() == 1 ? 'x' : s.charAt(1));
+ }
+
+ // JSON doesn't allow '.123' and '-.123'.
+ if (c == '.')
+ throw new ParseException(loc(r), "Invalid JSON number: ''{0}''", s);
+
+ // '01' is not a valid number, but '0.1', '0e1', '0e+1' are valid.
+ if (c == '0' && s.length() > (isNegative ? 2 : 1)) {
+ char c2 = s.charAt((isNegative ? 2 : 1));
+ if (c2 != '.' && c2 != 'e' && c2 != 'E')
+ throw new ParseException(loc(r), "Invalid JSON number: ''{0}''", s);
+ }
+
+ // JSON doesn't allow '1.' or '0.e1'.
+ int i = s.indexOf('.');
+ if (i != -1 && (s.length() == (i+1) || ! decChars.contains(s.charAt(i+1))))
+ throw new ParseException(loc(r), "Invalid JSON number: ''{0}''", s);
+
+ }
+ return StringUtils.parseNumber(s, type);
+ }
+
+ private Boolean parseBoolean(ParserReader r) throws Exception {
+ int c = r.peek();
+ if (c == '\'' || c == '"')
+ return Boolean.valueOf(parseString(r));
+ if (c == 't') {
+ parseKeyword("true", r);
+ return Boolean.TRUE;
+ }
+ parseKeyword("false", r);
+ return Boolean.FALSE;
+ }
+
+
+ private <K,V> Map<K,V> parseIntoMap2(ParserReader r, Map<K,V> m, ClassMeta<K> keyType,
+ ClassMeta<V> valueType, BeanPropertyMeta pMeta) throws Exception {
+
+ if (keyType == null)
+ keyType = (ClassMeta<K>)string();
+
+ int S0=0; // Looking for outer {
+ int S1=1; // Looking for attrName start.
+ int S3=3; // Found attrName end, looking for :.
+ int S4=4; // Found :, looking for valStart: { [ " ' LITERAL.
+ int S5=5; // Looking for , or }
+ int S6=6; // Found , looking for attr start.
+
+ int state = S0;
+ String currAttr = null;
+ int c = 0;
+ while (c != -1) {
+ c = r.read();
+ if (state == S0) {
+ if (c == '{')
+ state = S1;
+ } else if (state == S1) {
+ if (c == '}') {
+ return m;
+ } else if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else {
+ currAttr = parseFieldName(r.unread());
+ state = S3;
+ }
+ } else if (state == S3) {
+ if (c == ':')
+ state = S4;
+ } else if (state == S4) {
+ if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else {
+ K key = convertAttrToType(m, currAttr, keyType);
+ V value = parseAnything(valueType, r.unread(), m, pMeta);
+ setName(valueType, value, key);
+ m.put(key, value);
+ state = S5;
+ }
+ } else if (state == S5) {
+ if (c == ',')
+ state = S6;
+ else if (isCommentOrWhitespace(c))
+ skipCommentsAndSpace(r.unread());
+ else if (c == '}') {
+ return m;
+ } else {
+ break;
+ }
+ } else if (state == S6) {
+ if (c == '}') {
+ break;
+ } else if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else {
+ currAttr = parseFieldName(r.unread());
+ state = S3;
+ }
+ }
+ }
+ if (state == S0)
+ throw new ParseException(loc(r), "Expected '{' at beginning of JSON object.");
+ if (state == S1)
+ throw new ParseException(loc(r), "Could not find attribute name on JSON object.");
+ if (state == S3)
+ throw new ParseException(loc(r), "Could not find ':' following attribute name on JSON object.");
+ if (state == S4)
+ throw new ParseException(loc(r), "Expected one of the following characters: {,[,',\",LITERAL.");
+ if (state == S5)
+ throw new ParseException(loc(r), "Could not find '}' marking end of JSON object.");
+ if (state == S6)
+ throw new ParseException(loc(r), "Unexpected '}' found in JSON object.");
+
+ return null; // Unreachable.
+ }
+
+ /*
+ * Parse a JSON attribute from the character array at the specified position, then
+ * set the position marker to the last character in the field name.
+ */
+ private String parseFieldName(ParserReader r) throws Exception {
+ int c = r.peek();
+ if (c == '\'' || c == '"')
+ return parseString(r);
+ if (isStrict())
+ throw new ParseException(loc(r), "Unquoted attribute detected.");
+ r.mark();
+ // Look for whitespace.
+ while (c != -1) {
+ c = r.read();
+ if (c == ':' || isWhitespace(c) || c == '/') {
+ r.unread();
+ String s = r.getMarked().intern();
+ return s.equals("null") ? null : s;
+ }
+ }
+ throw new ParseException(loc(r), "Could not find the end of the field name.");
+ }
+
+ private <E> Collection<E> parseIntoCollection2(ParserReader r, Collection<E> l,
+ ClassMeta<?> type, BeanPropertyMeta pMeta) throws Exception {
+
+ int S0=0; // Looking for outermost [
+ int S1=1; // Looking for starting [ or { or " or ' or LITERAL or ]
+ int S2=2; // Looking for , or ]
+ int S3=3; // Looking for starting [ or { or " or ' or LITERAL
+
+ int argIndex = 0;
+
+ int state = S0;
+ int c = 0;
+ while (c != -1) {
+ c = r.read();
+ if (state == S0) {
+ if (c == '[')
+ state = S1;
+ } else if (state == S1) {
+ if (c == ']') {
+ return l;
+ } else if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else if (c != -1) {
+ l.add((E)parseAnything(type.isArgs() ? type.getArg(argIndex++) : type.getElementType(), r.unread(), l, pMeta));
+ state = S2;
+ }
+ } else if (state == S2) {
+ if (c == ',') {
+ state = S3;
+ } else if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else if (c == ']') {
+ return l;
+ } else {
+ break; // Invalid character found.
+ }
+ } else if (state == S3) {
+ if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else if (c == ']') {
+ break;
+ } else if (c != -1) {
+ l.add((E)parseAnything(type.isArgs() ? type.getArg(argIndex++) : type.getElementType(), r.unread(), l, pMeta));
+ state = S2;
+ }
+ }
+ }
+ if (state == S0)
+ throw new ParseException(loc(r), "Expected '[' at beginning of JSON array.");
+ if (state == S1)
+ throw new ParseException(loc(r), "Expected one of the following characters: {,[,',\",LITERAL.");
+ if (state == S2)
+ throw new ParseException(loc(r), "Expected ',' or ']'.");
+ if (state == S3)
+ throw new ParseException(loc(r), "Unexpected trailing comma in array.");
+
+ return null; // Unreachable.
+ }
+
+ private <T> BeanMap<T> parseIntoBeanMap2(ParserReader r, BeanMap<T> m) throws Exception {
+
+ int S0=0; // Looking for outer {
+ int S1=1; // Looking for attrName start.
+ int S3=3; // Found attrName end, looking for :.
+ int S4=4; // Found :, looking for valStart: { [ " ' LITERAL.
+ int S5=5; // Looking for , or }
+
+ int state = S0;
+ String currAttr = "";
+ int c = 0;
+ int currAttrLine = -1, currAttrCol = -1;
+ while (c != -1) {
+ c = r.read();
+ if (state == S0) {
+ if (c == '{')
+ state = S1;
+ } else if (state == S1) {
+ if (c == '}') {
+ return m;
+ } else if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else {
+ r.unread();
+ currAttrLine= r.getLine();
+ currAttrCol = r.getColumn();
+ currAttr = parseFieldName(r);
+ state = S3;
+ }
+ } else if (state == S3) {
+ if (c == ':')
+ state = S4;
+ } else if (state == S4) {
+ if (isCommentOrWhitespace(c)) {
+ skipCommentsAndSpace(r.unread());
+ } else {
+ if (! currAttr.equals(getBeanTypePropertyName(m.getClassMeta()))) {
+ BeanPropertyMeta pMeta = m.getPropertyMeta(currAttr);
+ setCurrentProperty(pMeta);
+ if (pMeta == null) {
+ onUnknownProperty(r.getPipe(), currAttr, m, currAttrLine, currAttrCol);
+ parseAnything(object(), r.unread(), m.getBean(false), null); // Read content anyway to ignore it
+ } else {
+ ClassMeta<?> cm = pMeta.getClassMeta();
+ Object value = parseAnything(cm, r.unread(), m.getBean(false), pMeta);
+ setName(cm, value, currAttr);
+ pMeta.set(m, currAttr, value);
+ }
+ setCurrentProperty(null);
+ }
+ state = S5;
+ }
+ } else if (state == S5) {
+ if (c == ',')
+ state = S1;
+ else if (isCommentOrWhitespace(c))
+ skipCommentsAndSpace(r.unread());
+ else if (c == '}') {
+ return m;
+ }
+ }
+ }
+ if (state == S0)
+ throw new ParseException(loc(r), "Expected '{' at beginning of JSON object.");
+ if (state == S1)
+ throw new ParseException(loc(r), "Could not find attribute name on JSON object.");
+ if (state == S3)
+ throw new ParseException(loc(r), "Could not find ':' following attribute name on JSON object.");
+ if (state == S4)
+ throw new ParseException(loc(r), "Expected one of the following characters: {,[,',\",LITERAL.");
+ if (state == S5)
+ throw new ParseException(loc(r), "Could not find '}' marking end of JSON object.");
+
+ return null; // Unreachable.
+ }
+
+ /*
+ * Starting from the specified position in the character array, returns the
+ * position of the character " or '.
+ * If the string consists of a concatenation of strings (e.g. 'AAA' + "BBB"), this method
+ * will automatically concatenate the strings and return the result.
+ */
+ private String parseString(ParserReader r) throws Exception {
+ r.mark();
+ int qc = r.read(); // The quote character being used (" or ')
+ if (qc != '"' && isStrict()) {
+ String msg = (
+ qc == '\''
+ ? "Invalid quote character \"{0}\" being used."
+ : "Did not find quote character marking beginning of string. Character=\"{0}\""
+ );
+ throw new ParseException(loc(r), msg, (char)qc);
+ }
+ final boolean isQuoted = (qc == '\'' || qc == '"');
+ String s = null;
+ boolean isInEscape = false;
+ int c = 0;
+ while (c != -1) {
+ c = r.read();
+ // Strict syntax requires that all control characters be escaped.
+ if (isStrict() && c <= 0x1F)
+ throw new ParseException("Unescaped control character encountered: ''0x{0}''", String.format("%04X", c));
+ if (isInEscape) {
+ switch (c) {
+ case 'n': r.replace('\n'); break;
+ case 'r': r.replace('\r'); break;
+ case 't': r.replace('\t'); break;
+ case 'f': r.replace('\f'); break;
+ case 'b': r.replace('\b'); break;
+ case '\\': r.replace('\\'); break;
+ case '/': r.replace('/'); break;
+ case '\'': r.replace('\''); break;
+ case '"': r.replace('"'); break;
+ case 'u': {
+ String n = r.read(4);
+ try {
+ r.replace(Integer.parseInt(n, 16), 6);
+ } catch (NumberFormatException e) {
+ throw new ParseException(loc(r), "Invalid Unicode escape sequence in string.");
+ }
+ break;
+ }
+ default:
+ throw new ParseException(loc(r), "Invalid escape sequence in string.");
+ }
+ isInEscape = false;
+ } else {
+ if (c == '\\') {
+ isInEscape = true;
+ r.delete();
+ } else if (isQuoted) {
+ if (c == qc) {
+ s = r.getMarked(1, -1);
+ break;
+ }
+ } else {
+ if (c == ',' || c == '}' || c == ']' || isWhitespace(c)) {
+ s = r.getMarked(0, -1);
+ r.unread();
+ break;
+ } else if (c == -1) {
+ s = r.getMarked(0, 0);
+ break;
+ }
+ }
+ }
+ }
+ if (s == null)
+ throw new ParseException(loc(r), "Could not find expected end character ''{0}''.", (char)qc);
+
+ // Look for concatenated string (i.e. whitespace followed by +).
+ skipCommentsAndSpace(r);
+ if (r.peek() == '+') {
+ if (isStrict())
+ throw new ParseException(loc(r), "String concatenation detected.");
+ r.read(); // Skip past '+'
+ skipCommentsAndSpace(r);
+ s += parseString(r);
+ }
+ return trim(s); // End of input reached.
+ }
+
+ /*
+ * Looks for the keywords true, false, or null.
+ * Throws an exception if any of these keywords are not found at the specified position.
+ */
+ private void parseKeyword(String keyword, ParserReader r) throws Exception {
+ try {
+ String s = r.read(keyword.length());
+ if (s.equals(keyword))
+ return;
+ throw new ParseException(loc(r), "Unrecognized syntax.");
+ } catch (IndexOutOfBoundsException e) {
+ throw new ParseException(loc(r), "Unrecognized syntax.");
+ }
+ }
+
+ /*
+ * Doesn't actually parse anything, but moves the position beyond any whitespace or comments.
+ * If positionOnNext is 'true', then the cursor will be set to the point immediately after
+ * the comments and whitespace. Otherwise, the cursor will be set to the last position of
+ * the comments and whitespace.
+ */
+ private void skipCommentsAndSpace(ParserReader r) throws Exception {
+ int c = 0;
+ while ((c = r.read()) != -1) {
+ if (! isWhitespace(c)) {
+ if (c == '/') {
+ if (isStrict())
+ throw new ParseException(loc(r), "Javascript comment detected.");
+ skipComments(r);
+ } else {
+ r.unread();
+ return;
+ }
+ }
+ }
+ }
+
+ /*
+ * Doesn't actually parse anything, but when positioned at the beginning of comment,
+ * it will move the pointer to the last character in the comment.
+ */
+ private void skipComments(ParserReader r) throws ParseException, IOException {
+ int c = r.read();
+ // "/* */" style comments
+ if (c == '*') {
+ while (c != -1)
+ if ((c = r.read()) == '*')
+ if ((c = r.read()) == '/')
+ return;
+ // "//" style comments
+ } else if (c == '/') {
+ while (c != -1) {
+ c = r.read();
+ if (c == -1 || c == '\n')
+ return;
+ }
+ }
+ throw new ParseException(loc(r), "Open ended comment.");
+ }
+
+ /*
+ * Call this method after you've finished a parsing a string to make sure that if there's any
+ * remainder in the input, that it consists only of whitespace and comments.
+ */
+ private void validateEnd(ParserReader r) throws Exception {
+ skipCommentsAndSpace(r);
+ int c = r.read();
+ if (c != -1 && c != ';') // var x = {...}; expressions can end with a semicolon.
+ throw new ParseException(loc(r), "Remainder after parse: ''{0}''.", (char)c);
+ }
+
+ private ObjectMap loc(ParserReader r) {
+ return getLastLocation().append("line", r.getLine()).append("column", r.getColumn());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializer.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializer.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializer.java
new file mode 100644
index 0000000..c8598b5
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializer.java
@@ -0,0 +1,146 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.serializer.*;
+
+/**
+ * Serializes POJO models to JSON.
+ *
+ * <h5 class='section'>Media types:</h5>
+ *
+ * Handles <code>Accept</code> types: <code>application/json, text/json</code>
+ * <p>
+ * Produces <code>Content-Type</code> types: <code>application/json</code>
+ *
+ * <h5 class='section'>Description:</h5>
+ *
+ * The conversion is as follows...
+ * <ul class='spaced-list'>
+ * <li>
+ * Maps (e.g. {@link HashMap HashMaps}, {@link TreeMap TreeMaps}) are converted to JSON objects.
+ * <li>
+ * Collections (e.g. {@link HashSet HashSets}, {@link LinkedList LinkedLists}) and Java arrays are converted to
+ * JSON arrays.
+ * <li>
+ * {@link String Strings} are converted to JSON strings.
+ * <li>
+ * {@link Number Numbers} (e.g. {@link Integer}, {@link Long}, {@link Double}) are converted to JSON numbers.
+ * <li>
+ * {@link Boolean Booleans} are converted to JSON booleans.
+ * <li>
+ * {@code nulls} are converted to JSON nulls.
+ * <li>
+ * {@code arrays} are converted to JSON arrays.
+ * <li>
+ * {@code beans} are converted to JSON objects.
+ * </ul>
+ *
+ * <p>
+ * The types above are considered "JSON-primitive" object types.
+ * Any non-JSON-primitive object types are transformed into JSON-primitive object types through
+ * {@link org.apache.juneau.transform.PojoSwap PojoSwaps} associated through the
+ * {@link CoreObjectBuilder#pojoSwaps(Class...)} method.
+ * Several default transforms are provided for transforming Dates, Enums, Iterators, etc...
+ *
+ * <p>
+ * This serializer provides several serialization options.
+ * Typically, one of the predefined DEFAULT serializers will be sufficient.
+ * However, custom serializers can be constructed to fine-tune behavior.
+ *
+ * <h5 class='section'>Configurable properties:</h5>
+ *
+ * This class has the following properties associated with it:
+ * <ul>
+ * <li>{@link YamlSerializerContext}
+ * <li>{@link SerializerContext}
+ * <li>{@link BeanContext}
+ * </ul>
+ *
+ * <h5 class='section'>Example:</h5>
+ * <p class='bcode'>
+ * <jc>// Use one of the default serializers to serialize a POJO</jc>
+ * String json = JsonSerializer.<jsf>DEFAULT</jsf>.serialize(someObject);
+ *
+ * <jc>// Create a custom serializer for lax syntax using single quote characters</jc>
+ * JsonSerializer serializer = <jk>new</jk> JsonSerializerBuilder().simple().sq().build();
+ *
+ * <jc>// Clone an existing serializer and modify it to use single-quotes</jc>
+ * JsonSerializer serializer = JsonSerializer.<jsf>DEFAULT</jsf>.builder().sq().build();
+ *
+ * <jc>// Serialize a POJO to JSON</jc>
+ * String json = serializer.serialize(someObject);
+ * </p>
+ */
+public class YamlSerializer extends WriterSerializer {
+
+ /** Default serializer, all default settings.*/
+ public static final YamlSerializer DEFAULT = new YamlSerializer(PropertyStore.create());
+
+
+ final YamlSerializerContext ctx;
+
+ /**
+ * Constructor.
+ *
+ * @param propertyStore
+ * The property store containing all the settings for this object.
+ */
+ public YamlSerializer(PropertyStore propertyStore) {
+ this(propertyStore, "application/yaml", "application/yaml", "application/yaml+*", "text/yaml", "text/yaml+*");
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param propertyStore
+ * The property store containing all the settings for this object.
+ * @param produces
+ * The media type that this serializer produces.
+ * @param accept
+ * The accept media types that the serializer can handle.
+ * <p>
+ * Can contain meta-characters per the <code>media-type</code> specification of
+ * <a class="doclink" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">RFC2616/14.1</a>
+ * <p>
+ * If empty, then assumes the only media type supported is <code>produces</code>.
+ * <p>
+ * For example, if this serializer produces <js>"application/json"</js> but should handle media types of
+ * <js>"application/json"</js> and <js>"text/json"</js>, then the arguments should be:
+ * <br><code><jk>super</jk>(propertyStore, <js>"application/json"</js>, <js>"application/json"</js>, <js>"text/json"</js>);</code>
+ * <br>...or...
+ * <br><code><jk>super</jk>(propertyStore, <js>"application/json"</js>, <js>"*​/json"</js>);</code>
+ */
+ public YamlSerializer(PropertyStore propertyStore, String produces, String...accept) {
+ super(propertyStore, produces, accept);
+ this.ctx = createContext(YamlSerializerContext.class);
+ }
+
+ @Override /* CoreObject */
+ public YamlSerializerBuilder builder() {
+ return new YamlSerializerBuilder(propertyStore);
+ }
+
+
+ //--------------------------------------------------------------------------------
+ // Entry point methods
+ //--------------------------------------------------------------------------------
+
+ @Override /* Serializer */
+ public WriterSerializerSession createSession(SerializerSessionArgs args) {
+ return new YamlSerializerSession(ctx, args);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerBuilder.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerBuilder.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerBuilder.java
new file mode 100644
index 0000000..69bdcb4
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerBuilder.java
@@ -0,0 +1,658 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import static org.apache.juneau.json.JsonSerializerContext.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.http.*;
+import org.apache.juneau.serializer.*;
+
+/**
+ * Builder class for building instances of JSON serializers.
+ */
+public class YamlSerializerBuilder extends SerializerBuilder {
+
+ /**
+ * Constructor, default settings.
+ */
+ public YamlSerializerBuilder() {
+ super();
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param propertyStore The initial configuration settings for this builder.
+ */
+ public YamlSerializerBuilder(PropertyStore propertyStore) {
+ super(propertyStore);
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializer build() {
+ return new YamlSerializer(propertyStore);
+ }
+
+
+ //--------------------------------------------------------------------------------
+ // Properties
+ //--------------------------------------------------------------------------------
+
+ /**
+ * <b>Configuration property:</b> Simple JSON mode.
+ *
+ * <ul>
+ * <li><b>Name:</b> <js>"JsonSerializer.simpleMode"</js>
+ * <li><b>Data type:</b> <code>Boolean</code>
+ * <li><b>Default:</b> <jk>false</jk>
+ * <li><b>Session-overridable:</b> <jk>true</jk>
+ * </ul>
+ *
+ * <p>
+ * If <jk>true</jk>, JSON attribute names will only be quoted when necessary.
+ * Otherwise, they are always quoted.
+ *
+ * <h5 class='section'>Notes:</h5>
+ * <ul>
+ * <li>This is equivalent to calling <code>property(<jsf>JSON_simpleMode</jsf>, value)</code>.
+ * </ul>
+ *
+ * @param value The new value for this property.
+ * @return This object (for method chaining).
+ * @see YamlSerializerContext#JSON_simpleMode
+ */
+ public YamlSerializerBuilder simple(boolean value) {
+ return property(JSON_simpleMode, value);
+ }
+
+ /**
+ * Shortcut for calling <code>setSimpleMode(<jk>true</jk>).sq()</code>.
+ *
+ * @return This object (for method chaining).
+ */
+ public YamlSerializerBuilder simple() {
+ return simple(true).sq();
+ }
+
+ /**
+ * <b>Configuration property:</b> Prefix solidus <js>'/'</js> characters with escapes.
+ *
+ * <ul>
+ * <li><b>Name:</b> <js>"JsonSerializer.escapeSolidus"</js>
+ * <li><b>Data type:</b> <code>Boolean</code>
+ * <li><b>Default:</b> <jk>false</jk>
+ * <li><b>Session-overridable:</b> <jk>true</jk>
+ * </ul>
+ *
+ * <p>
+ * If <jk>true</jk>, solidus (e.g. slash) characters should be escaped.
+ * The JSON specification allows for either format.
+ * However, if you're embedding JSON in an HTML script tag, this setting prevents confusion when trying to
+ * serialize <xt><\/script></xt>.
+ *
+ * <h5 class='section'>Notes:</h5>
+ * <ul>
+ * <li>This is equivalent to calling <code>property(<jsf>JSON_escapeSolidus</jsf>, value)</code>.
+ * </ul>
+ *
+ * @param value The new value for this property.
+ * @return This object (for method chaining).
+ * @see YamlSerializerContext#JSON_escapeSolidus
+ */
+ public YamlSerializerBuilder escapeSolidus(boolean value) {
+ return property(JSON_escapeSolidus, value);
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder maxDepth(int value) {
+ super.maxDepth(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder initialDepth(int value) {
+ super.initialDepth(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder detectRecursions(boolean value) {
+ super.detectRecursions(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder ignoreRecursions(boolean value) {
+ super.ignoreRecursions(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder useWhitespace(boolean value) {
+ super.useWhitespace(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder ws() {
+ super.ws();
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder maxIndent(int value) {
+ super.maxIndent(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder addBeanTypeProperties(boolean value) {
+ super.addBeanTypeProperties(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder quoteChar(char value) {
+ super.quoteChar(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder sq() {
+ super.sq();
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder trimNullProperties(boolean value) {
+ super.trimNullProperties(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder trimEmptyCollections(boolean value) {
+ super.trimEmptyCollections(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder trimEmptyMaps(boolean value) {
+ super.trimEmptyMaps(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder trimStrings(boolean value) {
+ super.trimStrings(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder uriContext(UriContext value) {
+ super.uriContext(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder uriResolution(UriResolution value) {
+ super.uriResolution(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder uriRelativity(UriRelativity value) {
+ super.uriRelativity(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder sortCollections(boolean value) {
+ super.sortCollections(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder sortMaps(boolean value) {
+ super.sortMaps(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder abridged(boolean value) {
+ super.abridged(value);
+ return this;
+ }
+
+ @Override /* SerializerBuilder */
+ public YamlSerializerBuilder listener(Class<? extends SerializerListener> value) {
+ super.listener(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beansRequireDefaultConstructor(boolean value) {
+ super.beansRequireDefaultConstructor(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beansRequireSerializable(boolean value) {
+ super.beansRequireSerializable(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beansRequireSettersForGetters(boolean value) {
+ super.beansRequireSettersForGetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beansRequireSomeProperties(boolean value) {
+ super.beansRequireSomeProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanMapPutReturnsOldValue(boolean value) {
+ super.beanMapPutReturnsOldValue(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanConstructorVisibility(Visibility value) {
+ super.beanConstructorVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanClassVisibility(Visibility value) {
+ super.beanClassVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanFieldVisibility(Visibility value) {
+ super.beanFieldVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder methodVisibility(Visibility value) {
+ super.methodVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder useJavaBeanIntrospector(boolean value) {
+ super.useJavaBeanIntrospector(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder useInterfaceProxies(boolean value) {
+ super.useInterfaceProxies(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder ignoreUnknownBeanProperties(boolean value) {
+ super.ignoreUnknownBeanProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder ignoreUnknownNullBeanProperties(boolean value) {
+ super.ignoreUnknownNullBeanProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder ignorePropertiesWithoutSetters(boolean value) {
+ super.ignorePropertiesWithoutSetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder ignoreInvocationExceptionsOnGetters(boolean value) {
+ super.ignoreInvocationExceptionsOnGetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder ignoreInvocationExceptionsOnSetters(boolean value) {
+ super.ignoreInvocationExceptionsOnSetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder sortProperties(boolean value) {
+ super.sortProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder notBeanPackages(String...values) {
+ super.notBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder notBeanPackages(Collection<String> values) {
+ super.notBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setNotBeanPackages(String...values) {
+ super.setNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setNotBeanPackages(Collection<String> values) {
+ super.setNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeNotBeanPackages(String...values) {
+ super.removeNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeNotBeanPackages(Collection<String> values) {
+ super.removeNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder notBeanClasses(Class<?>...values) {
+ super.notBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder notBeanClasses(Collection<Class<?>> values) {
+ super.notBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setNotBeanClasses(Class<?>...values) {
+ super.setNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setNotBeanClasses(Collection<Class<?>> values) {
+ super.setNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeNotBeanClasses(Class<?>...values) {
+ super.removeNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeNotBeanClasses(Collection<Class<?>> values) {
+ super.removeNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanFilters(Class<?>...values) {
+ super.beanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanFilters(Collection<Class<?>> values) {
+ super.beanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setBeanFilters(Class<?>...values) {
+ super.setBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setBeanFilters(Collection<Class<?>> values) {
+ super.setBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeBeanFilters(Class<?>...values) {
+ super.removeBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeBeanFilters(Collection<Class<?>> values) {
+ super.removeBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder pojoSwaps(Class<?>...values) {
+ super.pojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder pojoSwaps(Collection<Class<?>> values) {
+ super.pojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setPojoSwaps(Class<?>...values) {
+ super.setPojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setPojoSwaps(Collection<Class<?>> values) {
+ super.setPojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removePojoSwaps(Class<?>...values) {
+ super.removePojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removePojoSwaps(Collection<Class<?>> values) {
+ super.removePojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder implClasses(Map<Class<?>,Class<?>> values) {
+ super.implClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public <T> YamlSerializerBuilder implClass(Class<T> interfaceClass, Class<? extends T> implClass) {
+ super.implClass(interfaceClass, implClass);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder includeProperties(Map<String,String> values) {
+ super.includeProperties(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder includeProperties(String beanClassName, String properties) {
+ super.includeProperties(beanClassName, properties);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder includeProperties(Class<?> beanClass, String properties) {
+ super.includeProperties(beanClass, properties);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder excludeProperties(Map<String,String> values) {
+ super.excludeProperties(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder excludeProperties(String beanClassName, String properties) {
+ super.excludeProperties(beanClassName, properties);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder excludeProperties(Class<?> beanClass, String properties) {
+ super.excludeProperties(beanClass, properties);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanDictionary(Class<?>...values) {
+ super.beanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanDictionary(Collection<Class<?>> values) {
+ super.beanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setBeanDictionary(Class<?>...values) {
+ super.setBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder setBeanDictionary(Collection<Class<?>> values) {
+ super.setBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeFromBeanDictionary(Class<?>...values) {
+ super.removeFromBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeFromBeanDictionary(Collection<Class<?>> values) {
+ super.removeFromBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder beanTypePropertyName(String value) {
+ super.beanTypePropertyName(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder defaultParser(Class<?> value) {
+ super.defaultParser(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder locale(Locale value) {
+ super.locale(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder timeZone(TimeZone value) {
+ super.timeZone(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder mediaType(MediaType value) {
+ super.mediaType(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder debug() {
+ super.debug();
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder property(String name, Object value) {
+ super.property(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder properties(Map<String,Object> properties) {
+ super.properties(properties);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder addToProperty(String name, Object value) {
+ super.addToProperty(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder putToProperty(String name, Object key, Object value) {
+ super.putToProperty(name, key, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder putToProperty(String name, Object value) {
+ super.putToProperty(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder removeFromProperty(String name, Object value) {
+ super.removeFromProperty(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder classLoader(ClassLoader classLoader) {
+ super.classLoader(classLoader);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlSerializerBuilder apply(PropertyStore copyFrom) {
+ super.apply(copyFrom);
+ return this;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerContext.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerContext.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerContext.java
new file mode 100644
index 0000000..5714d42
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerContext.java
@@ -0,0 +1,130 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import org.apache.juneau.*;
+import org.apache.juneau.serializer.*;
+
+/**
+ * Configurable properties on the {@link YamlSerializer} class.
+ *
+ * <p>
+ * Context properties are set by calling {@link PropertyStore#setProperty(String, Object)} on the property store
+ * passed into the constructor.
+ *
+ * <p>
+ * See {@link PropertyStore} for more information about context properties.
+ *
+ * <h6 class='topic'>Inherited configurable properties</h6>
+ * <ul class='doctree'>
+ * <li class='jc'>
+ * <a class="doclink" href="../BeanContext.html#ConfigProperties">BeanContext</a>
+ * - Properties associated with handling beans on serializers and parsers.
+ * <ul>
+ * <li class='jc'>
+ * <a class="doclink" href="../serializer/SerializerContext.html#ConfigProperties">SerializerContext</a>
+ * - Configurable properties common to all serializers.
+ * </ul>
+ * </li>
+ * </ul>
+ */
+public final class YamlSerializerContext extends SerializerContext {
+
+ /**
+ * <b>Configuration property:</b> Simple JSON mode.
+ *
+ * <ul>
+ * <li><b>Name:</b> <js>"JsonSerializer.simpleMode"</js>
+ * <li><b>Data type:</b> <code>Boolean</code>
+ * <li><b>Default:</b> <jk>false</jk>
+ * <li><b>Session-overridable:</b> <jk>true</jk>
+ * </ul>
+ *
+ * <p>
+ * If <jk>true</jk>, JSON attribute names will only be quoted when necessary.
+ * Otherwise, they are always quoted.
+ */
+ public static final String JSON_simpleMode = "JsonSerializer.simpleMode";
+
+ /**
+ * <b>Configuration property:</b> Prefix solidus <js>'/'</js> characters with escapes.
+ *
+ * <ul>
+ * <li><b>Name:</b> <js>"JsonSerializer.escapeSolidus"</js>
+ * <li><b>Data type:</b> <code>Boolean</code>
+ * <li><b>Default:</b> <jk>false</jk>
+ * <li><b>Session-overridable:</b> <jk>true</jk>
+ * </ul>
+ *
+ * <p>
+ * If <jk>true</jk>, solidus (e.g. slash) characters should be escaped.
+ * The JSON specification allows for either format.
+ * However, if you're embedding JSON in an HTML script tag, this setting prevents confusion when trying to serialize
+ * <xt><\/script></xt>.
+ */
+ public static final String JSON_escapeSolidus = "JsonSerializer.escapeSolidus";
+
+ /**
+ * <b>Configuration property:</b> Add <js>"_type"</js> properties when needed.
+ *
+ * <ul>
+ * <li><b>Name:</b> <js>"JsonSerializer.addBeanTypeProperties"</js>
+ * <li><b>Data type:</b> <code>Boolean</code>
+ * <li><b>Default:</b> <jk>false</jk>
+ * <li><b>Session-overridable:</b> <jk>true</jk>
+ * </ul>
+ *
+ * <p>
+ * If <jk>true</jk>, then <js>"_type"</js> properties will be added to beans if their type cannot be inferred
+ * through reflection.
+ * This is used to recreate the correct objects during parsing if the object types cannot be inferred.
+ * For example, when serializing a {@code Map<String,Object>} field, where the bean class cannot be determined from
+ * the value type.
+ *
+ * <p>
+ * When present, this value overrides the {@link SerializerContext#SERIALIZER_addBeanTypeProperties} setting and is
+ * provided to customize the behavior of specific serializers in a {@link SerializerGroup}.
+ */
+ public static final String JSON_addBeanTypeProperties = "JsonSerializer.addBeanTypeProperties";
+
+ final boolean
+ simpleMode,
+ escapeSolidus,
+ addBeanTypeProperties;
+
+ /**
+ * Constructor.
+ *
+ * <p>
+ * Typically only called from {@link PropertyStore#getContext(Class)}.
+ *
+ * @param ps The property store that created this context.
+ */
+ public YamlSerializerContext(PropertyStore ps) {
+ super(ps);
+ simpleMode = ps.getProperty(JSON_simpleMode, boolean.class, false);
+ escapeSolidus = ps.getProperty(JSON_escapeSolidus, boolean.class, false);
+ addBeanTypeProperties = ps.getProperty(JSON_addBeanTypeProperties, boolean.class,
+ ps.getProperty(SERIALIZER_addBeanTypeProperties, boolean.class, true));
+ }
+
+ @Override /* Context */
+ public ObjectMap asMap() {
+ return super.asMap()
+ .append("JsonSerializerContext", new ObjectMap()
+ .append("simpleMode", simpleMode)
+ .append("escapeSolidus", escapeSolidus)
+ .append("addBeanTypeProperties", addBeanTypeProperties)
+ );
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerSession.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerSession.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerSession.java
new file mode 100644
index 0000000..1f252c9
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlSerializerSession.java
@@ -0,0 +1,244 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import static org.apache.juneau.json.JsonSerializerContext.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transform.*;
+
+/**
+ * Session object that lives for the duration of a single use of {@link YamlSerializer}.
+ *
+ * <p>
+ * This class is NOT thread safe.
+ * It is typically discarded after one-time use although it can be reused within the same thread.
+ */
+public class YamlSerializerSession extends WriterSerializerSession {
+
+ private final boolean
+ addBeanTypeProperties;
+
+ /**
+ * Create a new session using properties specified in the context.
+ *
+ * @param ctx
+ * The context creating this session object.
+ * The context contains all the configuration settings for this object.
+ * @param args
+ * Runtime arguments.
+ * These specify session-level information such as locale and URI context.
+ * It also include session-level properties that override the properties defined on the bean and
+ * serializer contexts.
+ */
+ protected YamlSerializerSession(YamlSerializerContext ctx, SerializerSessionArgs args) {
+ super(ctx, args);
+ ObjectMap p = getProperties();
+ if (p.isEmpty()) {
+ addBeanTypeProperties = ctx.addBeanTypeProperties;
+ } else {
+ addBeanTypeProperties = p.getBoolean(JSON_addBeanTypeProperties, ctx.addBeanTypeProperties);
+ }
+ }
+
+
+ @Override /* SerializerSesssion */
+ protected void doSerialize(SerializerPipe out, Object o) throws Exception {
+ serializeAnything(getJsonWriter(out), o, getExpectedRootType(o), "root", null);
+ }
+
+ /*
+ * Workhorse method.
+ * Determines the type of object, and then calls the appropriate type-specific serialization method.
+ */
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ SerializerWriter serializeAnything(YamlWriter out, Object o, ClassMeta<?> eType, String attrName, BeanPropertyMeta pMeta) throws Exception {
+
+ if (o == null) {
+ out.append("~");
+ return out;
+ }
+
+ if (eType == null)
+ eType = object();
+
+ ClassMeta<?> aType; // The actual type
+ ClassMeta<?> sType; // The serialized type
+
+ aType = push(attrName, o, eType);
+ boolean isRecursion = aType == null;
+
+ // Handle recursion
+ if (aType == null) {
+ o = null;
+ aType = object();
+ }
+
+ sType = aType;
+ String typeName = getBeanTypeName(eType, aType, pMeta);
+
+ // Swap if necessary
+ PojoSwap swap = aType.getPojoSwap(this);
+ if (swap != null) {
+ o = swap.swap(this, o);
+ sType = swap.getSwapClassMeta(this);
+
+ // If the getSwapClass() method returns Object, we need to figure out
+ // the actual type now.
+ if (sType.isObject())
+ sType = getClassMetaForObject(o);
+ }
+
+ // '\0' characters are considered null.
+ if (o == null || (sType.isChar() && ((Character)o).charValue() == 0))
+ out.append("~");
+ else if (sType.isNumber() || sType.isBoolean())
+ out.append(o);
+ else if (sType.isBean())
+ serializeBeanMap(out, toBeanMap(o), typeName);
+ else if (sType.isUri() || (pMeta != null && pMeta.isUri()))
+ out.uriValue(o);
+ else if (sType.isMap()) {
+ if (o instanceof BeanMap)
+ serializeBeanMap(out, (BeanMap)o, typeName);
+ else
+ serializeMap(out, (Map)o, eType);
+ }
+ else if (sType.isCollection()) {
+ serializeCollection(out, (Collection) o, eType);
+ }
+ else if (sType.isArray()) {
+ serializeCollection(out, toList(sType.getInnerClass(), o), eType);
+ }
+ else if (sType.isReader() || sType.isInputStream()) {
+ IOUtils.pipe(o, out);
+ }
+ else
+ out.stringValue(toString(o));
+
+ if (! isRecursion)
+ pop();
+ return out;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private SerializerWriter serializeMap(YamlWriter out, Map m, ClassMeta<?> type) throws Exception {
+
+ ClassMeta<?> keyType = type.getKeyType(), valueType = type.getValueType();
+
+ m = sort(m);
+
+ int i = indent;
+
+ Iterator mapEntries = m.entrySet().iterator();
+
+ while (mapEntries.hasNext()) {
+ Map.Entry e = (Map.Entry) mapEntries.next();
+ Object value = e.getValue();
+
+ Object key = generalize(e.getKey(), keyType);
+
+ out.attr(toString(key)).append(':').s();
+
+ serializeAnything(out, value, valueType, (key == null ? null : toString(key)), null);
+
+ if (mapEntries.hasNext())
+ out.nl(i);
+ }
+
+ out.cre(i-1);
+
+ return out;
+ }
+
+ private SerializerWriter serializeBeanMap(YamlWriter out, BeanMap<?> m, String typeName) throws Exception {
+ int i = indent;
+ out.append('{');
+
+ boolean addComma = false;
+ for (BeanPropertyValue p : m.getValues(isTrimNulls(), typeName != null ? createBeanTypeNameProperty(m, typeName) : null)) {
+ BeanPropertyMeta pMeta = p.getMeta();
+ ClassMeta<?> cMeta = p.getClassMeta();
+ String key = p.getName();
+ Object value = p.getValue();
+ Throwable t = p.getThrown();
+ if (t != null)
+ onBeanGetterException(pMeta, t);
+
+ if (canIgnoreValue(cMeta, key, value))
+ continue;
+
+ if (addComma)
+ out.append(',').smi(i);
+
+ out.cr(i).attr(key).append(':').s(i);
+
+ serializeAnything(out, value, cMeta, key, pMeta);
+
+ addComma = true;
+ }
+ out.cre(i-1).append('}');
+ return out;
+ }
+
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ private SerializerWriter serializeCollection(YamlWriter out, Collection c, ClassMeta<?> type) throws Exception {
+
+ ClassMeta<?> elementType = type.getElementType();
+
+ c = sort(c);
+
+ out.append('[');
+
+ for (Iterator i = c.iterator(); i.hasNext();) {
+ Object value = i.next();
+ out.cr(indent);
+ serializeAnything(out, value, elementType, "<iterator>", null);
+ if (i.hasNext())
+ out.append(',').smi(indent);
+ }
+ out.cre(indent-1).append(']');
+ return out;
+ }
+
+
+ /**
+ * Returns the {@link YamlSerializerContext#JSON_addBeanTypeProperties} setting value for this session.
+ *
+ * @return The {@link YamlSerializerContext#JSON_addBeanTypeProperties} setting value for this session.
+ */
+ @Override /* SerializerSession */
+ protected final boolean isAddBeanTypeProperties() {
+ return addBeanTypeProperties;
+ }
+
+ /**
+ * Converts the specified output target object to an {@link YamlWriter}.
+ *
+ * @param out The output target object.
+ * @return The output target object wrapped in an {@link YamlWriter}.
+ * @throws Exception
+ */
+ protected final YamlWriter getJsonWriter(SerializerPipe out) throws Exception {
+ Object output = out.getRawOutput();
+ if (output instanceof YamlWriter)
+ return (YamlWriter)output;
+ YamlWriter w = new YamlWriter(out.getWriter(), getQuoteChar(), isTrimStrings(), getUriResolver());
+ out.setWriter(w);
+ return w;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlWriter.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlWriter.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlWriter.java
new file mode 100644
index 0000000..f9345b0
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlWriter.java
@@ -0,0 +1,288 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import java.io.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.serializer.*;
+
+/**
+ * Specialized writer for serializing JSON.
+ *
+ * <h5 class='section'>Notes:</h5>
+ * <ul>
+ * <li>This class is not intended for external use.
+ * </ul>
+ */
+public final class YamlWriter extends SerializerWriter {
+
+ // Characters that trigger special handling of serializing attribute values.
+ private static final AsciiSet
+ encodedChars = new AsciiSet("\n\t\b\f\r'\"\\");
+
+ private static final KeywordSet reservedWords = new KeywordSet(
+ "y","Y","yes","Yes","YES","n","N","no","No","NO",
+ "true","True","TRUE","false","False","FALSE",
+ "on","On","ON","off","Off","OFF"
+ );
+
+
+
+ // Characters that represent attribute name characters that don't trigger quoting.
+ // These are actually more strict than the actual Javascript specification, but
+ // can be narrowed in the future if necessary.
+ // For example, we quote attributes that start with $ even though we don't need to.
+ private static final AsciiSet validAttrChars = new AsciiSet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_");
+ private static final AsciiSet validFirstAttrChars = new AsciiSet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_");
+
+ private final AsciiSet ec;
+
+ /**
+ * Constructor.
+ *
+ * @param out The writer being wrapped.
+ * @param quoteChar The quote character to use (i.e. <js>'\''</js> or <js>'"'</js>)
+ * @param trimStrings If <jk>true</jk>, strings will be trimmed before being serialized.
+ * @param uriResolver The URI resolver for resolving URIs to absolute or root-relative form.
+ */
+ protected YamlWriter(Writer out, char quoteChar, boolean trimStrings, UriResolver uriResolver) {
+ super(out, true, Integer.MAX_VALUE, trimStrings, quoteChar, uriResolver);
+ this.ec = encodedChars;
+ }
+
+ /**
+ * Serializes the specified object as a JSON string value.
+ *
+ * @param s The object being serialized.
+ * @return This object (for method chaining).
+ * @throws IOException Should never happen.
+ */
+ public YamlWriter stringValue(String s) throws IOException {
+ if (s == null)
+ return this;
+ boolean doConvert = false;
+ for (int i = 0; i < s.length() && ! doConvert; i++) {
+ char c = s.charAt(i);
+ doConvert |= ec.contains(c);
+ }
+ q();
+ if (! doConvert) {
+ out.append(s);
+ } else {
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (ec.contains(c)) {
+ if (c == '\n')
+ out.append('\\').append('n');
+ else if (c == '\t')
+ out.append('\\').append('t');
+ else if (c == '\b')
+ out.append('\\').append('b');
+ else if (c == '\f')
+ out.append('\\').append('f');
+ else if (c == quoteChar)
+ out.append('\\').append(quoteChar);
+ else if (c == '\\')
+ out.append('\\').append('\\');
+ else if (c != '\r')
+ out.append(c);
+ } else {
+ out.append(c);
+ }
+ }
+ }
+ q();
+ return this;
+ }
+
+ /**
+ * Serializes the specified object as a JSON attribute name.
+ *
+ * @param s The object being serialized.
+ * @return This object (for method chaining).
+ * @throws IOException Should never happen.
+ */
+ public YamlWriter attr(String s) throws IOException {
+ /*
+ * Converts a Java string to an acceptable JSON attribute name. If
+ * useStrictJson is false, then quotes will only be used if the attribute
+ * name consists of only alphanumeric characters.
+ */
+ boolean doConvert = false; // Always convert when not in lax mode.
+
+ // If the attribute is null, it must always be printed as null without quotes.
+ // Technically, this isn't part of the JSON spec, but it does allow for null key values.
+ if (s == null) {
+ s = "~";
+ doConvert = false;
+
+ } else {
+
+ // Look for characters that would require the attribute to be quoted.
+ // All possible numbers should be caught here.
+ if (! doConvert) {
+ for (int i = 0; i < s.length() && ! doConvert; i++) {
+ char c = s.charAt(i);
+ doConvert |= ! (i == 0 ? validFirstAttrChars.contains(c) : validAttrChars.contains(c));
+ }
+ }
+
+ // Reserved words and blanks must be quoted.
+ if (! doConvert) {
+ if (s.isEmpty() || reservedWords.contains(s))
+ doConvert = true;
+ }
+ }
+
+ // If no conversion necessary, just print the attribute as-is.
+ if (doConvert)
+ stringValue(s);
+ else
+ out.append(s);
+
+ return this;
+ }
+
+ /**
+ * Appends a URI to the output.
+ *
+ * @param uri The URI to append to the output.
+ * @return This object (for method chaining).
+ * @throws IOException
+ */
+ public SerializerWriter uriValue(Object uri) throws IOException {
+ return stringValue(uriResolver.resolve(uri));
+ }
+
+ //--------------------------------------------------------------------------------
+ // Overridden methods
+ //--------------------------------------------------------------------------------
+
+ @Override /* SerializerWriter */
+ public YamlWriter cr(int depth) throws IOException {
+ super.cr(depth);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter cre(int depth) throws IOException {
+ super.cre(depth);
+ return this;
+ }
+
+ /**
+ * Performs an indentation only if we're currently past max indentation.
+ *
+ * @param depth The current indentation depth.
+ * @return This object (for method chaining).
+ * @throws IOException
+ */
+ public YamlWriter smi(int depth) throws IOException {
+ if (depth > maxIndent)
+ super.s();
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter appendln(int indent, String text) throws IOException {
+ super.appendln(indent, text);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter appendln(String text) throws IOException {
+ super.appendln(text);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter append(int indent, String text) throws IOException {
+ super.append(indent, text);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter append(int indent, char c) throws IOException {
+ super.append(indent, c);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter s() throws IOException {
+ super.s();
+ return this;
+ }
+
+ /**
+ * Adds a space only if the current indentation level is below maxIndent.
+ *
+ * @param indent
+ * @return This object (for method chaining).
+ * @throws IOException
+ */
+ public YamlWriter s(int indent) throws IOException {
+ if (indent <= maxIndent)
+ super.s();
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter q() throws IOException {
+ super.q();
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter i(int indent) throws IOException {
+ super.i(indent);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter nl(int indent) throws IOException {
+ super.nl(indent);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter append(Object text) throws IOException {
+ super.append(text);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter append(String text) throws IOException {
+ super.append(text);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter appendIf(boolean b, String text) throws IOException {
+ super.appendIf(b, text);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter appendIf(boolean b, char c) throws IOException {
+ super.appendIf(b, c);
+ return this;
+ }
+
+ @Override /* SerializerWriter */
+ public YamlWriter append(char c) throws IOException {
+ super.append(c);
+ return this;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/Yaml.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/Yaml.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/Yaml.java
new file mode 100644
index 0000000..08e2e50
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/Yaml.java
@@ -0,0 +1,36 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto.annotation;
+
+import static java.lang.annotation.ElementType.*;
+import static java.lang.annotation.RetentionPolicy.*;
+
+import java.lang.annotation.*;
+
+/**
+ * Annotation for specifying various YAML options for the YAML serializers and parsers.
+ *
+ * <p>
+ * Can be applied to Java types.
+ *
+ * <p>
+ * Can be used for the following:
+ * <ul class='spaced-list'>
+ * </ul>
+ */
+@Documented
+@Target({TYPE})
+@Retention(RUNTIME)
+@Inherited
+public @interface Yaml {
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/package.html
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/package.html b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/package.html
new file mode 100644
index 0000000..df41b35
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/annotation/package.html
@@ -0,0 +1,41 @@
+<!DOCTYPE HTML>
+<!--
+/***************************************************************************************************************************
+ * 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.
+ *
+ ***************************************************************************************************************************/
+ -->
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <style type="text/css">
+ /* For viewing in Page Designer */
+ @IMPORT url("../../../../../../../javadoc.css");
+
+ /* For viewing in REST interface */
+ @IMPORT url("../htdocs/javadoc.css");
+ body {
+ margin: 20px;
+ }
+ </style>
+ <script>
+ /* Replace all @code and @link tags. */
+ window.onload = function() {
+ document.body.innerHTML = document.body.innerHTML.replace(/\{\@code ([^\}]+)\}/g, '<code>$1</code>');
+ document.body.innerHTML = document.body.innerHTML.replace(/\{\@link (([^\}]+)\.)?([^\.\}]+)\}/g, '<code>$3</code>');
+ }
+ </script>
+</head>
+<body>
+<p>JSON annotations</p>
+</body>
+</html>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_HTML.png
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_HTML.png b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_HTML.png
new file mode 100644
index 0000000..b4a3576
Binary files /dev/null and b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_HTML.png differ
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSON.png
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSON.png b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSON.png
new file mode 100644
index 0000000..13b5c22
Binary files /dev/null and b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSON.png differ
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSchema.png
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSchema.png b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSchema.png
new file mode 100644
index 0000000..bf1cdc6
Binary files /dev/null and b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSchema.png differ
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSimple.png
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSimple.png b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSimple.png
new file mode 100644
index 0000000..935e8a9
Binary files /dev/null and b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/doc-files/Example_JSONSimple.png differ
[3/3] incubator-juneau git commit: YAML prototype.
Posted by ja...@apache.org.
YAML prototype.
Project: http://git-wip-us.apache.org/repos/asf/incubator-juneau/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-juneau/commit/ab8f0faa
Tree: http://git-wip-us.apache.org/repos/asf/incubator-juneau/tree/ab8f0faa
Diff: http://git-wip-us.apache.org/repos/asf/incubator-juneau/diff/ab8f0faa
Branch: refs/heads/master
Commit: ab8f0faaa862c84e344329725bccbb6a4b86ae15
Parents: b89cb98
Author: JamesBognar <ja...@apache.org>
Authored: Sun Sep 24 14:34:21 2017 -0400
Committer: JamesBognar <ja...@apache.org>
Committed: Sun Sep 24 14:34:21 2017 -0400
----------------------------------------------------------------------
.../apache/juneau/utils/KeywordStoreTest.java | 4 -
.../juneau/yaml/proto/CommonParserTest.java | 180 ++++
.../apache/juneau/yaml/proto/CommonTest.java | 339 ++++++
.../juneau/yaml/proto/YamlParserTest.java | 326 ++++++
.../org/apache/juneau/yaml/proto/YamlTest.java | 215 ++++
.../org/apache/juneau/internal/KeywordSet.java | 57 +-
.../org/apache/juneau/internal/SystemUtils.java | 71 ++
.../apache/juneau/yaml/proto/YamlClassMeta.java | 45 +
.../apache/juneau/yaml/proto/YamlParser.java | 163 +++
.../juneau/yaml/proto/YamlParserBuilder.java | 465 ++++++++
.../juneau/yaml/proto/YamlParserContext.java | 61 ++
.../juneau/yaml/proto/YamlParserSession.java | 669 ++++++++++++
.../juneau/yaml/proto/YamlSerializer.java | 146 +++
.../yaml/proto/YamlSerializerBuilder.java | 658 ++++++++++++
.../yaml/proto/YamlSerializerContext.java | 130 +++
.../yaml/proto/YamlSerializerSession.java | 244 +++++
.../apache/juneau/yaml/proto/YamlWriter.java | 288 +++++
.../juneau/yaml/proto/annotation/Yaml.java | 36 +
.../juneau/yaml/proto/annotation/package.html | 41 +
.../yaml/proto/doc-files/Example_HTML.png | Bin 0 -> 35528 bytes
.../yaml/proto/doc-files/Example_JSON.png | Bin 0 -> 26954 bytes
.../yaml/proto/doc-files/Example_JSONSchema.png | Bin 0 -> 34114 bytes
.../yaml/proto/doc-files/Example_JSONSimple.png | Bin 0 -> 30920 bytes
.../org/apache/juneau/yaml/proto/package.html | 1005 ++++++++++++++++++
24 files changed, 5087 insertions(+), 56 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java
index 89ac7b4..a61eb1d 100755
--- a/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java
+++ b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java
@@ -38,9 +38,5 @@ public class KeywordStoreTest {
assertFalse(ks.contains("|a"));
assertFalse(ks.contains("Aa"));
assertFalse(ks.contains("aA"));
-
- for (String s : new String[]{"a","aA","Aa","a|","|a"}) {
- try { ks = new KeywordSet(s); fail(); } catch (IllegalArgumentException e) {}
- }
}
}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonParserTest.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonParserTest.java b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonParserTest.java
new file mode 100755
index 0000000..e8dd392
--- /dev/null
+++ b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonParserTest.java
@@ -0,0 +1,180 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","serial","javadoc"})
+public class CommonParserTest {
+
+ //====================================================================================================
+ // testFromSerializer
+ //====================================================================================================
+ @Test
+ public void testFromSerializer() throws Exception {
+ ReaderParser p = new YamlParserBuilder().beanDictionary(A1.class).build();
+
+ Map m = null;
+ m = (Map)p.parse("{a:1}", Object.class);
+ assertEquals(1, m.get("a"));
+ m = (Map)p.parse("{a:1,b:\"foo bar\"}", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ m = (Map)p.parse("{a:1,b:\"foo bar\",c:false}", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals(false, m.get("c"));
+ m = (Map)p.parse(" { a : 1 , b : 'foo' , c : false } ", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ m = (Map)p.parse("{x:\"org.apache.juneau.test.Person\",addresses:[{x:\"org.apache.juneau.test.Address\",city:\"city A\",state:\"state A\",street:\"street A\",zip:12345}]}", Object.class);
+ assertEquals("org.apache.juneau.test.Person", m.get("x"));
+ List l = (List)m.get("addresses");
+ assertNotNull(l);
+ m = (Map)l.get(0);
+ assertNotNull(m);
+ assertEquals("org.apache.juneau.test.Address", m.get("x"));
+ assertEquals("city A", m.get("city"));
+ assertEquals("state A", m.get("state"));
+ assertEquals("street A", m.get("street"));
+ assertEquals(12345, m.get("zip"));
+
+ ObjectList jl = (ObjectList)p.parse("[{attribute:'value'},{attribute:'value'}]", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+
+ // Verify that all the following return null.
+ assertNull(p.parse((CharSequence)null, Object.class));
+ assertNull(p.parse("", Object.class));
+ assertNull(p.parse(" ", Object.class));
+ assertNull(p.parse(" \t", Object.class));
+ assertNull(p.parse(" /*foo*/", Object.class));
+ assertNull(p.parse(" /*foo*/ ", Object.class));
+ assertNull(p.parse(" //foo ", Object.class));
+
+ try {
+ jl = (ObjectList)p.parse("[{attribute:'value'},{attribute:'value'}]", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+ } catch (Exception e) {
+ fail(e.getLocalizedMessage());
+ }
+
+ A1 b = new A1();
+ A2 tl = new A2();
+ tl.add(new A3("name0","value0"));
+ tl.add(new A3("name1","value1"));
+ b.list = tl;
+ String json = new YamlSerializerBuilder().addBeanTypeProperties(true).beanDictionary(A1.class).build().serialize(b);
+ b = (A1)p.parse(json, Object.class);
+ assertEquals("value1", b.list.get(1).value);
+
+ json = YamlSerializer.DEFAULT.serialize(b);
+ b = p.parse(json, A1.class);
+ assertEquals("value1", b.list.get(1).value);
+ }
+
+ @Bean(typeName="A1")
+ public static class A1 {
+ public A2 list;
+ }
+
+ public static class A2 extends LinkedList<A3> {
+ }
+
+ public static class A3 {
+ public String name, value;
+ public A3(){}
+ public A3(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Correct handling of unknown properties.
+ //====================================================================================================
+ @Test
+ public void testCorrectHandlingOfUnknownProperties() throws Exception {
+ ReaderParser p = new YamlParserBuilder().ignoreUnknownBeanProperties(true).build();
+ B b;
+
+ String in = "{a:1,unknown:3,b:2}";
+ b = p.parse(in, B.class);
+ assertEquals(b.a, 1);
+ assertEquals(b.b, 2);
+
+ try {
+ p = YamlParser.DEFAULT;
+ p.parse(in, B.class);
+ fail("Exception expected");
+ } catch (ParseException e) {}
+ }
+
+ public static class B {
+ public int a, b;
+ }
+
+ //====================================================================================================
+ // Writing to Collection properties with no setters.
+ //====================================================================================================
+ @Test
+ public void testCollectionPropertiesWithNoSetters() throws Exception {
+ YamlParser p = YamlParser.DEFAULT;
+ String json = "{ints:[1,2,3],beans:[{a:1,b:2}]}";
+ C t = p.parse(json, C.class);
+ assertEquals(t.getInts().size(), 3);
+ assertEquals(t.getBeans().get(0).b, 2);
+ }
+
+ public static class C {
+ private Collection<Integer> ints = new LinkedList<Integer>();
+ private List<B> beans = new LinkedList<B>();
+ public Collection<Integer> getInts() {
+ return ints;
+ }
+ public List<B> getBeans() {
+ return beans;
+ }
+ }
+
+ //====================================================================================================
+ // Parser listeners.
+ //====================================================================================================
+ @Test
+ public void testParserListeners() throws Exception {
+ YamlParser p = new YamlParserBuilder().ignoreUnknownBeanProperties(true).listener(MyParserListener.class).build();
+
+ String json = "{a:1,unknownProperty:\"/foo\",b:2}";
+ p.parse(json, B.class);
+ assertEquals(1, MyParserListener.events.size());
+ assertEquals("unknownProperty,1,5", MyParserListener.events.get(0));
+ }
+
+ public static class MyParserListener extends ParserListener {
+ final static List<String> events = new LinkedList<String>();
+
+ @Override /* ParserListener */
+ public <T> void onUnknownBeanProperty(ParserSession session, ParserPipe pipe, String propertyName, Class<T> beanClass, T bean, int line, int col) {
+ events.add(propertyName + "," + line + "," + col);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonTest.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonTest.java b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonTest.java
new file mode 100755
index 0000000..a6e6e7b
--- /dev/null
+++ b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/CommonTest.java
@@ -0,0 +1,339 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.utils.*;
+import org.junit.*;
+
+@SuppressWarnings({"serial","javadoc"})
+@Ignore
+public class CommonTest {
+
+ //====================================================================================================
+ // Trim nulls from beans
+ //====================================================================================================
+ @Test
+ public void testTrimNullsFromBeans() throws Exception {
+ YamlSerializerBuilder s = new YamlSerializerBuilder().simple();
+ YamlParser p = YamlParser.DEFAULT;
+ A t1 = A.create(), t2;
+
+ s.trimNullProperties(false);
+ String r = s.build().serialize(t1);
+ assertEquals("{s1:null,s2:'s2'}", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+
+ s.trimNullProperties(true);
+ r = s.build().serialize(t1);
+ assertEquals("{s2:'s2'}", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ public String s1, s2;
+
+ public static A create() {
+ A t = new A();
+ t.s2 = "s2";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty maps
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyMaps() throws Exception {
+ YamlSerializerBuilder s = new YamlSerializerBuilder().simple();
+ YamlParser p = YamlParser.DEFAULT;
+ B t1 = B.create(), t2;
+ String r;
+
+ s.trimEmptyMaps(false);
+ r = s.build().serialize(t1);
+ assertEquals("{f1:{},f2:{f2a:null,f2b:{s2:'s2'}}}", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+
+ s.trimEmptyMaps(true);
+ r = s.build().serialize(t1);
+ assertEquals("{f2:{f2a:null,f2b:{s2:'s2'}}}", r);
+ t2 = p.parse(r, B.class);
+ assertNull(t2.f1);
+ }
+
+ public static class B {
+ public TreeMap<String,A> f1, f2;
+
+ public static B create() {
+ B t = new B();
+ t.f1 = new TreeMap<String,A>();
+ t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty lists
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyLists() throws Exception {
+ YamlSerializerBuilder s = new YamlSerializerBuilder().simple();
+ YamlParser p = YamlParser.DEFAULT;
+ C t1 = C.create(), t2;
+ String r;
+
+ s.trimEmptyCollections(false);
+ r = s.build().serialize(t1);
+ assertEquals("{f1:[],f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, C.class);
+ assertEqualObjects(t1, t2);
+
+ s.trimEmptyCollections(true);
+ r = s.build().serialize(t1);
+ assertEquals("{f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, C.class);
+ assertNull(t2.f1);
+ }
+
+ public static class C {
+ public List<A> f1, f2;
+
+ public static C create() {
+ C t = new C();
+ t.f1 = new AList<A>();
+ t.f2 = new AList<A>().append(null).append(A.create());
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty arrays
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyArrays() throws Exception {
+ YamlSerializerBuilder s = new YamlSerializerBuilder().simple();
+ YamlParser p = YamlParser.DEFAULT;
+ D t1 = D.create(), t2;
+ String r;
+
+ s.trimEmptyCollections(false);
+ r = s.build().serialize(t1);
+ assertEquals("{f1:[],f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, D.class);
+ assertEqualObjects(t1, t2);
+
+ s.trimEmptyCollections(true);
+ r = s.build().serialize(t1);
+ assertEquals("{f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, D.class);
+ assertNull(t2.f1);
+ }
+
+ public static class D {
+ public A[] f1, f2;
+
+ public static D create() {
+ D t = new D();
+ t.f1 = new A[]{};
+ t.f2 = new A[]{null, A.create()};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperies() throws Exception {
+ YamlSerializer s = YamlSerializer.DEFAULT;
+ E1 t = new E1();
+ String r;
+
+ r = s.serialize(t);
+ assertEquals("{x1:{f1:1},x2:{f1:1},x3:[{f1:1}],x4:[{f1:1}],x5:[{f1:1}],x6:[{f1:1}]}", r);
+ }
+
+ public static class E1 {
+ @BeanProperty(properties="f1") public E2 x1 = new E2();
+ @BeanProperty(properties="f1") public Map<String,Integer> x2 = new AMap<String,Integer>().append("f1",1).append("f2",2);
+ @BeanProperty(properties="f1") public E2[] x3 = {new E2()};
+ @BeanProperty(properties="f1") public List<E2> x4 = new AList<E2>().append(new E2());
+ @BeanProperty(properties="f1") public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
+ @BeanProperty(properties="f1") public List<ObjectMap> x6 = new AList<ObjectMap>().append(new ObjectMap().append("f1",1).append("f2",2));
+ }
+
+ public static class E2 {
+ public int f1 = 1;
+ public int f2 = 2;
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation on list of beans.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperiesOnListOfBeans() throws Exception {
+ YamlSerializer s = YamlSerializer.DEFAULT;
+ List<F> l = new LinkedList<F>();
+ F t = new F();
+ t.x1.add(new F());
+ l.add(t);
+ String json = s.serialize(l);
+ assertEquals("[{x1:[{x2:2}],x2:2}]", json);
+ }
+
+ public static class F {
+ @BeanProperty(properties="x2") public List<F> x1 = new LinkedList<F>();
+ public int x2 = 2;
+ }
+
+ //====================================================================================================
+ // Test that URLs and URIs are serialized and parsed correctly.
+ //====================================================================================================
+ @Test
+ public void testURIAttr() throws Exception {
+ YamlSerializer s = YamlSerializer.DEFAULT;
+ YamlParser p = YamlParser.DEFAULT;
+
+ G t = new G();
+ t.uri = new URI("http://uri");
+ t.f1 = new URI("http://f1");
+ t.f2 = new URL("http://f2");
+
+ String json = s.serialize(t);
+ t = p.parse(json, G.class);
+ assertEquals("http://uri", t.uri.toString());
+ assertEquals("http://f1", t.f1.toString());
+ assertEquals("http://f2", t.f2.toString());
+ }
+
+ public static class G {
+ public URI uri;
+ public URI f1;
+ public URL f2;
+ }
+
+
+ //====================================================================================================
+ // Recursion
+ //====================================================================================================
+ @Test
+ public void testRecursion() throws Exception {
+ YamlSerializerBuilder s = new YamlSerializerBuilder().simple();
+
+ R1 r1 = new R1();
+ R2 r2 = new R2();
+ R3 r3 = new R3();
+ r1.r2 = r2;
+ r2.r3 = r3;
+ r3.r1 = r1;
+
+ // No recursion detection
+ try {
+ s.build().serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
+ }
+
+ // Recursion detection, no ignore
+ s.detectRecursions(true);
+ try {
+ s.build().serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("[0]root:org.apache.juneau.json.CommonTest$R1"));
+ assertTrue(msg.contains("->[1]r2:org.apache.juneau.json.CommonTest$R2"));
+ assertTrue(msg.contains("->[2]r3:org.apache.juneau.json.CommonTest$R3"));
+ assertTrue(msg.contains("->[3]r1:org.apache.juneau.json.CommonTest$R1"));
+ }
+
+ s.ignoreRecursions(true);
+ assertEquals("{name:'foo',r2:{name:'bar',r3:{name:'baz'}}}", s.build().serialize(r1));
+ }
+
+ public static class R1 {
+ public String name = "foo";
+ public R2 r2;
+ }
+ public static class R2 {
+ public String name = "bar";
+ public R3 r3;
+ }
+ public static class R3 {
+ public String name = "baz";
+ public R1 r1;
+ }
+
+ //====================================================================================================
+ // Basic bean
+ //====================================================================================================
+ @Test
+ public void testBasicBean() throws Exception {
+ YamlSerializer s = new YamlSerializerBuilder().simple().trimNullProperties(false).sortProperties(true).build();
+
+ J a = new J();
+ a.setF1("J");
+ a.setF2(100);
+ a.setF3(true);
+ assertEquals("C1", "{f1:'J',f2:100,f3:true}", s.serialize(a));
+ }
+
+ public static class J {
+ private String f1 = null;
+ private int f2 = -1;
+ private boolean f3 = false;
+
+ public String getF1() {
+ return this.f1;
+ }
+
+ public void setF1(String f1) {
+ this.f1 = f1;
+ }
+
+ public int getF2() {
+ return this.f2;
+ }
+
+ public void setF2(int f2) {
+ this.f2 = f2;
+ }
+
+ public boolean isF3() {
+ return this.f3;
+ }
+
+ public void setF3(boolean f3) {
+ this.f3 = f3;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return ("J(f1: " + this.getF1() + ", f2: " + this.getF2() + ")");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlParserTest.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlParserTest.java b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlParserTest.java
new file mode 100755
index 0000000..0b0c667
--- /dev/null
+++ b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlParserTest.java
@@ -0,0 +1,326 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings({"javadoc"})
+@Ignore
+public class YamlParserTest {
+
+ private static final YamlParser p = YamlParser.DEFAULT;
+ private static final YamlParser sp = YamlParser.DEFAULT_STRICT;
+
+
+ //====================================================================================================
+ // Test invalid input
+ //====================================================================================================
+ @Test
+ public void testInvalidYaml() {
+ try {
+ p.parse("{\na:1,\nb:xxx\n}", Object.class);
+ fail("Exception expected.");
+ } catch (ParseException e) {}
+ }
+
+ @Test
+ public void testNonExistentAttribute() throws Exception {
+ String json = "{foo:,bar:}";
+ ObjectMap m = p.parse(json, ObjectMap.class);
+ assertEquals("{foo:null,bar:null}", m.toString());
+ }
+
+ @Test
+ public void testNonStringAsString() throws Exception {
+ String json = "123";
+ String s;
+
+ // Strict mode does not allow unquoted values.
+ try {
+ sp.parse(json, String.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ s = p.parse(json, String.class);
+ assertEquals("123", s);
+
+ json = " 123 ";
+ // Strict mode does not allow unquoted values.
+ try {
+ sp.parse(json, String.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ s = p.parse(json, String.class);
+ assertEquals("123", s);
+
+ json = "{\"fa\":123}";
+ try {
+ sp.parse(json, A.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ A a = p.parse(json, A.class);
+ assertEquals("123", a.fa);
+
+ json = " { \"fa\" : 123 } ";
+ try {
+ sp.parse(json, A.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ a = p.parse(json, A.class);
+ assertEquals("123", a.fa);
+
+ json = "'123'";
+ try {
+ sp.parse(json, String.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Invalid quote character"));
+ }
+ }
+
+ public static class A {
+ public String fa;
+ }
+
+ @Test
+ public void testStrictMode() throws Exception {
+ YamlParser p = sp;
+
+ // Missing attribute values.
+ String json = "{\"foo\":,\"bar\":}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:7}. Missing value detected.", e.getRootCause().getMessage());
+ }
+
+ // Single quoted values.
+ json = "{\"foo\":'bar'}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:8}. Invalid quote character \"'\" being used.", e.getRootCause().getMessage());
+ }
+
+ // Single quoted attribute name.
+ json = "{'foo':\"bar\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:2}. Invalid quote character \"'\" being used.", e.getRootCause().getMessage());
+ }
+
+ // Unquoted attribute name.
+ json = "{foo:\"bar\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:1}. Unquoted attribute detected.", e.getRootCause().getMessage());
+ }
+
+ // Concatenated string
+ json = "{\"foo\":\"bar\"+\"baz\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:12}. String concatenation detected.", e.getRootCause().getMessage());
+ }
+
+ // Concatenated string 2
+ json = "{\"foo\":\"bar\" + \"baz\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:13}. String concatenation detected.", e.getRootCause().getMessage());
+ }
+
+ json = "{\"foo\":/*comment*/\"bar\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:8}. Javascript comment detected.", e.getRootCause().getMessage());
+ }
+ }
+
+ /**
+ * JSON numbers and booleans should be representable as strings and converted accordingly.
+ */
+ @Test
+ public void testPrimitivesAsStrings() throws Exception {
+ String json;
+ ReaderParser p = YamlParser.DEFAULT;
+ WriterSerializer s = YamlSerializer.DEFAULT;
+
+ json = "{f1:'1',f2:'1',f3:'true',f4:'true',f5:'1',f6:'1',f7:'1',f8:'1',f9:'1',f10:'1'}";
+ B b = p.parse(json, B.class);
+ assertEquals("{f1:1,f2:1,f3:true,f4:true,f5:1.0,f6:1.0,f7:1,f8:1,f9:1,f10:1}", s.toString(b));
+
+ json = "{f1:'',f2:'',f3:'',f4:'',f5:'',f6:'',f7:'',f8:'',f9:'',f10:''}";
+ b = p.parse(json, B.class);
+ assertEquals("{f1:0,f2:0,f3:false,f4:false,f5:0.0,f6:0.0,f7:0,f8:0,f9:0,f10:0}", s.toString(b));
+ }
+
+ public static class B {
+ public int f1;
+ public Integer f2;
+ public boolean f3;
+ public Boolean f4;
+ public float f5;
+ public Float f6;
+ public long f7;
+ public Long f8;
+ public byte f9;
+ public Byte f10;
+ }
+
+ //====================================================================================================
+ // testInvalidYamlNumbers
+ // Lax parser allows octal and hexadecimal numbers. Strict parser does not.
+ //====================================================================================================
+ @Test
+ public void testInvalidYamlNumbers() throws Exception {
+ YamlParser p1 = YamlParser.DEFAULT;
+ YamlParser p2 = YamlParser.DEFAULT_STRICT;
+ Number r;
+
+ // Lax allows blank strings interpreted as 0, strict does not.
+ String s = "\"\"";
+ r = p1.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().contains("Invalid JSON number"));
+ }
+
+ // Either should allow 0 or -0.
+ s = "0";
+ r = p1.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+ r = p2.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+
+ s = "-0";
+ r = p1.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+ r = p2.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+
+ // Lax allows 0123 and -0123, strict does not.
+ s = "0123";
+ r = p1.parse(s, Number.class);
+ assertEquals(0123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().contains("Invalid JSON number"));
+ }
+ s = "-0123";
+ r = p1.parse(s, Number.class);
+ assertEquals(-0123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().contains("Invalid JSON number"));
+ }
+
+ // Lax allows 0x123 and -0x123, strict does not.
+ s = "0x123";
+ r = p1.parse(s, Number.class);
+ assertEquals(0x123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().contains("Invalid JSON number"));
+ }
+ s = "-0x123";
+ r = p1.parse(s, Number.class);
+ assertEquals(-0x123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().contains("Invalid JSON number"));
+ }
+ }
+
+ //====================================================================================================
+ // testUnquotedStrings
+ // Lax parser allows unquoted strings if POJO can be converted from a string.
+ //====================================================================================================
+ @Test
+ public void testUnquotedStrings() throws Exception {
+ YamlParser p1 = YamlParser.DEFAULT;
+ YamlParser p2 = YamlParser.DEFAULT_STRICT;
+
+ String s = "foobar";
+ C c = p1.parse(s, C.class);
+ assertEquals("f=foobar", c.toString());
+
+ try {
+ p2.parse(s, C.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ // OK
+ }
+ }
+
+ public static class C {
+ String f;
+ public static C valueOf(String s) {
+ C c = new C();
+ c.f = s;
+ return c;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "f="+f;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlTest.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlTest.java b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlTest.java
new file mode 100755
index 0000000..cf74bf6
--- /dev/null
+++ b/juneau-core/juneau-core-test/src/test/java/org/apache/juneau/yaml/proto/YamlTest.java
@@ -0,0 +1,215 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import org.junit.*;
+
+@SuppressWarnings({"javadoc"})
+public class YamlTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+// Map<String,Object> m = new LinkedHashMap<String,Object>();
+// List<Object> l = new LinkedList<Object>();
+//
+// WriterSerializer s1 = new YamlSerializerBuilder().simple().trimNullProperties(false).build();
+// WriterSerializer s2 = new YamlSerializerBuilder().simple().trimNullProperties(false).quoteChar('"').build();
+// String r;
+//
+// // Null keys and values
+// m.clear();
+// m.put(null, null);
+// m.put("aaa", "bbb");
+// assertEquals("A1", "~: ~,\naaa: bbb\n", s1.serialize(m));
+//
+// // Escapes.
+// // String = ["]
+// m.clear();
+// m.put("x", "[\"]");
+// assertEquals("{x:\"[\\\"]\"}", s2.serialize(m));
+// // String = [\"]
+// // JSON = {x:"\\\""}
+// m.clear();
+// m.put("x", "[\\\"]");
+// assertEquals("{x:\"[\\\\\\\"]\"}", s2.serialize(m));
+//
+// // String = [\w[\w\-\.]{3,}\w]
+// // JSON = {x:"\\w[\\w\\-\\.]{3,}\\w"}
+// m.clear();
+// r = "\\w[\\w\\-\\.]{3,}\\w";
+// m.put("x", r);
+// assertEquals("{x:\"\\\\w[\\\\w\\\\-\\\\.]{3,}\\\\w\"}", s2.serialize(m));
+// assertEquals(r, new ObjectMap(s2.serialize(m)).getString("x"));
+//
+// // String = [foo\bar]
+// // JSON = {x:"foo\\bar"}
+// m.clear();
+// m.put("x", "foo\\bar");
+// assertEquals("{x:\"foo\\\\bar\"}", s2.serialize(m));
+//
+// m.clear();
+// m.put("null", null);
+// m.put("aaa", "bbb");
+// assertEquals("A2", "{'null':null,aaa:'bbb'}", s1.serialize(m));
+//
+// m.clear();
+// m.put(null, "null");
+// m.put("aaa", "bbb");
+// assertEquals("A3", "{null:'null',aaa:'bbb'}", s1.serialize(m));
+//
+// // Arrays
+// m.clear();
+// l.clear();
+// m.put("J", "f1");
+// m.put("B", "b");
+// m.put("C", "c");
+// l.add("1");
+// l.add("2");
+// l.add("3");
+// Object o = new Object[] { m, l };
+// Object o2 = new Object[] { o, "foo", "bar", new Integer(1), new Boolean(false), new Float(1.2), null };
+// assertEquals("K1", "[[{J:'f1',B:'b',C:'c'},['1','2','3']],'foo','bar',1,false,1.2,null]", s1.serialize(o2));
+ }
+
+// @Test
+// public void testReservedKeywordAttributes() throws Exception {
+// Map<String,Object> m = new LinkedHashMap<String,Object>();
+//
+// // Keys with reserved names.
+// for (String attr : new String[]{"","true","false","null","try","123","1x","-123",".123"}) {
+// m.clear();
+// m.put(attr,1);
+// assertObjectEquals("{'"+attr+"':1}", m);
+// }
+// }
+//
+// //====================================================================================================
+// // Validate various backslashes in strings.
+// //====================================================================================================
+// @Test
+// public void testBackslashesInStrings() throws Exception {
+// YamlSerializer s = new YamlSerializerBuilder().simple().trimNullProperties(false).quoteChar('"').build();
+// String r, r2;
+//
+// // [\\]
+// r = "\\";
+// r2 = s.serialize(r);
+// assertEquals(r2, "\"\\\\\"");
+// assertEquals(YamlParser.DEFAULT.parse(r2, Object.class), r);
+//
+// // [\b\f\n\t]
+// r = "\b\f\n\t";
+// r2 = s.serialize(r);
+// assertEquals("\"\\b\\f\\n\\t\"", r2);
+// assertEquals(r, YamlParser.DEFAULT.parse(r2, Object.class));
+//
+// // Special JSON case: Forward slashes can OPTIONALLY be escaped.
+// // [\/]
+// assertEquals(YamlParser.DEFAULT.parse("\"\\/\"", Object.class), "/");
+//
+// // Unicode
+// r = "\u1234\u1ABC\u1abc";
+// r2 = s.serialize(r);
+// assertEquals("\"\u1234\u1ABC\u1abc\"", r2);
+//
+// assertEquals("\u1234", YamlParser.DEFAULT.parse("\"\\u1234\"", Object.class));
+// }
+//
+// //====================================================================================================
+// // Indentation
+// //====================================================================================================
+// @Test
+// public void testIndentation() throws Exception {
+// ObjectMap m = new ObjectMap("{J:{B:['c',{D:'e'},['f',{G:'h'},1,false]]},I:'j'}");
+// String e = ""
+// + "{"
+// + "\n J: {"
+// + "\n B: ["
+// + "\n 'c',"
+// + "\n {"
+// + "\n D: 'e'"
+// + "\n },"
+// + "\n ["
+// + "\n 'f',"
+// + "\n {"
+// + "\n G: 'h'"
+// + "\n },"
+// + "\n 1,"
+// + "\n false"
+// + "\n ]"
+// + "\n ]"
+// + "\n },"
+// + "\n I: 'j'"
+// + "\n}";
+// assertEquals(e, YamlSerializer.DEFAULT.serialize(m));
+// }
+//
+// //====================================================================================================
+// // Escaping double quotes
+// //====================================================================================================
+// @Test
+// public void testEscapingDoubleQuotes() throws Exception {
+// YamlSerializer s = YamlSerializer.DEFAULT;
+// String r = s.serialize(new ObjectMap().append("f1", "x'x\"x"));
+// assertEquals("{\"f1\":\"x'x\\\"x\"}", r);
+// YamlParser p = YamlParser.DEFAULT;
+// assertEquals("x'x\"x", p.parse(r, ObjectMap.class).getString("f1"));
+// }
+//
+// //====================================================================================================
+// // Escaping single quotes
+// //====================================================================================================
+// @Test
+// public void testEscapingSingleQuotes() throws Exception {
+// YamlSerializer s = YamlSerializer.DEFAULT;
+// String r = s.serialize(new ObjectMap().append("f1", "x'x\"x"));
+// assertEquals("{f1:'x\\'x\"x'}", r);
+// YamlParser p = YamlParser.DEFAULT;
+// assertEquals("x'x\"x", p.parse(r, ObjectMap.class).getString("f1"));
+// }
+//
+// //====================================================================================================
+// // testSubclassedList
+// //====================================================================================================
+// @Test
+// public void testSubclassedList() throws Exception {
+// YamlSerializer s = YamlSerializer.DEFAULT;
+// Map<String,Object> o = new HashMap<String,Object>();
+// o.put("c", new C());
+// assertEquals("{\"c\":[]}", s.serialize(o));
+// }
+//
+// public static class C extends LinkedList<String> {
+// }
+//
+// //====================================================================================================
+// // testEscapeSolidus
+// //====================================================================================================
+// @Test
+// public void testEscapeSolidus() throws Exception {
+// YamlSerializer s = new YamlSerializerBuilder().escapeSolidus(false).build();
+// String r = s.serialize("foo/bar");
+// assertEquals("\"foo/bar\"", r);
+// r = YamlParser.DEFAULT.parse(r, String.class);
+// assertEquals("foo/bar", r);
+//
+// s = new YamlSerializerBuilder().escapeSolidus(true).build();
+// r = s.serialize("foo/bar");
+// assertEquals("\"foo\\/bar\"", r);
+// r = YamlParser.DEFAULT.parse(r, String.class);
+// assertEquals("foo/bar", r);
+// }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/KeywordSet.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/KeywordSet.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/KeywordSet.java
index 15ebd33..b2f79d7 100644
--- a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/KeywordSet.java
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/KeywordSet.java
@@ -12,22 +12,13 @@
// ***************************************************************************************************************************
package org.apache.juneau.internal;
-import static org.apache.juneau.internal.ThrowableUtils.*;
+import java.util.*;
/**
* Stores a set of language keywords for quick lookup.
- *
- * <p>
- * Keywords must be:
- * <ul class='spaced-list'>
- * <li>
- * 2 or more characters in length.
- * <li>
- * Lowercase ASCII.
- * </ul>
*/
public final class KeywordSet {
- final char[][][][] store;
+ final String[] store;
/**
* Constructor.
@@ -35,28 +26,8 @@ public final class KeywordSet {
* @param keywords The list of keywords.
*/
public KeywordSet(String... keywords) {
- this.store = new char[26][][][];
-
- for (String keyword : keywords) {
- if (keyword.length() < 2)
- illegalArg("Invalid keyword '{0}' passed to KeywordStore.", keyword);
- int c0 = keyword.charAt(0) - 'a';
- int c1 = keyword.charAt(1) - 'a';
- if (c0 < 0 || c0 > 25 || c1 < 0 || c1 > 25)
- illegalArg("Invalid keyword '{0}' passed to KeywordStore.", keyword);
- if (this.store[c0] == null)
- this.store[c0] = new char[26][][];
- char[][][] x1 = this.store[c0];
- char[][] x2;
- if (x1[c1] == null)
- x2 = new char[1][];
- else {
- x2 = new char[x1[c1].length+1][];
- System.arraycopy(x1[c1], 0, x2, 0, x1[c1].length);
- }
- x2[x2.length-1] = keyword.toCharArray();
- x1[c1] = x2;
- }
+ this.store = keywords;
+ Arrays.sort(store);
}
/**
@@ -68,24 +39,6 @@ public final class KeywordSet {
public boolean contains(String s) {
if (s == null || s.length() < 2)
return false;
- int c0 = s.charAt(0) - 'a', c1 = s.charAt(1) - 'a';
- if (c0 < 0 || c0 > 25 || c1 < 0 || c1 > 25)
- return false;
- char[][][] x1 = store[c0];
- if (x1 == null)
- return false;
- char[][] x2 = x1[c1];
- if (x2 == null)
- return false;
- for (int i = 0; i < x2.length; i++) {
- char[] keyword = x2[i];
- if (keyword.length == s.length()) {
- for (int j = 0; j < keyword.length; j++)
- if (keyword[j] != s.charAt(j))
- return false;
- return true;
- }
- }
- return false;
+ return Arrays.binarySearch(store, s) >= 0;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/SystemUtils.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/SystemUtils.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/SystemUtils.java
new file mode 100644
index 0000000..5f7a6b9
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/internal/SystemUtils.java
@@ -0,0 +1,71 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.internal;
+
+/**
+ * System utilities.
+ */
+public class SystemUtils {
+
+ /**
+ * Returns the first non-<jk>null</jk> system property.
+ *
+ * @param def
+ * The default value if none are found.
+ * Can be <jk>null</jk>.
+ * @param keys
+ * The system properties to look for.
+ * @return
+ * The first non-<jk>null</jk> system property, or the default value if non were found.
+ */
+ public static String getFirstString(String def, String...keys) {
+ for (String key : keys) {
+ String v = System.getProperty(key);
+ if (v != null)
+ return v;
+ }
+ return def;
+ }
+
+ /**
+ * Returns the first non-<jk>null</jk> boolean system property.
+ *
+ * @param def
+ * The default value if none are found.
+ * Can be <jk>null</jk>.
+ * @param keys
+ * The system properties to look for.
+ * @return
+ * The first non-<jk>null</jk> system property, or the default value if non were found.
+ */
+ public static Boolean getFirstBoolean(Boolean def, String...keys) {
+ String s = getFirstString(null, keys);
+ return s == null ? def : Boolean.parseBoolean(s);
+ }
+
+ /**
+ * Returns the first non-<jk>null</jk> integer system property.
+ *
+ * @param def
+ * The default value if none are found.
+ * Can be <jk>null</jk>.
+ * @param keys
+ * The system properties to look for.
+ * @return
+ * The first non-<jk>null</jk> system property, or the default value if non were found.
+ */
+ public static Integer getFirstInteger(Integer def, String...keys) {
+ String s = getFirstString(null, keys);
+ return s == null ? def : Integer.parseInt(s);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlClassMeta.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlClassMeta.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlClassMeta.java
new file mode 100644
index 0000000..b1b22bb
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlClassMeta.java
@@ -0,0 +1,45 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import org.apache.juneau.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.json.annotation.*;
+
+/**
+ * Metadata on classes specific to the JSON serializers and parsers pulled from the {@link Json @Json} annotation on
+ * the class.
+ */
+public class YamlClassMeta extends ClassMetaExtended {
+
+ private final Json json;
+
+ /**
+ * Constructor.
+ *
+ * @param cm The class that this annotation is defined on.
+ */
+ public YamlClassMeta(ClassMeta<?> cm) {
+ super(cm);
+ this.json = ReflectionUtils.getAnnotation(Json.class, getInnerClass());
+ }
+
+ /**
+ * Returns the {@link Json} annotation defined on the class.
+ *
+ * @return The value of the {@link Json} annotation, or <jk>null</jk> if not specified.
+ */
+ protected Json getAnnotation() {
+ return json;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParser.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParser.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParser.java
new file mode 100644
index 0000000..5ddcf33
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParser.java
@@ -0,0 +1,163 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import static org.apache.juneau.parser.ParserContext.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+
+/**
+ * Parses any valid JSON text into a POJO model.
+ *
+ * <h5 class='section'>Media types:</h5>
+ *
+ * Handles <code>Content-Type</code> types: <code>application/json, text/json</code>
+ *
+ * <h5 class='section'>Description:</h5>
+ *
+ * This parser uses a state machine, which makes it very fast and efficient. It parses JSON in about 70% of the
+ * time that it takes the built-in Java DOM parsers to parse equivalent XML.
+ *
+ * <p>
+ * This parser handles all valid JSON syntax.
+ * In addition, when strict mode is disable, the parser also handles the following:
+ * <ul class='spaced-list'>
+ * <li>
+ * Javascript comments (both {@code /*} and {@code //}) are ignored.
+ * <li>
+ * Both single and double quoted strings.
+ * <li>
+ * Automatically joins concatenated strings (e.g. <code><js>"aaa"</js> + <js>'bbb'</js></code>).
+ * <li>
+ * Unquoted attributes.
+ * </ul>
+ *
+ * <p>
+ * Also handles negative, decimal, hexadecimal, octal, and double numbers, including exponential notation.
+ *
+ * <p>
+ * This parser handles the following input, and automatically returns the corresponding Java class.
+ * <ul class='spaced-list'>
+ * <li>
+ * JSON objects (<js>"{...}"</js>) are converted to {@link ObjectMap ObjectMaps}.
+ * <b>Note:</b> If a <code><xa>_type</xa>=<xs>'xxx'</xs></code> attribute is specified on the object, then an
+ * attempt is made to convert the object to an instance of the specified Java bean class.
+ * See the <code>beanTypeName</code> setting on the {@link PropertyStore} for more information about parsing
+ * beans from JSON.
+ * <li>
+ * JSON arrays (<js>"[...]"</js>) are converted to {@link ObjectList ObjectLists}.
+ * <li>
+ * JSON string literals (<js>"'xyz'"</js>) are converted to {@link String Strings}.
+ * <li>
+ * JSON numbers (<js>"123"</js>, including octal/hexadecimal/exponential notation) are converted to
+ * {@link Integer Integers}, {@link Long Longs}, {@link Float Floats}, or {@link Double Doubles} depending on
+ * whether the number is decimal, and the size of the number.
+ * <li>
+ * JSON booleans (<js>"false"</js>) are converted to {@link Boolean Booleans}.
+ * <li>
+ * JSON nulls (<js>"null"</js>) are converted to <jk>null</jk>.
+ * <li>
+ * Input consisting of only whitespace or JSON comments are converted to <jk>null</jk>.
+ * </ul>
+ *
+ * <p>
+ * Input can be any of the following:
+ * <ul class='spaced-list'>
+ * <li>
+ * <js>"{...}"</js> - Converted to a {@link ObjectMap} or an instance of a Java bean if a <xa>_type</xa>
+ * attribute is present.
+ * <li>
+ * <js>"[...]"</js> - Converted to a {@link ObjectList}.
+ * <li>
+ * <js>"123..."</js> - Converted to a {@link Number} (either {@link Integer}, {@link Long}, {@link Float},
+ * or {@link Double}).
+ * <li>
+ * <js>"true"</js>/<js>"false"</js> - Converted to a {@link Boolean}.
+ * <li>
+ * <js>"null"</js> - Returns <jk>null</jk>.
+ * <li>
+ * <js>"'xxx'"</js> - Converted to a {@link String}.
+ * <li>
+ * <js>"\"xxx\""</js> - Converted to a {@link String}.
+ * <li>
+ * <js>"'xxx' + \"yyy\""</js> - Converted to a concatenated {@link String}.
+ * </ul>
+ *
+ * <p>
+ * TIP: If you know you're parsing a JSON object or array, it can be easier to parse it using the
+ * {@link ObjectMap#ObjectMap(CharSequence) ObjectMap(CharSequence)} or {@link ObjectList#ObjectList(CharSequence)
+ * ObjectList(CharSequence)} constructors instead of using this class.
+ * The end result should be the same.
+ *
+ * <h5 class='section'>Configurable properties:</h5>
+ *
+ * This class has the following properties associated with it:
+ * <ul>
+ * <li>{@link YamlParserContext}
+ * </ul>
+ */
+public class YamlParser extends ReaderParser {
+
+ /** Default parser, all default settings.*/
+ public static final YamlParser DEFAULT = new YamlParser(PropertyStore.create());
+
+ /** Default parser, all default settings.*/
+ public static final YamlParser DEFAULT_STRICT = new YamlParser.Strict(PropertyStore.create());
+
+ /** Default parser, strict mode. */
+ public static class Strict extends YamlParser {
+
+ /**
+ * Constructor.
+ *
+ * @param propertyStore The property store containing all the settings for this object.
+ */
+ public Strict(PropertyStore propertyStore) {
+ super(propertyStore.copy().append(PARSER_strict, true));
+ }
+ }
+
+
+ private final YamlParserContext ctx;
+
+ /**
+ * Constructor.
+ *
+ * @param propertyStore The property store containing all the settings for this object.
+ */
+ public YamlParser(PropertyStore propertyStore) {
+ this(propertyStore, "application/json", "text/json");
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param propertyStore The property store containing all the settings for this object.
+ * @param consumes The list of media types that this parser consumes (e.g. <js>"application/json"</js>).
+ */
+ public YamlParser(PropertyStore propertyStore, String...consumes) {
+ super(propertyStore, consumes);
+ this.ctx = createContext(YamlParserContext.class);
+ }
+
+ @Override /* CoreObject */
+ public YamlParserBuilder builder() {
+ return new YamlParserBuilder(propertyStore);
+ }
+
+ @Override /* Parser */
+ public ReaderParserSession createSession(ParserSessionArgs args) {
+ return new YamlParserSession(ctx, args);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserBuilder.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserBuilder.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserBuilder.java
new file mode 100644
index 0000000..c1c77d2
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserBuilder.java
@@ -0,0 +1,465 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.http.*;
+import org.apache.juneau.parser.*;
+
+/**
+ * Builder class for building instances of JSON parsers.
+ */
+public class YamlParserBuilder extends ParserBuilder {
+
+ /**
+ * Constructor, default settings.
+ */
+ public YamlParserBuilder() {
+ super();
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param propertyStore The initial configuration settings for this builder.
+ */
+ public YamlParserBuilder(PropertyStore propertyStore) {
+ super(propertyStore);
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParser build() {
+ return new YamlParser(propertyStore);
+ }
+
+
+ //--------------------------------------------------------------------------------
+ // Properties
+ //--------------------------------------------------------------------------------
+
+ @Override /* ParserBuilder */
+ public YamlParserBuilder trimStrings(boolean value) {
+ super.trimStrings(value);
+ return this;
+ }
+
+ @Override /* ParserBuilder */
+ public YamlParserBuilder strict(boolean value) {
+ super.strict(value);
+ return this;
+ }
+
+ @Override /* ParserBuilder */
+ public YamlParserBuilder strict() {
+ super.strict();
+ return this;
+ }
+
+ @Override /* ParserBuilder */
+ public YamlParserBuilder inputStreamCharset(String value) {
+ super.inputStreamCharset(value);
+ return this;
+ }
+
+ @Override /* ParserBuilder */
+ public YamlParserBuilder fileCharset(String value) {
+ super.fileCharset(value);
+ return this;
+ }
+
+ @Override /* ParserBuilder */
+ public YamlParserBuilder listener(Class<? extends ParserListener> value) {
+ super.listener(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beansRequireDefaultConstructor(boolean value) {
+ super.beansRequireDefaultConstructor(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beansRequireSerializable(boolean value) {
+ super.beansRequireSerializable(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beansRequireSettersForGetters(boolean value) {
+ super.beansRequireSettersForGetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beansRequireSomeProperties(boolean value) {
+ super.beansRequireSomeProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanMapPutReturnsOldValue(boolean value) {
+ super.beanMapPutReturnsOldValue(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanConstructorVisibility(Visibility value) {
+ super.beanConstructorVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanClassVisibility(Visibility value) {
+ super.beanClassVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanFieldVisibility(Visibility value) {
+ super.beanFieldVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder methodVisibility(Visibility value) {
+ super.methodVisibility(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder useJavaBeanIntrospector(boolean value) {
+ super.useJavaBeanIntrospector(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder useInterfaceProxies(boolean value) {
+ super.useInterfaceProxies(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder ignoreUnknownBeanProperties(boolean value) {
+ super.ignoreUnknownBeanProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder ignoreUnknownNullBeanProperties(boolean value) {
+ super.ignoreUnknownNullBeanProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder ignorePropertiesWithoutSetters(boolean value) {
+ super.ignorePropertiesWithoutSetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder ignoreInvocationExceptionsOnGetters(boolean value) {
+ super.ignoreInvocationExceptionsOnGetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder ignoreInvocationExceptionsOnSetters(boolean value) {
+ super.ignoreInvocationExceptionsOnSetters(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder sortProperties(boolean value) {
+ super.sortProperties(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder notBeanPackages(String...values) {
+ super.notBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder notBeanPackages(Collection<String> values) {
+ super.notBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setNotBeanPackages(String...values) {
+ super.setNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setNotBeanPackages(Collection<String> values) {
+ super.setNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeNotBeanPackages(String...values) {
+ super.removeNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeNotBeanPackages(Collection<String> values) {
+ super.removeNotBeanPackages(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder notBeanClasses(Class<?>...values) {
+ super.notBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder notBeanClasses(Collection<Class<?>> values) {
+ super.notBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setNotBeanClasses(Class<?>...values) {
+ super.setNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setNotBeanClasses(Collection<Class<?>> values) {
+ super.setNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeNotBeanClasses(Class<?>...values) {
+ super.removeNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeNotBeanClasses(Collection<Class<?>> values) {
+ super.removeNotBeanClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanFilters(Class<?>...values) {
+ super.beanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanFilters(Collection<Class<?>> values) {
+ super.beanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setBeanFilters(Class<?>...values) {
+ super.setBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setBeanFilters(Collection<Class<?>> values) {
+ super.setBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeBeanFilters(Class<?>...values) {
+ super.removeBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeBeanFilters(Collection<Class<?>> values) {
+ super.removeBeanFilters(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder pojoSwaps(Class<?>...values) {
+ super.pojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder pojoSwaps(Collection<Class<?>> values) {
+ super.pojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setPojoSwaps(Class<?>...values) {
+ super.setPojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setPojoSwaps(Collection<Class<?>> values) {
+ super.setPojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removePojoSwaps(Class<?>...values) {
+ super.removePojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removePojoSwaps(Collection<Class<?>> values) {
+ super.removePojoSwaps(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder implClasses(Map<Class<?>,Class<?>> values) {
+ super.implClasses(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public <T> YamlParserBuilder implClass(Class<T> interfaceClass, Class<? extends T> implClass) {
+ super.implClass(interfaceClass, implClass);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanDictionary(Class<?>...values) {
+ super.beanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanDictionary(Collection<Class<?>> values) {
+ super.beanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setBeanDictionary(Class<?>...values) {
+ super.setBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder setBeanDictionary(Collection<Class<?>> values) {
+ super.setBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeFromBeanDictionary(Class<?>...values) {
+ super.removeFromBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeFromBeanDictionary(Collection<Class<?>> values) {
+ super.removeFromBeanDictionary(values);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder beanTypePropertyName(String value) {
+ super.beanTypePropertyName(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder defaultParser(Class<?> value) {
+ super.defaultParser(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder locale(Locale value) {
+ super.locale(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder timeZone(TimeZone value) {
+ super.timeZone(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder mediaType(MediaType value) {
+ super.mediaType(value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder debug() {
+ super.debug();
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder property(String name, Object value) {
+ super.property(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder properties(Map<String,Object> properties) {
+ super.properties(properties);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder addToProperty(String name, Object value) {
+ super.addToProperty(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder putToProperty(String name, Object key, Object value) {
+ super.putToProperty(name, key, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder putToProperty(String name, Object value) {
+ super.putToProperty(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder removeFromProperty(String name, Object value) {
+ super.removeFromProperty(name, value);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder classLoader(ClassLoader classLoader) {
+ super.classLoader(classLoader);
+ return this;
+ }
+
+ @Override /* CoreObjectBuilder */
+ public YamlParserBuilder apply(PropertyStore copyFrom) {
+ super.apply(copyFrom);
+ return this;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/ab8f0faa/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserContext.java
----------------------------------------------------------------------
diff --git a/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserContext.java b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserContext.java
new file mode 100644
index 0000000..48b589d
--- /dev/null
+++ b/juneau-core/juneau-marshall/src/main/java/org/apache/juneau/yaml/proto/YamlParserContext.java
@@ -0,0 +1,61 @@
+// ***************************************************************************************************************************
+// * 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 org.apache.juneau.yaml.proto;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+
+/**
+ * Configurable properties on the {@link YamlParser} class.
+ *
+ * <p>
+ * Context properties are set by calling {@link PropertyStore#setProperty(String, Object)} on the property store
+ * passed into the constructor.
+ *
+ * <p>
+ * See {@link PropertyStore} for more information about context properties.
+ *
+ * <h6 class='topic'>Inherited configurable properties</h6>
+ * <ul class='doctree'>
+ * <li class='jc'>
+ * <a class="doclink" href="../BeanContext.html#ConfigProperties">BeanContext</a>
+ * - Properties associated with handling beans on serializers and parsers.
+ * <ul>
+ * <li class='jc'>
+ * <a class="doclink" href="../parser/ParserContext.html#ConfigProperties">ParserContext</a>
+ * - Configurable properties common to all parsers.
+ * </ul>
+ * </li>
+ * </ul>
+ */
+public final class YamlParserContext extends ParserContext {
+
+ /**
+ * Constructor.
+ *
+ * <p>
+ * Typically only called from {@link PropertyStore#getContext(Class)}.
+ *
+ * @param ps The property store that created this context.
+ */
+ public YamlParserContext(PropertyStore ps) {
+ super(ps);
+ }
+
+ @Override /* Context */
+ public ObjectMap asMap() {
+ return super.asMap()
+ .append("JsonParserContext", new ObjectMap()
+ );
+ }
+}