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 org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.concurrent.atomic.*;
022import java.util.function.*;
023
024/**
025 * Supported wire formats for {@link Class} values.
026 *
027 * <p>
028 * Used by {@link MarshallingContext.Builder#classFormat(ClassFormat)},
029 * {@link Marshalled#classFormat()},
030 * {@link MarshalledProp#classFormat()}, and
031 * {@link MarshalledConfig#classFormat()} to control how {@link Class} values
032 * are written to text-based wire formats.
033 *
034 * <p>
035 * The default is {@link #FQCN} which mirrors the historical {@code ClassSwap} behavior (canonical dotted
036 * name with sensible fallback to the JVM binary name).
037 *
038 * <h2 class='topic'>FQCN vs BINARY_NAME for nested classes</h2>
039 *
040 * <p>
041 * For nested-type encoding the two forms diverge:
042 * <ul>
043 *    <li>{@link #FQCN} uses {@link Class#getCanonicalName()} when available — {@code "java.util.Map.Entry"}
044 *       — and falls back to {@link Class#getName()} for local / anonymous classes (where
045 *       {@code getCanonicalName()} returns {@code null}).
046 *    <li>{@link #BINARY_NAME} always uses {@link Class#getName()} — {@code "java.util.Map$Entry"}.
047 * </ul>
048 *
049 * <p>
050 * For arrays the difference is more dramatic:
051 * <ul>
052 *    <li>{@link #FQCN} produces {@code "int[]"} / {@code "java.lang.String[]"}.
053 *    <li>{@link #BINARY_NAME} produces {@code "[I"} / {@code "[Ljava.lang.String;"} (JVM descriptor form).
054 * </ul>
055 *
056 * <h2 class='topic'>SIMPLE_NAME is serialize-only</h2>
057 *
058 * <p>
059 * {@link #SIMPLE_NAME} discards package and outer-class context and is <b>not round-trip safe</b>. The
060 * parser path for this constant throws {@link UnsupportedOperationException}; use {@link #FQCN} or
061 * {@link #BINARY_NAME} for round-trippable wires.
062 *
063 * <h2 class='topic'>Precedence (highest to lowest)</h2>
064 * <ol>
065 *    <li>{@link MarshalledProp#classFormat() @MarshalledProp(classFormat=…)} on the bean property.
066 *    <li>{@link Marshalled#classFormat() @Marshalled(classFormat=…)} on the bean class.
067 *    <li>{@link MarshalledConfig#classFormat() @MarshalledConfig(classFormat=…)} on
068 *       <code><ja>@Rest</ja></code>-annotated classes / methods.
069 *    <li>Programmatic {@link MarshallingContext.Builder#classFormat(ClassFormat)}.
070 *    <li>Environment variable <c>MarshallingContext.classFormat</c>.
071 *    <li>The default constant ({@link #FQCN}).
072 * </ol>
073 *
074 * <h2 class='topic'>Parser leniency</h2>
075 *
076 * <p>
077 * Parsers SHALL try {@link Class#forName(String, boolean, ClassLoader)} first regardless of the
078 * parser-side {@code ClassFormat} setting — this handles {@link #BINARY_NAME} and most {@link #FQCN}
079 * inputs unambiguously. For nested-type {@link #FQCN} input ({@code "java.util.Map.Entry"}), the parser
080 * walks back through dotted segments from right to left, replacing each uppercase-prefixed dot with
081 * {@code $} and retrying — this resolves multi-level nesting like
082 * {@code "com.example.Outer.Inner.Deepest"} to {@code com.example.Outer$Inner$Deepest}.  For
083 * {@link #FQCN} array input the parser strips trailing {@code []} pairs, resolves the leaf component
084 * type (including primitives like {@code "int"}), and rebuilds the array via {@link Class#arrayType()}
085 * — so {@code "int[]"} resolves to {@code int[].class} and {@code "java.lang.String[][]"} resolves to
086 * {@code String[][].class}.
087 *
088 * <h2 class='topic'>Binary serializers</h2>
089 *
090 * <p>
091 * Binary serializers (BSON / CBOR / MsgPack / Prototext / Parquet) emit a UTF-8 string regardless of this
092 * setting — there is no native {@code Class} wire type in any supported binary format.
093 */
094public enum ClassFormat {
095
096   /** Sentinel meaning "no value configured" — falls through to the next-higher precedence level. */
097   NOT_SET,
098
099   /**
100    * Canonical fully-qualified name with dotted nested-type separators (the default).
101    *
102    * <p>
103    * Uses {@link Class#getCanonicalName()} when available; falls back to {@link Class#getName()} for
104    * local / anonymous classes where {@code getCanonicalName()} returns {@code null}.
105    *
106    * <h4 class='figure'>Example:</h4>
107    * <p class='bcode'>
108    *    java.lang.String
109    *    java.util.Map.Entry
110    *    int[]
111    * </p>
112    */
113   FQCN,
114
115   /**
116    * JVM binary name per {@link Class#getName()}.
117    *
118    * <h4 class='figure'>Example:</h4>
119    * <p class='bcode'>
120    *    java.lang.String
121    *    java.util.Map$Entry
122    *    [Ljava.lang.String;
123    *    [I
124    * </p>
125    *
126    * <p>
127    * Identical to {@link #FQCN} for top-level non-array reference types; diverges for nested types
128    * ({@code $} vs {@code .}) and arrays (JVM descriptor vs {@code Type[]} form).
129    */
130   BINARY_NAME,
131
132   /**
133    * Unqualified simple name per {@link Class#getSimpleName()}.
134    *
135    * <h4 class='figure'>Example:</h4>
136    * <p class='bcode'>
137    *    java.lang.String
138    *    Entry
139    *    int
140    * </p>
141    *
142    * <p>
143    * <b>Serialize-only.</b> The parser path for this constant throws
144    * {@link UnsupportedOperationException} — there is no defensible way to resolve {@code "Map"} back
145    * to a unique {@link Class} without a registry hint, and adding such a hint is out of scope.
146    */
147   SIMPLE_NAME;
148
149   // Optional global guard vetting class names before the parser path resolves them.  null == allow all.
150   private static final AtomicReference<Predicate<String>> classNameGuard = new AtomicReference<>();
151
152   /**
153    * Installs a global guard that vets class names before the parser path resolves them to a {@link Class}.
154    *
155    * <p>
156    * The guard is consulted for every candidate name (including the nested-type <c>$</c>-rewritten forms)
157    * before it is passed to {@link Class#forName(String, boolean, ClassLoader)}.  Names the guard rejects are
158    * treated as unresolvable.  This lets a deployment restrict which types may be materialized from parsed
159    * input to an explicit allow-list.
160    *
161    * <p>
162    * No guard is installed by default.  Deployments that parse input from untrusted sources and materialize
163    * {@link Class} values from it should install one that permits only the expected types.  Classes are
164    * resolved without running their static initializers either way, but an allow-list additionally bounds
165    * which classes the input may load or name.
166    *
167    * @param value The guard predicate returning <jk>true</jk> for permitted class names, or <jk>null</jk> to
168    *    allow all names (the default).
169    */
170   @SuppressWarnings({
171      "java:S3066" // Public setter is the documented deployment-configuration entry point (see Javadoc above); it is also exercised directly from ClassFormat_Test in another package, so visibility cannot be narrowed without breaking that call site.
172   })
173   public static void setClassNameGuard(Predicate<String> value) {
174      classNameGuard.set(value);
175   }
176
177   /**
178    * Returns whether the specified candidate class name is permitted by the installed guard.
179    *
180    * @param name The candidate class name.
181    * @return <jk>true</jk> if no guard is installed or the guard permits the name.
182    */
183   static boolean isClassNameAllowed(String name) {
184      var g = classNameGuard.get();
185      return g == null || g.test(name);
186   }
187
188   /**
189    * Formats the specified {@link Class} using this format.
190    *
191    * <p>
192    * {@link #NOT_SET} / {@code null} format are treated as {@link #FQCN}.
193    *
194    * @param value The value to format. Can be <jk>null</jk> (returns <jk>null</jk>).
195    * @param format The configured format. Can be <jk>null</jk> (treated as {@link #FQCN}).
196    * @return The formatted wire representation, or <jk>null</jk> if {@code value} is <jk>null</jk>.
197    */
198   public static String format(Class<?> value, ClassFormat format) {
199      if (value == null)
200         return null;
201      var fmt = format == null ? FQCN : format;
202      return switch (fmt) {
203         case NOT_SET, FQCN -> {
204            // getCanonicalName() returns null for local / anonymous classes; fall back to binary name.
205            var canonical = value.getCanonicalName();
206            yield canonical != null ? canonical : value.getName();
207         }
208         case BINARY_NAME -> value.getName();
209         case SIMPLE_NAME -> value.getSimpleName();
210      };
211   }
212
213   /**
214    * Parses the specified wire value into a {@link Class}.
215    *
216    * <p>
217    * Lenient parsing — handles every shape produced by {@link #format(Class, ClassFormat)} for the
218    * round-trippable formats ({@link #FQCN} and {@link #BINARY_NAME}), and accepts cross-form input
219    * as well (an {@link #FQCN} parser still resolves {@link #BINARY_NAME} input and vice versa).
220    *
221    * <p>
222    * Resolution steps:
223    * <ol>
224    *    <li>Strip trailing {@code []} pairs ({@link #FQCN} array form), tracking dimension count.  Empty
225    *       brackets at the leading edge (JVM descriptor form like {@code "[I"} /
226    *       {@code "[Ljava.lang.String;"}) are left to {@link Class#forName(String, boolean, ClassLoader)}
227    *       because that method already handles them.
228    *    <li>Resolve the leaf component:
229    *       <ul>
230    *          <li>If the leaf names a primitive type ({@code "int"}, {@code "boolean"}, etc. — emitted
231    *             by {@link #FQCN} for primitive arrays), return the corresponding {@code TYPE} class.
232    *          <li>Otherwise try {@link Class#forName(String, boolean, ClassLoader)} directly.
233    *          <li>On failure, walk dots from right to left, replacing each uppercase-prefixed dot with
234    *             {@code $} (cumulatively — already-replaced dots stay replaced) and retrying.  This
235    *             resolves multi-level nesting like {@code "com.example.Outer.Inner.Deepest"} to
236    *             {@code com.example.Outer$Inner$Deepest}.  Dots whose trailing segment starts with a
237    *             lowercase letter are treated as package boundaries and skipped.
238    *       </ul>
239    *    <li>Apply {@link Class#arrayType()} once per stripped dimension to rebuild the array class.
240    * </ol>
241    *
242    * <p>
243    * {@link #SIMPLE_NAME} is not supported on the parser side — throws
244    * {@link UnsupportedOperationException}.
245    *
246    * @param value The wire value. Can be <jk>null</jk> or blank (returns <jk>null</jk>).
247    * @param format The configured format hint. Can be <jk>null</jk> (treated as {@link #FQCN}).
248    * @param classLoader The class loader. Can be <jk>null</jk> (uses
249    *   {@link Thread#getContextClassLoader() context class loader}).
250    * @return The parsed {@link Class}, or <jk>null</jk> if {@code value} is <jk>null</jk> or blank.
251    * @throws IllegalArgumentException If the value cannot be resolved.
252    * @throws UnsupportedOperationException If {@code format} is {@link #SIMPLE_NAME}.
253    */
254   public static Class<?> parse(String value, ClassFormat format, ClassLoader classLoader) {
255      if (value == null)
256         return null;
257      var s = value.trim();
258      if (s.isEmpty())
259         return null;
260      var fmt = format == null ? FQCN : format;
261      if (fmt == SIMPLE_NAME)
262         throw new UnsupportedOperationException("SIMPLE_NAME is serialize-only — use FQCN or BINARY_NAME for round-trippable wires");
263      var cl = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader();
264      try {
265         return resolveWithArraySuffix(s, cl);
266      } catch (ClassNotFoundException firstAttempt) {
267         throw iaex("Could not resolve class '%s' for format %s: %s", value, format, firstAttempt.getMessage());
268      }
269   }
270
271   /**
272    * Strips trailing {@code []} pairs from the FQCN array form, resolves the leaf component, then
273    * rebuilds the array dimensions via {@link Class#arrayType()}.
274    *
275    * <p>
276    * Inputs that don't end in {@code []} (top-level classes and JVM-descriptor array forms like
277    * {@code "[I"}) pass straight through to {@link #resolveLeaf(String, ClassLoader)}.
278    */
279   private static Class<?> resolveWithArraySuffix(String s, ClassLoader cl) throws ClassNotFoundException {
280      var dims = 0;
281      var leaf = s;
282      while (leaf.endsWith("[]")) {
283         dims++;
284         leaf = leaf.substring(0, leaf.length() - 2);
285      }
286      if (dims == 0)
287         return resolveLeaf(s, cl);
288      if (leaf.isEmpty())
289         throw new ClassNotFoundException(s);
290      var result = resolveLeaf(leaf, cl);
291      for (var i = 0; i < dims; i++)
292         result = result.arrayType();
293      return result;
294   }
295
296   /**
297    * Resolves a non-array leaf token to a {@link Class}.
298    *
299    * <p>
300    * Checks the primitive-name table first ({@link #FQCN} emits {@code "int"} / {@code "boolean"} /
301    * etc. for primitive array leafs), then falls through to {@link Class#forName(String, boolean,
302    * ClassLoader)} with a multi-level nested-type fallback heuristic.
303    */
304   private static Class<?> resolveLeaf(String s, ClassLoader cl) throws ClassNotFoundException {
305      var prim = primitiveByName(s);
306      if (prim != null)
307         return prim;
308      if (! isClassNameAllowed(s))
309         throw new ClassNotFoundException(s);
310      try {
311         // Resolve without initializing — a parsed name must never trigger a target type's static initializer.
312         return Class.forName(s, false, cl);
313      } catch (ClassNotFoundException firstAttempt) {
314         var nested = nestedTypeFallback(s, cl);
315         if (nested != null)
316            return nested;
317         throw firstAttempt;
318      }
319   }
320
321   /**
322    * Walks dots from right to left, replacing each uppercase-prefixed dot with {@code $} and retrying
323    * {@link Class#forName(String, boolean, ClassLoader)}.  Replacements accumulate — once a dot has
324    * been replaced, it stays replaced for subsequent iterations — so multi-level nesting like
325    * {@code "Outer.Inner.Deepest"} resolves to {@code "Outer$Inner$Deepest"}.
326    *
327    * <p>
328    * Returns <jk>null</jk> if no rewrite resolves to a loadable class.  Dots whose trailing segment
329    * starts with a lowercase letter are treated as package boundaries and left alone.
330    */
331   private static Class<?> nestedTypeFallback(String s, ClassLoader cl) {
332      var chars = s.toCharArray();
333      for (var i = chars.length - 1; i > 0; i--) {
334         if (chars[i] == '.' && i + 1 < chars.length && Character.isUpperCase(chars[i + 1])) {
335            chars[i] = '$';
336            var candidate = new String(chars);
337            if (! isClassNameAllowed(candidate))
338               continue;
339            try {
340               return Class.forName(candidate, false, cl);
341            } catch (@SuppressWarnings("unused") ClassNotFoundException ignored) {
342               // Keep walking; the previous-dot replacement persists in chars so deeper nesting can resolve.
343            }
344         }
345      }
346      return null;
347   }
348
349   private static Class<?> primitiveByName(String s) {
350      return switch (s) {
351         case "boolean" -> boolean.class;
352         case "byte" -> byte.class;
353         case "char" -> char.class;
354         case "short" -> short.class;
355         case "int" -> int.class;
356         case "long" -> long.class;
357         case "float" -> float.class;
358         case "double" -> double.class;
359         case "void" -> void.class;
360         default -> null;
361      };
362   }
363
364   /**
365    * Returns <jk>true</jk> if this format emits a numeric wire value.
366    *
367    * <p>
368    * Always <jk>false</jk> — every constant emits a textual representation.
369    *
370    * @return <jk>false</jk>.
371    */
372   @SuppressWarnings({
373      "java:S3400", // Same rationale — must remain an instance method, not a constant, to match the cross-Format API contract.
374      "static-method" // Kept as an instance method for polymorphic-by-convention symmetry with the other Format classes (BigNumberFormat, FloatFormat, DurationFormat, etc.) where isNumeric() depends on the enum constant.
375   })
376   public boolean isNumeric() {
377      return false;
378   }
379}