All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.juneau.uon.UonSerializer Maven / Gradle / Ivy

There is a newer version: 9.0.1
Show newest version
// ***************************************************************************************************************************
// * 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.uon;

import org.apache.juneau.*;
import org.apache.juneau.httppart.*;
import org.apache.juneau.serializer.*;
import org.apache.juneau.urlencoding.*;

/**
 * Serializes POJO models to UON (a notation for URL-encoded query parameter values).
 *
 * 
Media types
* * Handles Accept types: text/uon *

* Produces Content-Type types: text/uon * *

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

* The following shows a sample object defined in Javascript: *

* { * id: 1, * name: 'John Smith', * uri: 'http://sample/addressBook/person/1', * addressBookUri: 'http://sample/addressBook', * birthDate: '1946-08-12T00:00:00Z', * otherIds: null, * addresses: [ * { * uri: 'http://sample/addressBook/address/1', * personUri: 'http://sample/addressBook/person/1', * id: 1, * street: '100 Main Street', * city: 'Anywhereville', * state: 'NY', * zip: 12345, * isCurrent: true, * } * ] * } *

* *

* Using the "strict" syntax defined in this document, the equivalent UON notation would be as follows: *

* ( * id=1, * name='John+Smith', * uri=http://sample/addressBook/person/1, * addressBookUri=http://sample/addressBook, * birthDate=1946-08-12T00:00:00Z, * otherIds=null, * addresses=@( * ( * uri=http://sample/addressBook/address/1, * personUri=http://sample/addressBook/person/1, * id=1, * street='100+Main+Street', * city=Anywhereville, * state=NY, * zip=12345, * isCurrent=true * ) * ) * ) *

* *
Example:
*

* // Serialize a Map * Map m = new ObjectMap("{a:'b',c:1,d:false,e:['f',1,false],g:{h:'i'}}"); * * // Serialize to value equivalent to JSON. * // Produces "(a=b,c=1,d=false,e=@(f,1,false),g=(h=i))" * String s = UonSerializer.DEFAULT.serialize(s); * * // Serialize a bean * public class Person { * public Person(String s); * public String getName(); * public int getAge(); * public Address getAddress(); * public boolean deceased; * } * * public class Address { * public String getStreet(); * public String getCity(); * public String getState(); * public int getZip(); * } * * Person p = new Person("John Doe", 23, "123 Main St", "Anywhere", * "NY", 12345, false); * * // Produces "(name='John Doe',age=23,address=(street='123 Main St',city=Anywhere,state=NY,zip=12345),deceased=false)" * String s = UonSerializer.DEFAULT.serialize(s); *

*/ public class UonSerializer extends WriterSerializer implements HttpPartSerializer { //------------------------------------------------------------------------------------------------------------------- // Configurable properties //------------------------------------------------------------------------------------------------------------------- private static final String PREFIX = "UonSerializer."; /** * Configuration property: Add "_type" properties when needed. * *
Property:
*
    *
  • Name: "UonSerializer.addBeanTypes.b" *
  • Data type: Boolean *
  • Default: false *
  • Session property: false *
  • Methods: *
      *
    • {@link UonSerializerBuilder#addBeanTypes(boolean)} *
    *
* *
Description:
*

* If true, then "_type" properties will be added to beans if their type cannot be inferred * through reflection. * *

* When present, this value overrides the {@link #SERIALIZER_addBeanTypes} setting and is * provided to customize the behavior of specific serializers in a {@link SerializerGroup}. */ public static final String UON_addBeanTypes = PREFIX + "addBeanTypes.b"; /** * Configuration property: Encode non-valid URI characters. * *

Property:
*
    *
  • Name: "UonSerializer.encoding.b" *
  • Data type: Boolean *
  • Default: false for {@link UonSerializer}, true for {@link UrlEncodingSerializer} *
  • Session property: false *
  • Methods: *
      *
    • {@link UonSerializerBuilder#encoding(boolean)} *
    • {@link UonSerializerBuilder#encoding()} *
    *
* *
Description:
*

* Encode non-valid URI characters with "%xx" constructs. * *

* If true, non-valid URI characters will be converted to "%xx" sequences. *
Set to false if parameter value is being passed to some other code that will already perform * URL-encoding of non-valid URI characters. * *

Example:
*

* // Create a non-encoding UON serializer. * UonSerializer s1 = UonSerializer. * .create() * .build(); * * // Create an encoding UON serializer. * UonSerializer s2 = UonSerializer. * .create() * .encoding() * .build(); * * ObjectMap m = new ObjectMap().append("foo", "foo bar"); * * // Produces: "(foo=foo bar)" * String uon1 = s1.serialize(m) * * // Produces: "(foo=foo%20bar)" * String uon2 = s2.serialize(m) *

*/ public static final String UON_encoding = PREFIX + "encoding.b"; /** * Configuration property: Format to use for query/form-data/header values. * *
Property:
*
    *
  • Name: "UrlEncodingSerializer.paramFormat.s" *
  • Data type: String ({@link ParamFormat}) *
  • Default: "UON" *
  • Session property: false *
  • Methods: *
      *
    • {@link UonSerializerBuilder#paramFormat(ParamFormat)} *
    • {@link UonSerializerBuilder#paramFormatPlain()} *
    *
* *
Description:
*

* Specifies the format to use for URL GET parameter keys and values. * *

* Possible values: *

    *
  • {@link ParamFormat#UON} - Use UON notation for parameters. *
  • {@link ParamFormat#PLAINTEXT} - Use plain text for parameters. *
* *
Example:
*

* // Create a normal UON serializer. * UonSerializer s1 = UonSerializer. * .create() * .build(); * * // Create a plain-text UON serializer. * UonSerializer s2 = UonSerializer. * .create() * .paramFormat(PLAIN_TEXT) * .build(); * * ObjectMap m = new ObjectMap() * .append("foo", "bar"); * .append("baz", new String[]{"qux", "true", "123"}); * * // Produces: "(foo=bar,baz=@(qux,'true','123'))" * String uon1 = s1.serialize(m) * * // Produces: "foo=bar,baz=qux,true,123" * String uon2 = s2.serialize(m) *

*/ public static final String UON_paramFormat = PREFIX + "paramFormat.s"; //------------------------------------------------------------------------------------------------------------------- // Predefined instances //------------------------------------------------------------------------------------------------------------------- /** Reusable instance of {@link UonSerializer}, all default settings. */ public static final UonSerializer DEFAULT = new UonSerializer(PropertyStore.DEFAULT); /** Reusable instance of {@link UonSerializer.Readable}. */ public static final UonSerializer DEFAULT_READABLE = new Readable(PropertyStore.DEFAULT); /** Reusable instance of {@link UonSerializer.Encoding}. */ public static final UonSerializer DEFAULT_ENCODING = new Encoding(PropertyStore.DEFAULT); //------------------------------------------------------------------------------------------------------------------- // Predefined subclasses //------------------------------------------------------------------------------------------------------------------- /** * Equivalent to UonSerializer.create().ws().build();. */ public static class Readable extends UonSerializer { /** * Constructor. * * @param ps The property store containing all the settings for this object. */ public Readable(PropertyStore ps) { super(ps.builder().set(SERIALIZER_useWhitespace, true).build()); } } /** * Equivalent to UonSerializer.create().encoding().build();. */ public static class Encoding extends UonSerializer { /** * Constructor. * * @param ps The property store containing all the settings for this object. */ public Encoding(PropertyStore ps) { super(ps.builder().set(UON_encoding, true).build()); } } //------------------------------------------------------------------------------------------------------------------- // Instance //------------------------------------------------------------------------------------------------------------------- private final boolean encodeChars, addBeanTypes; private final ParamFormat paramFormat; /** * Constructor. * * @param ps * The property store containing all the settings for this object. */ public UonSerializer(PropertyStore ps) { this(ps, "text/uon", null); } /** * Constructor. * * @param ps * 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. *

* Can contain meta-characters per the media-type specification of {@doc RFC2616.section14.1} *

* If empty, then assumes the only media type supported is produces. *

* For example, if this serializer produces "application/json" but should handle media types of * "application/json" and "text/json", then the arguments should be: *

* super(ps, "application/json", "application/json,text/json"); *

*
...or... *

* super(ps, "application/json", "*​/json"); *

*

* The accept value can also contain q-values. */ public UonSerializer(PropertyStore ps, String produces, String accept) { super(ps, produces, accept); encodeChars = getBooleanProperty(UON_encoding, false); addBeanTypes = getBooleanProperty(UON_addBeanTypes, getBooleanProperty(SERIALIZER_addBeanTypes, false)); paramFormat = getProperty(UON_paramFormat, ParamFormat.class, ParamFormat.UON); } @Override /* Context */ public UonSerializerBuilder builder() { return new UonSerializerBuilder(getPropertyStore()); } /** * Instantiates a new clean-slate {@link UonSerializerBuilder} object. * *

* This is equivalent to simply calling new UonSerializerBuilder(). * *

* Note that this method creates a builder initialized to all default settings, whereas {@link #builder()} copies * the settings of the object called on. * * @return A new {@link UonSerializerBuilder} object. */ public static UonSerializerBuilder create() { return new UonSerializerBuilder(); } //----------------------------------------------------------------------------------------------------------------- // Entry point methods //----------------------------------------------------------------------------------------------------------------- @Override /* Serializer */ public WriterSerializerSession createSession(SerializerSessionArgs args) { return new UonSerializerSession(this, null, args); } @Override /* HttpPartSerializer */ public UonSerializerSession createPartSession(SerializerSessionArgs args) { return new UonSerializerSession(this, null, args); } @Override /* HttpPartSerializer */ public UonSerializerSession createPartSession() { return createPartSession(null); } @Override /* HttpPartSerializer */ public String serialize(HttpPartType partType, HttpPartSchema schema, Object value) throws SchemaValidationException, SerializeException { return createPartSession().serialize(partType, schema, value); } @Override /* HttpPartSerializer */ public String serialize(HttpPartSchema schema, Object value) throws SchemaValidationException, SerializeException { return createPartSession().serialize(null, schema, value); } //----------------------------------------------------------------------------------------------------------------- // Properties //----------------------------------------------------------------------------------------------------------------- /** * Configuration property: Encode non-valid URI characters. * * @see #UON_encoding * @return * true if non-valid URI characters should be encoded with "%xx" constructs. */ protected final boolean isEncodeChars() { return encodeChars; } /** * Configuration property: Add "_type" properties when needed. * * @see #UON_addBeanTypes * @return * true if "_type" properties will be added to beans if their type cannot be inferred * through reflection. */ @Override protected final boolean isAddBeanTypes() { return addBeanTypes; } /** * Configuration property: Format to use for query/form-data/header values. * * @see #UON_paramFormat * @return * Specifies the format to use for URL GET parameter keys and values. */ protected final ParamFormat getParamFormat() { return paramFormat; } @Override /* Context */ public ObjectMap asMap() { return super.asMap() .append("UonSerializer", new ObjectMap() .append("encodeChars", encodeChars) .append("addBeanTypes", addBeanTypes) .append("paramFormat", paramFormat) ); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy