001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.serializer;
014
015import org.apache.juneau.*;
016import org.apache.juneau.annotation.*;
017
018/**
019 * Subclass of {@link Serializer} for byte-based serializers.
020 */
021@ConfigurableContext
022public abstract class OutputStreamSerializer extends Serializer {
023
024   //-------------------------------------------------------------------------------------------------------------------
025   // Configurable properties
026   //-------------------------------------------------------------------------------------------------------------------
027
028   static final String PREFIX = "OutputStreamSerializer";
029
030   /**
031    * Configuration property:  Binary output format.
032    *
033    * <h5 class='section'>Property:</h5>
034    * <ul>
035    *    <li><b>Name:</b>  <js>"OutputStreamSerializer.binaryFormat.s"</js>
036    *    <li><b>Data type:</b>  {@link BinaryFormat}
037    *    <li><b>Default:</b>  {@link BinaryFormat#HEX}
038    *    <li><b>Session property:</b>  <jk>false</jk>
039    *    <li><b>Methods:</b>
040    *       <ul>
041    *          <li class='jm'>{@link OutputStreamSerializerBuilder#binaryFormat(BinaryFormat)}
042    *       </ul>
043    * </ul>
044    *
045    * <h5 class='section'>Description:</h5>
046    * <p>
047    * When using the {@link #serializeToString(Object)} method on stream-based serializers, this defines the format to use
048    * when converting the resulting byte array to a string.
049    *
050    *
051    * <h5 class='section'>Example:</h5>
052    * <p class='bcode w800'>
053    *    <jc>// Create a serializer that serializes to BASE64.</jc>
054    *    OutputStreamSerializer s = MsgPackSerializer
055    *       .<jsm>create</jsm>()
056    *       .binaryFormat(<jsf>BASE64</jsf>)
057    *       .build();
058    *
059    *    <jc>// Same, but use property.</jc>
060    *    OutputStreamSerializer s = MsgPackSerializer
061    *       .<jsm>create</jsm>()
062    *       .set(<jsf>SERIALIZER_binaryOutputFormat</jsf>, <js>"BASE64"</js>)
063    *       .build();
064    *
065    *    <jc>// The bean we want to serialize.</jc>
066    *    <jk>public class</jk> MyBean {...}
067    *
068    *    <jc>// MessagePack will generate BASE64-encoded string.</jc>
069    *    String msgPack = s.serializeToString(<jk>new</jk> MyBean());
070    * </p>
071    */
072   public static final String OSSERIALIZER_binaryFormat = PREFIX + ".binaryFormat.s";
073
074   static final OutputStreamSerializer DEFAULT = new OutputStreamSerializer(PropertyStore.create().build(), "", "") {
075      @Override
076      public OutputStreamSerializerSession createSession(SerializerSessionArgs args) {
077         throw new NoSuchMethodError();
078      }
079   };
080
081   //-------------------------------------------------------------------------------------------------------------------
082   // Instance
083   //-------------------------------------------------------------------------------------------------------------------
084
085   private final BinaryFormat binaryFormat;
086
087   /**
088    * Constructor.
089    *
090    * @param ps
091    *    The property store containing all the settings for this object.
092    * @param produces
093    *    The media type that this serializer produces.
094    * @param accept
095    *    The accept media types that the serializer can handle.
096    *    <p>
097    *    Can contain meta-characters per the <c>media-type</c> specification of {@doc RFC2616.section14.1}
098    *    <p>
099    *    If empty, then assumes the only media type supported is <c>produces</c>.
100    *    <p>
101    *    For example, if this serializer produces <js>"application/json"</js> but should handle media types of
102    *    <js>"application/json"</js> and <js>"text/json"</js>, then the arguments should be:
103    *    <p class='bcode w800'>
104    *    <jk>super</jk>(ps, <js>"application/json"</js>, <js>"application/json,text/json"</js>);
105    *    </p>
106    *    <br>...or...
107    *    <p class='bcode w800'>
108    *    <jk>super</jk>(ps, <js>"application/json"</js>, <js>"*&#8203;/json"</js>);
109    *    </p>
110    * <p>
111    * The accept value can also contain q-values.
112    */
113   protected OutputStreamSerializer(PropertyStore ps, String produces, String accept) {
114      super(ps, produces, accept);
115
116      binaryFormat = getProperty(OSSERIALIZER_binaryFormat, BinaryFormat.class, BinaryFormat.HEX);
117   }
118
119   //-----------------------------------------------------------------------------------------------------------------
120   // Abstract methods
121   //-----------------------------------------------------------------------------------------------------------------
122
123   @Override /* SerializerSession */
124   public abstract OutputStreamSerializerSession createSession(SerializerSessionArgs args);
125
126
127   //-----------------------------------------------------------------------------------------------------------------
128   // Other methods
129   //-----------------------------------------------------------------------------------------------------------------
130
131   @Override /* Context */
132   public OutputStreamSerializerSession createSession() {
133      return createSession(createDefaultSessionArgs());
134   }
135
136   @Override /* Serializer */
137   public final boolean isWriterSerializer() {
138      return false;
139   }
140
141   /**
142    * Convenience method for serializing an object to a <code><jk>byte</jk></code>.
143    *
144    * @param o The object to serialize.
145    * @return The output serialized to a byte array.
146    * @throws SerializeException If a problem occurred trying to convert the output.
147    */
148   @Override
149   public final byte[] serialize(Object o) throws SerializeException {
150      return createSession(createDefaultSessionArgs()).serialize(o);
151   }
152
153   //-----------------------------------------------------------------------------------------------------------------
154   // Properties
155   //-----------------------------------------------------------------------------------------------------------------
156
157   /**
158    * Configuration property:  Binary output format.
159    *
160    * @see #OSSERIALIZER_binaryFormat
161    * @return
162    *    The format to use for the {@link #serializeToString(Object)} method on stream-based serializers when converting byte arrays to strings.
163    */
164   protected final BinaryFormat getBinaryFormat() {
165      return binaryFormat;
166   }
167
168   //-----------------------------------------------------------------------------------------------------------------
169   // Other methods
170   //-----------------------------------------------------------------------------------------------------------------
171
172   @Override /* Context */
173   public ObjectMap toMap() {
174      return super.toMap()
175         .append("OutputStreamSerializer", new DefaultFilteringObjectMap()
176            .append("binaryFormat", binaryFormat)
177         );
178   }
179}