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;
018
019import static java.util.Collections.*;
020import static org.apache.juneau.commons.function.Suppliers.*;
021import static org.apache.juneau.commons.utils.CollectionUtils.*;
022import static org.apache.juneau.commons.utils.Shorts.*;
023import static org.apache.juneau.commons.utils.StringUtils.*;
024
025import java.util.*;
026import java.util.function.*;
027
028import org.apache.juneau.commons.collections.*;
029import org.apache.juneau.commons.conversion.*;
030import org.apache.juneau.commons.function.*;
031import org.apache.juneau.commons.reflect.*;
032
033/**
034 * A one-time-use non-thread-safe object that's meant to be used once and then thrown away.
035 *
036 * <h2 class='section'>Notes:</h2><ul>
037 *    <li class='warn'>This class is not typically thread safe.
038 * </ul>
039 *
040 */
041@SuppressWarnings({
042   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
043})
044public abstract class ContextSession {
045
046   /**
047    * Builder class.
048    */
049   @SuppressWarnings({
050      "java:S119" // 'SELF' (CRTP self-type) is intentional and clearer than a single-letter name.
051   })
052   public abstract static class Builder<SELF extends Builder<SELF>> {
053
054      /**
055       * Returns this object cast to the self (CRTP) type.
056       *
057       * @return This object.
058       */
059      @SuppressWarnings({
060         "unchecked" // CRTP self-type cast is safe by construction.
061      })
062      protected final SELF self() {
063         return (SELF)this;
064      }
065
066      private Boolean debug;
067      private boolean unmodifiable;
068      private final Context ctx;
069      private final Memoizer<LinkedHashMap<String,Object>> properties;
070
071      /**
072       * Convenience method for converting values using {@link BasicConverter}.
073       *
074       * @param <T> The target type.
075       * @param value The value to convert.
076       *    <br>Can be <jk>null</jk> (returns <jk>null</jk>).
077       * @param type The target class.
078       * @return The converted value, or <jk>null</jk> if the input value was <jk>null</jk>.
079       */
080      protected static <T> T cvt(Object value, Class<T> type) {
081         return BasicConverter.INSTANCE.to(value, null, null, type);
082      }
083
084      /**
085       * Constructor.
086       *
087       * @param ctx The context creating this session.
088       *    <br>Cannot be <jk>null</jk>.
089       */
090      protected Builder(Context ctx) {
091         this.ctx = reqnn("ctx", ctx);
092         this.properties = memoizer(LinkedHashMap::new);
093      }
094
095      /**
096       * Applies a consumer to this builder if it's the specified type.
097       *
098       * @param <T> The expected type.
099       * @param type The expected type.
100       *    <br>Cannot be <jk>null</jk>.
101       * @param apply   The consumer to apply.
102       *    <br>Cannot be <jk>null</jk>.
103       * @return This object.
104       */
105      public <T> SELF apply(Class<T> type, Consumer<T> apply) {
106         if (reqnn("type", type).isInstance(this))
107            reqnn("apply", apply).accept(type.cast(this));
108         return self();
109      }
110
111      /**
112       * Build the object.
113       *
114       * @return The built object.
115       */
116      public abstract ContextSession build();
117
118      /**
119       * Debug mode.
120       *
121       * <p>
122       * Enables the following additional information during parsing:
123       * <ul>
124       *    <li> When bean setters throws exceptions, the exception includes the object stack information in order to determine how that method was invoked.
125       * </ul>
126       *
127       * <p>
128       * If not specified, defaults to {@link Context.Builder#debug()}.
129       *
130       * <h4 class='section'>See Also:</h4><ul>
131       *    <li class='ja'>{@link MarshalledConfig#debug()}
132       *    <li class='jm'>{@link Context.Builder#debug()}
133       * </ul>
134       *
135       * @param value
136       *    The new value for this property.
137       *    <br>If <jk>null</jk>, defaults to {@link Context#isDebug()}.
138       * @return This object.
139       */
140      public SELF debug(Boolean value) {
141         debug = value;
142         return self();
143      }
144
145      /**
146       * Session properties.
147       *
148       * <p>
149       * Session properties are generic key-value pairs that can be passed through the session and made
150       * available to any customized serializers/parsers or swaps.
151       *
152       * @param value
153       *    The new value for this property.
154       *    <br>Cannot be <jk>null</jk>.
155       * @return This object.
156       */
157      public SELF properties(Map<String,Object> value) {
158         reqnn("value", value);
159         properties.reset();
160         value.forEach(this::property);
161         return self();
162      }
163
164      /**
165       * Adds a property to this session.
166       *
167       * <p>
168       * If the key matches a known session property (e.g. <js>"debug"</js> or <js>"ContextSession.debug"</js>),
169       * the value is converted via {@link BasicConverter} and routed to the corresponding typed setter.
170       * Unknown keys are stored in the raw session properties map.
171       *
172       * @param key The property key.
173       *    <br>Cannot be <jk>null</jk>.
174       * @param value The property value.
175       *    <br>Can be <jk>null</jk> (resets typed properties to their default; removes raw properties).
176       * @return This object.
177       */
178      public SELF property(String key, Object value) {
179         reqnn("key", key);
180         switch (key) {
181            case "debug", "ContextSession.debug":
182               return debug(cvt(value, Boolean.class));
183            default:
184               var map = properties.get();
185               if (value == null) {
186                  map.remove(key);
187               } else {
188                  map.put(key, value);
189               }
190               return self();
191         }
192      }
193
194      /**
195       * Create an unmodifiable session.
196       *
197       * <p>
198       * The created ContextSession object will be unmodifiable which makes it suitable for caching and reuse.
199       *
200       * @return This object.
201       */
202      public SELF unmodifiable() {
203         unmodifiable = true;
204         return self();
205      }
206   }
207
208   private final boolean debug;
209   private final boolean unmodifiable;
210   private final Context ctx;
211   private final Map<String,Object> properties;
212   private List<String> warnings;   // Any warnings encountered.
213
214   /**
215    * Default constructor.
216    *
217    * @param builder The builder for this object.
218    *    <br>Cannot be <jk>null</jk>.
219    */
220   protected ContextSession(Builder<?> builder) {
221      reqnn("builder", builder);
222      ctx = builder.ctx;
223      debug = o(builder.debug).orElse(ctx.isDebug());
224      unmodifiable = builder.unmodifiable;
225      var sp = builder.properties.get();
226      if (unmodifiable) {
227         properties = sp.isEmpty() ? Collections.emptyMap() : u(sp);
228      } else {
229         properties = sp;
230      }
231   }
232
233   /**
234    * Logs a warning message.
235    *
236    * @param msg The warning message.
237    *    <br>Cannot be <jk>null</jk>.
238    * @param args Optional {@link String#format(String, Object...) String.format}-style arguments.
239    *    <br>Cannot be <jk>null</jk> (individual values may be <jk>null</jk>).
240    */
241   public void addWarning(String msg, Object...args) {
242      reqnn("msg", msg, "args", args);
243      if (unmodifiable)
244         return;
245      if (warnings == null)
246         warnings = ll();
247      warnings.add((warnings.size() + 1) + ": " + f(msg, args));
248   }
249
250   /**
251    * Throws a {@link BeanRuntimeException} if any warnings occurred in this session and debug is enabled.
252    */
253   public void checkForWarnings() {
254      if (debug && ! getWarnings().isEmpty())
255         throw brex("Warnings occurred in session: \n" + join(getWarnings(), "\n"));
256   }
257
258   /**
259    * Returns the context that created this session.
260    *
261    * @return The context that created this session.
262    */
263   public Context getContext() { return ctx; }
264
265   /**
266    * Returns the session properties on this session.
267    *
268    * @return The session properties on this session.  Never <jk>null</jk>.
269    */
270   public final Map<String,Object> getSessionProperties() { return properties; }
271
272   /**
273    * Returns the warnings that occurred in this session.
274    *
275    * @return The warnings that occurred in this session, or an empty list if no warnings occurred.
276    */
277   public final List<String> getWarnings() { return warnings == null ? emptyList() : warnings; }
278
279   /**
280    * Debug mode enabled.
281    *
282    * @see Context.Builder#debug()
283    * @return
284    *    <jk>true</jk> if debug mode is enabled.
285    */
286   public boolean isDebug() { return debug; }
287
288   @Override /* Overridden from Object */
289   public String toString() {
290      return r(properties());
291   }
292
293   /**
294    * Returns the properties on this bean as a map for debugging.
295    *
296    * @return The properties on this bean as a map for debugging.
297    */
298   protected FluentMap<String,Object> properties() {
299      return filteredBeanPropertyMap()
300         .a("debug", debug);
301   }
302}