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.ini;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022
023import org.apache.juneau.commons.bean.*;
024import org.apache.juneau.commons.collections.*;
025import org.apache.juneau.marshall.*;
026import org.apache.juneau.marshall.serializer.*;
027import org.apache.juneau.marshall.stream.*;
028
029/**
030 * Serializes POJO models to INI format.
031 *
032 * <p>
033 * Converts Java POJOs to INI format (section/key-value structure).
034 *
035 * <h2 class='topic'>Media types</h2>
036 * <p>
037 * Produces: <bc>text/ini</bc>
038 * <br>Accepts: <bc>text/ini, text/x-ini</bc>
039 *
040 * <h2 class='topic'>Bean-to-INI mapping</h2>
041 * <ul class='spaced-list'>
042 *    <li>Simple properties → key-value pairs in the default section
043 *    <li>Nested beans → <c>[sectionName]</c> sections
044 *    <li>Deeply nested beans → <c>[path/to/section]</c> section paths
045 *    <li>Collections and complex values → JSON5-encoded inline values
046 *    <li>Maps with string keys → <c>[sectionName]</c> sections
047 *    <li>Null values → unquoted <c>null</c> token
048 * </ul>
049 *
050 * <h2 class='section'>Example:</h2>
051 * <p class='bjava'>
052 *    <jc>// Serialize a bean to INI</jc>
053 *    String <jv>ini</jv> = IniSerializer.<jsf>DEFAULT</jsf>.write(<jv>myBean</jv>);
054 *
055 *    <jc>// Create a custom serializer</jc>
056 *    IniSerializer <jv>s</jv> = IniSerializer.<jsm>create</jsm>().useComments().build();
057 *    <jv>ini</jv> = <jv>s</jv>.write(<jv>myBean</jv>);
058 * </p>
059 *
060 * <h2 class='figure'>Example output (Map of name/age):</h2>
061 * <p class='bini'>
062 *    <ck>name</ck> = <cv>Alice</cv>
063 *    <ck>age</ck> = <cv>30</cv>
064 * </p>
065 *
066 * <h2 class='figure'>Complex (nested object + array):</h2>
067 * <p class='bini'>
068 *    <ck>name</ck> = <cv>Alice</cv>
069 *    <ck>age</ck> = <cv>30</cv>
070 *    <ck>tags</ck> = <cv>['a','b','c']</cv>
071 *
072 *    <cs>[address]</cs>
073 *    <ck>street</ck> = <cv>123 Main St</cv>
074 *    <ck>city</ck> = <cv>Boston</cv>
075 *    <ck>state</ck> = <cv>MA</cv>
076 * </p>
077 *
078 * <h2 class='topic'>Limitations</h2>
079 * <ul class='spaced-list'>
080 *    <li>Top-level collections, arrays, and scalar values are not supported. The root must be a bean or
081 *       <c>Map&lt;String,?&gt;</c>. Throws {@link SerializeException} for unsupported root types.
082 *    <li>{@link Reader} and {@link InputStream} passthrough is not supported.
083 * </ul>
084 *
085 * <h2 class='section'>Notes:</h2><ul>
086 *    <li class='note'>This class is thread safe and reusable.
087 *    <li class='note'>Complex values (collections, maps with complex values) are embedded as JSON5 inline
088 *       strings and remain fully round-trippable.
089 * </ul>
090 *
091 * <h2 class='section'>See Also:</h2><ul>
092 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/Ini">INI Basics</a>
093 * </ul>
094 */
095@SuppressWarnings({
096   "java:S110", // Serializer hierarchy (IniSerializer -> WriterSerializer -> Serializer -> MarshallingContextable -> Context) is inherently deep.
097   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
098   "java:S9149", // Per-format static factories intentionally shadow the parent's.
099   "resource" // Closeable resources are owned by the caller's serializer session; Eclipse JDT @Owning warning is by design.
100})
101public class IniSerializer extends WriterSerializer implements IniMetaProvider, RecordWritable {
102
103   private final java.util.concurrent.ConcurrentHashMap<ClassMeta<?>,IniClassMeta> iniClassMetas = new java.util.concurrent.ConcurrentHashMap<>();
104   private final java.util.concurrent.ConcurrentHashMap<BeanPropertyMeta,IniBeanPropertyMeta> iniBeanPropertyMetas = new java.util.concurrent.ConcurrentHashMap<>();
105
106   /**
107    * Builder class.
108    */
109   public static class Builder extends WriterSerializer.Builder<Builder> {
110
111      private static final Cache<HashKey,IniSerializer> CACHE = Cache.of(HashKey.class, IniSerializer.class).build();
112
113      private char kvSeparator = '=';
114      private boolean spacedSeparator = true;
115      private boolean useComments = false;
116
117      protected Builder() {
118         produces("text/ini");
119         accept("text/ini,text/x-ini");
120      }
121
122      protected Builder(Builder copyFrom) {
123         super(reqnn("copyFrom", copyFrom));
124         kvSeparator = copyFrom.kvSeparator;
125         spacedSeparator = copyFrom.spacedSeparator;
126         useComments = copyFrom.useComments;
127      }
128
129      protected Builder(IniSerializer copyFrom) {
130         super(reqnn("copyFrom", copyFrom));
131         kvSeparator = copyFrom.kvSeparator;
132         spacedSeparator = copyFrom.spacedSeparator;
133         useComments = copyFrom.useComments;
134      }
135
136      /**
137       * Key-value separator character.
138       *
139       * @param value <c>=</c> (default) or <c>:</c>.
140       * @return This object.
141       */
142      public Builder kvSeparator(char value) {
143         kvSeparator = value;
144         return this;
145      }
146
147      /**
148       * Whether to add spaces around the separator.
149       *
150       * @param value <jk>true</jk> for <c>key = value</c>, <jk>false</jk> for <c>key=value</c>.
151       * @return This object.
152       */
153      public Builder spacedSeparator(boolean value) {
154         spacedSeparator = value;
155         return this;
156      }
157
158      /**
159       * Whether to emit <c>#</c> comments from bean property descriptions.
160       *
161       * @param value The flag.
162       * @return This object.
163       */
164      public Builder useComments(boolean value) {
165         useComments = value;
166         return this;
167      }
168
169      /**
170       * Emit <c>#</c> comments from bean property descriptions.
171       *
172       * @return This object.
173       */
174      public Builder useComments() {
175         useComments = true;
176         return this;
177      }
178
179      @Override
180      public Builder useWhitespace() {
181         super.useWhitespace();
182         return this;
183      }
184
185      @Override
186      public Builder useWhitespace(boolean value) {
187         super.useWhitespace(value);
188         return this;
189      }
190
191      @Override
192      public Builder ws() {
193         return useWhitespace();
194      }
195
196      @Override
197      public IniSerializer build() {
198         return cache(CACHE).build(IniSerializer.class);
199      }
200
201      @Override
202      public Builder copy() {
203         return new Builder(this);
204      }
205
206      @Override
207      public HashKey hashKey() {
208         return HashKey.of(super.hashKey(), kvSeparator, spacedSeparator, useComments);
209      }
210   }
211
212   /** Default serializer. */
213   public static final IniSerializer DEFAULT = new IniSerializer(create());
214
215   /** Default serializer with blank lines between sections. */
216   public static final IniSerializer DEFAULT_READABLE = new IniSerializer(create().ws());
217
218   /**
219    * Creates a new builder.
220    *
221    * @return A new builder.
222    */
223   public static Builder create() {
224      return new Builder();
225   }
226
227   /** Key-value separator. */
228   protected final char kvSeparator;
229
230   /** Whether to add spaces around the separator. */
231   protected final boolean spacedSeparator;
232
233   /** Whether to emit property descriptions as comments. */
234   protected final boolean useComments;
235
236   /**
237    * Constructor.
238    *
239    * @param builder The builder.
240    */
241   public IniSerializer(Builder builder) {
242      super(builder);
243      kvSeparator = builder.kvSeparator;
244      spacedSeparator = builder.spacedSeparator;
245      useComments = builder.useComments;
246   }
247
248   @Override
249   public IniSerializerSession.Builder createSession() {
250      return IniSerializerSession.create(this);
251   }
252
253   @Override
254   public Builder copy() {
255      return new Builder(this);
256   }
257
258   @Override
259   public IniBeanPropertyMeta getIniBeanPropertyMeta(BeanPropertyMeta bpm) {
260      if (bpm == null)
261         return IniBeanPropertyMeta.DEFAULT;
262      return iniBeanPropertyMetas.computeIfAbsent(bpm, k -> new IniBeanPropertyMeta(k, this));
263   }
264
265   @Override
266   public IniClassMeta getIniClassMeta(ClassMeta<?> cm) {
267      return iniClassMetas.computeIfAbsent(cm, k -> new IniClassMeta(k, this));
268   }
269
270   @Override
271   protected FluentMap<String,Object> properties() {
272      return super.properties()
273         .a("kvSeparator", String.valueOf(kvSeparator))
274         .a("spacedSeparator", spacedSeparator)
275         .a("useComments", useComments);
276   }
277
278   /**
279    * Convenience delegator that opens a {@link RecordWriter} over the output using
280    * <b>default session arguments</b> (mirrors {@link #write(Object)}).
281    *
282    * <p>
283    * The real implementation lives on {@link IniSerializerSession#writeRecords(Object)}.
284    * Callers that need request-derived configuration should call {@link #createSession()} and
285    * invoke {@link IniSerializerSession#writeRecords(Object)} on the built session instead.
286    *
287    * @param output The output.
288    * @return A new {@link RecordWriter}.
289    * @throws IOException If a problem occurred opening the underlying output.
290    */
291   @Override /* RecordWritable */
292   public RecordWriter writeRecords(Object output) throws IOException {
293      return ((RecordWritable) getSession()).writeRecords(output);
294   }
295
296   @Override /* RecordWritable */
297   public boolean isRecordStreaming() {
298      return false;
299   }
300}