001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.marshall.hocon;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022import java.net.*;
023import java.util.*;
024
025import org.apache.juneau.commons.bean.*;
026import org.apache.juneau.commons.collections.*;
027import org.apache.juneau.marshall.*;
028import org.apache.juneau.marshall.serializer.*;
029import org.apache.juneau.marshall.stream.*;
030import org.apache.juneau.marshall.swap.spi.*;
031
032/**
033 * Serializes POJO models to HOCON (Human-Optimized Config Object Notation).
034 *
035 * <h2 class='topic'>Media types</h2>
036 * <p>
037 * Accepts <c>Accept</c> types:  <bc>application/hocon</bc>
038 * <p>
039 * Produces <c>Content-Type</c> types:  <bc>application/hocon</bc>
040 *
041 * <h2 class='topic'>Description</h2>
042 * <p>
043 * HOCON is a superset of JSON used extensively in the JVM ecosystem for configuration files.
044 * This serializer produces output that is valid HOCON and can be parsed back by {@link HoconParser}.
045 *
046 * <p>
047 * The conversion is as follows:
048 * <ul class='spaced-list'>
049 *    <li>
050 *       {@link HashMap HashMap} / bean → HOCON object with unquoted keys and <c>=</c> separator (<c>{ key = value }</c>).
051 *    <li>
052 *       {@link Collection Collection} / array → HOCON array (<c>[a, b, c]</c>).
053 *    <li>
054 *       {@link String String} (simple, no special chars) → unquoted string (<c>name = myapp</c>).
055 *    <li>
056 *       {@link String String} (contains special chars or is ambiguous like <c>"true"</c>, <c>"42"</c>, <c>"null"</c>) → quoted string (<c>path = "/usr/local/bin"</c>).
057 *    <li>
058 *       {@link String String} (multi-line) → triple-quoted string (<c>desc = """..."""</c>).
059 *    <li>
060 *       {@link Number Number} → number literal (<c>port = 8080</c>).
061 *    <li>
062 *       {@link Boolean Boolean} → <c>true</c> or <c>false</c>.
063 *    <li>
064 *       <c>null</c> → <c>null</c> keyword.
065 *    <li>
066 *       Non-primitive types (e.g. {@link Date Date}, {@link URI URI}) → converted via {@link ObjectSwap} before serialization.
067 * </ul>
068 *
069 * <h2 class='topic'>Behavior-specific subclasses</h2>
070 * <ul class='spaced-list'>
071 *    <li>
072 *       {@link #DEFAULT} — readable, unquoted keys/values, <c>=</c> separator, root braces omitted (config-file style).
073 *    <li>
074 *       {@link #DEFAULT_BRACES} — same as {@link #DEFAULT} but includes root <c>{ }</c> braces.
075 *    <li>
076 *       {@link #DEFAULT_COMPACT} — single-line compact output, JSON-compatible.
077 * </ul>
078 *
079 * <h2 class='section'>Example:</h2>
080 * <p class='bjava'>
081 *    <jc>// Serialize a bean</jc>
082 *    String <jv>hocon</jv> = HoconSerializer.<jsf>DEFAULT</jsf>.write(<jv>myBean</jv>);
083 *
084 *    <jc>// Create a custom serializer instance</jc>
085 *    HoconSerializer <jv>s</jv> = HoconSerializer.<jsm>create</jsm>().omitRootBraces(<jk>false</jk>).build();
086 *    String <jv>hocon2</jv> = <jv>s</jv>.write(<jv>myBean</jv>);
087 * </p>
088 *
089 * <h2 class='figure'>Example output (bean, root braces omitted):</h2>
090 * <p class='bjson'>
091 * name = myapp
092 * port = 8080
093 * debug = true
094 * database {
095 *   host = localhost
096 *   port = 5432
097 * }
098 * tags = [web, api, rest]
099 * </p>
100 *
101 * <h2 class='figure'>Example output (with root braces — DEFAULT_BRACES):</h2>
102 * <p class='bjson'>
103 * {
104 *   name = myapp
105 *   port = 8080
106 *   debug = true
107 * }
108 * </p>
109 *
110 * <h2 class='section'>Limitations:</h2><ul>
111 *    <li class='note'>Substitutions (<c>${var}</c>) are never emitted — the serializer always writes resolved (concrete) values.
112 *    <li class='note'>Value concatenation is never emitted — the serializer always writes complete strings.
113 *    <li class='note'>Path expressions (<c>a.b.c = value</c>) are never emitted — the serializer always uses nested-brace form.
114 *    <li class='note'><c>include</c> directives are never emitted — these require file-system access outside the scope of a serializer.
115 * </ul>
116 *
117 * <h2 class='section'>Notes:</h2><ul>
118 *    <li class='note'>This class is thread safe and reusable.
119 * </ul>
120 *
121 * <h2 class='section'>See Also:</h2><ul>
122 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/HoconSupport">HOCON</a>
123 * </ul>
124 */
125@SuppressWarnings({
126   "java:S110", // HoconSerializer extends WriterSerializer, which sits on the shared Serializer base-class chain; the depth comes from that format-family design.
127   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
128   "java:S9149", // Per-format static factories intentionally shadow the parent's.
129   "resource" // Closeable resources are owned by the caller's serializer session; Eclipse JDT @Owning warning is by design.
130})
131public class HoconSerializer extends WriterSerializer implements HoconMetaProvider, RecordWritable {
132
133   private final java.util.concurrent.ConcurrentHashMap<ClassMeta<?>,HoconClassMeta> hoconClassMetas = new java.util.concurrent.ConcurrentHashMap<>();
134   private final java.util.concurrent.ConcurrentHashMap<BeanPropertyMeta,HoconBeanPropertyMeta> hoconBeanPropertyMetas = new java.util.concurrent.ConcurrentHashMap<>();
135
136   /** Use = (not :) for key-value separator. */
137   protected final boolean useEqualsSign;
138
139   /** Use unquoted strings for simple values. */
140   protected final boolean useUnquotedStrings;
141
142   /** Use unquoted keys when safe. */
143   protected final boolean useUnquotedKeys;
144
145   /** Omit root object braces. */
146   protected final boolean omitRootBraces;
147
148   /** Use triple-quoted """ for strings with newlines. */
149   protected final boolean useMultilineStrings;
150
151   /** Use newlines instead of commas between members. */
152   protected final boolean useNewlineSeparators;
153
154   /**
155    * Builder class.
156    */
157   public static class Builder extends WriterSerializer.Builder<Builder> {
158
159      private static final Cache<HashKey,HoconSerializer> CACHE = Cache.of(HashKey.class, HoconSerializer.class).build();
160
161      private boolean useEqualsSign = true;
162      private boolean useUnquotedStrings = true;
163      private boolean useUnquotedKeys = true;
164      private boolean omitRootBraces = true;
165      private boolean useMultilineStrings = true;
166      private boolean useNewlineSeparators = true;
167
168      protected Builder() {
169         produces("application/hocon");
170         accept("application/hocon");
171      }
172
173      protected Builder(Builder copyFrom) {
174         super(reqnn("copyFrom", copyFrom));
175         useEqualsSign = copyFrom.useEqualsSign;
176         useUnquotedStrings = copyFrom.useUnquotedStrings;
177         useUnquotedKeys = copyFrom.useUnquotedKeys;
178         omitRootBraces = copyFrom.omitRootBraces;
179         useMultilineStrings = copyFrom.useMultilineStrings;
180         useNewlineSeparators = copyFrom.useNewlineSeparators;
181      }
182
183      protected Builder(HoconSerializer copyFrom) {
184         super(reqnn("copyFrom", copyFrom));
185         useEqualsSign = copyFrom.useEqualsSign;
186         useUnquotedStrings = copyFrom.useUnquotedStrings;
187         useUnquotedKeys = copyFrom.useUnquotedKeys;
188         omitRootBraces = copyFrom.omitRootBraces;
189         useMultilineStrings = copyFrom.useMultilineStrings;
190         useNewlineSeparators = copyFrom.useNewlineSeparators;
191      }
192
193      /**
194       * Uses = for key-value separator (HOCON convention).
195       *
196       * @param value <jk>true</jk> for <c>=</c>, <jk>false</jk> for <c>:</c>.
197       * @return This object.
198       */
199      public Builder useEqualsSign(boolean value) {
200         useEqualsSign = value;
201         return this;
202      }
203
204      /**
205       * Enables unquoted string output when values are unambiguous.
206       *
207       * @param value <jk>true</jk> to emit unquoted strings when safe.
208       * @return This object.
209       */
210      public Builder useUnquotedStrings(boolean value) {
211         useUnquotedStrings = value;
212         return this;
213      }
214
215      /**
216       * Enables unquoted object keys when safe.
217       *
218       * @param value <jk>true</jk> to emit unquoted keys when safe.
219       * @return This object.
220       */
221      public Builder useUnquotedKeys(boolean value) {
222         useUnquotedKeys = value;
223         return this;
224      }
225
226      /**
227       * Omits root-level object braces <c>{}</c> in output.
228       *
229       * @param value <jk>true</jk> to omit root braces.
230       * @return This object.
231       */
232      public Builder omitRootBraces(boolean value) {
233         omitRootBraces = value;
234         return this;
235      }
236
237      /**
238       * Enables triple-quoted strings for values containing newlines.
239       *
240       * @param value <jk>true</jk> to use <c>"""</c> blocks for newline-containing strings.
241       * @return This object.
242       */
243      public Builder useMultilineStrings(boolean value) {
244         useMultilineStrings = value;
245         return this;
246      }
247
248      /**
249       * Uses newlines instead of commas between object members.
250       *
251       * @param value <jk>true</jk> for newline-separated members.
252       * @return This object.
253       */
254      public Builder useNewlineSeparators(boolean value) {
255         useNewlineSeparators = value;
256         return this;
257      }
258
259      /**
260       * Creates compact output (comma-separated, single line).
261       *
262       * @return This object.
263       */
264      public Builder compact() {
265         useNewlineSeparators = false;
266         return this;
267      }
268
269      @Override
270      public Builder useWhitespace() {
271         super.useWhitespace();
272         return this;
273      }
274
275      @Override
276      public Builder useWhitespace(boolean value) {
277         super.useWhitespace(value);
278         return this;
279      }
280
281      @Override /* Overridden from WriterSerializer.Builder<?> */
282      public Builder ws() {
283         return useWhitespace();
284      }
285
286      @Override
287      public HoconSerializer build() {
288         return cache(CACHE).build(HoconSerializer.class);
289      }
290
291      @Override
292      public Builder copy() {
293         return new Builder(this);
294      }
295
296      @Override
297      public HashKey hashKey() {
298         return HashKey.of(super.hashKey(), useEqualsSign, useUnquotedStrings, useUnquotedKeys,
299            omitRootBraces, useMultilineStrings, useNewlineSeparators);
300      }
301   }
302
303   /** Default serializer (readable, root braces omitted). */
304   public static final HoconSerializer DEFAULT = new HoconSerializer(create().ws());
305
306   /** Default serializer with root braces. */
307   public static final HoconSerializer DEFAULT_BRACES = new HoconSerializer(create().ws().omitRootBraces(false));
308
309   /** Compact serializer (single line). */
310   public static final HoconSerializer DEFAULT_COMPACT = new HoconSerializer(create().useWhitespace(false).compact());
311
312   /**
313    * Creates a new builder.
314    *
315    * @return A new builder.
316    */
317   public static Builder create() {
318      return new Builder();
319   }
320
321   /**
322    * Constructor.
323    *
324    * @param builder The builder.
325    */
326   public HoconSerializer(Builder builder) {
327      super(builder);
328      useEqualsSign = builder.useEqualsSign;
329      useUnquotedStrings = builder.useUnquotedStrings;
330      useUnquotedKeys = builder.useUnquotedKeys;
331      omitRootBraces = builder.omitRootBraces;
332      useMultilineStrings = builder.useMultilineStrings;
333      useNewlineSeparators = builder.useNewlineSeparators;
334   }
335
336   @Override
337   public HoconSerializerSession.Builder createSession() {
338      return HoconSerializerSession.create(this);
339   }
340
341   @Override
342   public Builder copy() {
343      return new Builder(this);
344   }
345
346   @Override
347   public HoconBeanPropertyMeta getHoconBeanPropertyMeta(BeanPropertyMeta bpm) {
348      if (bpm == null)
349         return HoconBeanPropertyMeta.DEFAULT;
350      return hoconBeanPropertyMetas.computeIfAbsent(bpm, k -> new HoconBeanPropertyMeta(k, this));
351   }
352
353   @Override
354   public HoconClassMeta getHoconClassMeta(ClassMeta<?> cm) {
355      return hoconClassMetas.computeIfAbsent(cm, k -> new HoconClassMeta(k, this));
356   }
357
358   @Override
359   protected FluentMap<String,Object> properties() {
360      return super.properties()
361         .a("useEqualsSign", useEqualsSign)
362         .a("useUnquotedStrings", useUnquotedStrings)
363         .a("useUnquotedKeys", useUnquotedKeys)
364         .a("omitRootBraces", omitRootBraces)
365         .a("useMultilineStrings", useMultilineStrings)
366         .a("useNewlineSeparators", useNewlineSeparators);
367   }
368
369   /**
370    * Convenience delegator that opens a {@link RecordWriter} over the output using
371    * <b>default session arguments</b> (mirrors {@link #write(Object)}).
372    *
373    * <p>
374    * The real implementation lives on {@link HoconSerializerSession#writeRecords(Object)}.
375    * Callers that need request-derived configuration should call {@link #createSession()} and
376    * invoke {@link HoconSerializerSession#writeRecords(Object)} on the built session instead.
377    *
378    * @param output The output.
379    * @return A new {@link RecordWriter}.
380    * @throws IOException If a problem occurred opening the underlying output.
381    */
382   @Override /* RecordWritable */
383   public RecordWriter writeRecords(Object output) throws IOException {
384      return ((RecordWritable) getSession()).writeRecords(output);
385   }
386
387   @Override /* RecordWritable */
388   public boolean isRecordStreaming() {
389      return false;
390   }
391}