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.reflect.ReflectionUtils.*;
020import static org.apache.juneau.commons.utils.CollectionUtils.*;
021import static org.apache.juneau.commons.utils.Shorts.*;
022import static org.apache.juneau.commons.utils.SystemUtils.*;
023import static org.apache.juneau.commons.utils.ThrowableUtils.*;
024
025import java.lang.annotation.*;
026import java.lang.reflect.*;
027import java.util.*;
028import java.util.function.*;
029
030import org.apache.juneau.commons.bean.*;
031import org.apache.juneau.commons.collections.*;
032import org.apache.juneau.commons.reflect.*;
033import org.apache.juneau.commons.svl.*;
034import org.apache.juneau.commons.utils.*;
035import org.apache.juneau.marshall.bson.*;
036import org.apache.juneau.marshall.cbor.*;
037import org.apache.juneau.marshall.csv.*;
038import org.apache.juneau.marshall.hjson.*;
039import org.apache.juneau.marshall.hocon.*;
040import org.apache.juneau.marshall.html.*;
041import org.apache.juneau.marshall.ini.*;
042import org.apache.juneau.marshall.jcs.*;
043import org.apache.juneau.marshall.json.*;
044import org.apache.juneau.marshall.jsonl.*;
045import org.apache.juneau.marshall.jsonschema.*;
046import org.apache.juneau.marshall.markdown.*;
047import org.apache.juneau.marshall.msgpack.*;
048import org.apache.juneau.marshall.oapi.*;
049import org.apache.juneau.marshall.parquet.*;
050import org.apache.juneau.marshall.parser.*;
051import org.apache.juneau.marshall.plaintext.*;
052import org.apache.juneau.marshall.prototext.*;
053import org.apache.juneau.marshall.serializer.*;
054import org.apache.juneau.marshall.soap.*;
055import org.apache.juneau.marshall.toml.*;
056import org.apache.juneau.marshall.uon.*;
057import org.apache.juneau.marshall.urlencoding.*;
058import org.apache.juneau.marshall.xml.*;
059import org.apache.juneau.marshall.yaml.*;
060
061/**
062 * Base class for all Context beans.
063 *
064 * <p>
065 * Context beans follow the convention of having the following parts:
066 * <ul>
067 *    <li>A {@link Builder} class for configuring the context bean.
068 *    <ul>
069 *       <li>This bean is non-thread-safe and meant for one-time use.
070 *    </ul>
071 *    <li>A {@link Context#Context(Builder)} constructor that takes in a builder object.
072 *    <ul>
073 *       <li>This bean is thread-safe and cacheable/reusable.
074 *    </ul>
075 *    <li>A {@link ContextSession} class for doing work.
076 *    <ul>
077 *       <li>This bean is non-thread-safe and meant for one-time use.
078 *    </ul>
079 * </ul>
080 *
081 * <h2 class='section'>Notes:</h2><ul>
082 *    <li class='note'>This class is thread safe and reusable.
083 * </ul>
084 *
085 */
086@SuppressWarnings({
087   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
088   "java:S1452", // Builder<?> is returned by copyOrNull() because callers only need the base builder and the concrete SELF type is unknown.
089   "java:S3740", // Raw Builder types in reflection-based context creation; parameterization is not possible at call sites
090   "rawtypes", // Raw Builder is used by createBuilder(), the Context(Builder) constructor, copy() and the constructor cache because the builder subtype is only known reflectively.
091   "unchecked" // Casts of the reflectively-resolved Class to Class<? extends Context> and of innerBuild() to T are guaranteed by the builder/context type pairing.
092})
093public abstract class Context {
094
095   /**
096    * Builder class.
097    */
098   @SuppressWarnings({
099      "java:S119" // 'SELF' (CRTP self-type) is intentional and clearer than a single-letter name.
100   })
101   public abstract static class Builder<SELF extends Builder<SELF>> {
102
103      /**
104       * Returns this object cast to the self (CRTP) type.
105       *
106       * @return This object.
107       */
108      protected final SELF self() {
109         return (SELF)this;
110      }
111
112
113      private boolean debug;
114      private final AnnotationWorkList applied = AnnotationWorkList.create();
115      private Cache<HashKey,? extends Context> cache;
116      private Class<? extends Context> type;
117      private Context impl;
118      private final List<Annotation> annotations;
119      private final List<Object> builders = list();
120
121      /**
122       * Constructor.
123       * Default settings.
124       */
125      protected Builder() {
126         debug = env("Context.debug", false);
127         annotations = list();
128         registerBuilders(this);
129
130         // By default, the type being created should be the class declaring the builder.
131         var dc = getClass().getDeclaringClass();
132         if (Context.class.isAssignableFrom(dc))
133            type((Class<? extends Context>)dc);
134      }
135
136      /**
137       * Copy constructor.
138       *
139       * @param copyFrom The builder to copy from.
140       *    <br>Cannot be <jk>null</jk>.
141       */
142      protected Builder(Builder<?> copyFrom) {
143         reqnn("copyFrom", copyFrom);
144         annotations = cp(copyFrom.annotations);
145         debug = copyFrom.debug;
146         type = copyFrom.type;
147         // Intentionally not copied: a prebuilt impl would bypass changes made to the copy, and the cache is per-builder.
148         cache = null;
149         impl = null;
150         registerBuilders(this);
151      }
152
153      /**
154       * Copy constructor.
155       *
156       * @param copyFrom The bean to copy from.
157       *    <br>Cannot be <jk>null</jk>.
158       */
159      protected Builder(Context copyFrom) {
160         reqnn("copyFrom", copyFrom);
161         annotations = cp(copyFrom.annotations);
162         debug = copyFrom.debug;
163         type = copyFrom.getClass();
164         // Intentionally not copied: a prebuilt impl would bypass changes made to the copy, and the cache is per-builder.
165         cache = null;
166         impl = null;
167         registerBuilders(this);
168      }
169
170      /**
171       * Defines annotations to apply to specific classes and methods.
172       *
173       * <p>
174       * Allows you to dynamically apply Juneau annotations typically applied directly to classes and methods.
175       * Useful in cases where you want to use the functionality of the annotation on beans and bean properties but
176       * do not have access to the code to do so.
177       *
178       * <p>
179       * As a rule, any Juneau annotation with an <l>on()</l> method can be used with this setting.
180       *
181       * <p>
182       * The following example shows the equivalent methods for applying the {@link Marshalled @Marshalled} annotation:
183       * <p class='bjava'>
184       *    <jc>// Class with explicit annotation.</jc>
185       *    <ja>@Marshalled</ja>(properties=<js>"street,city,state"</js>)
186       *    <jk>public class</jk> A {...}
187       *
188       *    <jc>// Class with annotation applied via @MarshalledConfig</jc>
189       *    <jk>public class</jk> B {...}
190       *
191       *    <jc>// Java REST method with @MarshalledConfig annotation.</jc>
192       *    <ja>@RestGet</ja>(...)
193       *    <ja>@Marshalled</ja>(on=<js>"B"</js>, properties=<js>"street,city,state"</js>)
194       *    <jk>public void</jk> doFoo() {...}
195       * </p>
196       *
197       * <p>
198       * In general, the underlying framework uses this method when it finds dynamically applied annotations on
199       * config annotations.  However, concrete implementations of annotations are also provided that can be passed
200       * directly into builder classes like so:
201       * <p class='bjava'>
202       *    <jc>// Create a concrete @Marshalled annotation.</jc>
203       *    <ja>Marshalled</ja> <jv>annotation</jv> = MarshalledAnnotation.<jsm>create</jsm>(B.<jk>class</jk>).properties(<js>"street,city,state"</js>).build();
204       *
205       *    <jc>// Apply it to a serializer.</jc>
206       *    WriterSerializer <jv>serializer</jv> = JsonSerializer.<jsm>create</jsm>().annotations(<jv>annotation</jv>).build();
207       *
208       *    <jc>// Serialize a bean with the dynamically applied annotation.</jc>
209       *    String <jv>json</jv> = <jv>serializer</jv>.write(<jk>new</jk> B());
210       * </p>
211       *
212       * <p>
213       * The following is the list of annotations builders provided that can be constructed
214       * and passed into the builder class:
215       * <ul class='javatreec'>
216       *    <li class='ja'>{@link MarshalledAnnotation}
217       *    <li class='ja'>{@link BeanCtorAnnotation}
218       *    <li class='ja'>{@link BeanIgnoreAnnotation}
219       *    <li class='ja'>{@link MarshalledIgnoreAnnotation}
220       *    <li class='ja'>{@link BeanPropAnnotation}
221       *    <li class='ja'>{@link MarshalledPropAnnotation}
222       *    <li class='ja'>{@link ExampleAnnotation}
223       *    <li class='ja'>{@link NamePropertyAnnotation}
224       *    <li class='ja'>{@link ParentPropertyAnnotation}
225       *    <li class='ja'>{@link SwapAnnotation}
226       *    <li class='ja'>{@link UriAnnotation}
227       *    <li class='ja'>{@link CsvAnnotation}
228       *    <li class='ja'>{@link HtmlAnnotation}
229       *    <li class='ja'>{@link JsonAnnotation}
230       *    <li class='ja'>{@link SchemaAnnotation}
231       *    <li class='ja'>{@link MsgPackAnnotation}
232       *    <li class='ja'>{@link OpenApiAnnotation}
233       *    <li class='ja'>{@link PlainTextAnnotation}
234       *    <li class='ja'>{@link SoapXmlAnnotation}
235       *    <li class='ja'>{@link UonAnnotation}
236       *    <li class='ja'>{@link UrlEncodingAnnotation}
237       *    <li class='ja'>{@link XmlAnnotation}
238       * </ul>
239       *
240       * <p>
241       * The syntax for the <l>on()</l> pattern match parameter depends on whether it applies to a class, method, field, or constructor.
242       * The valid pattern matches are:
243       * <ul class='spaced-list'>
244       *  <li>Classes:
245       *       <ul>
246       *          <li>Fully qualified:
247       *             <ul>
248       *                <li><js>"com.foo.MyClass"</js>
249       *             </ul>
250       *          <li>Fully qualified inner class:
251       *             <ul>
252       *                <li><js>"com.foo.MyClass$Inner1$Inner2"</js>
253       *             </ul>
254       *          <li>Simple:
255       *             <ul>
256       *                <li><js>"MyClass"</js>
257       *             </ul>
258       *          <li>Simple inner:
259       *             <ul>
260       *                <li><js>"MyClass$Inner1$Inner2"</js>
261       *                <li><js>"Inner1$Inner2"</js>
262       *                <li><js>"Inner2"</js>
263       *             </ul>
264       *       </ul>
265       *    <li>Methods:
266       *       <ul>
267       *          <li>Fully qualified with args:
268       *             <ul>
269       *                <li><js>"com.foo.MyClass.myMethod(String,int)"</js>
270       *                <li><js>"com.foo.MyClass.myMethod(java.lang.String,int)"</js>
271       *                <li><js>"com.foo.MyClass.myMethod()"</js>
272       *             </ul>
273       *          <li>Fully qualified:
274       *             <ul>
275       *                <li><js>"com.foo.MyClass.myMethod"</js>
276       *             </ul>
277       *          <li>Simple with args:
278       *             <ul>
279       *                <li><js>"MyClass.myMethod(String,int)"</js>
280       *                <li><js>"MyClass.myMethod(java.lang.String,int)"</js>
281       *                <li><js>"MyClass.myMethod()"</js>
282       *             </ul>
283       *          <li>Simple:
284       *             <ul>
285       *                <li><js>"MyClass.myMethod"</js>
286       *             </ul>
287       *          <li>Simple inner class:
288       *             <ul>
289       *                <li><js>"MyClass$Inner1$Inner2.myMethod"</js>
290       *                <li><js>"Inner1$Inner2.myMethod"</js>
291       *                <li><js>"Inner2.myMethod"</js>
292       *             </ul>
293       *       </ul>
294       *    <li>Fields:
295       *       <ul>
296       *          <li>Fully qualified:
297       *             <ul>
298       *                <li><js>"com.foo.MyClass.myField"</js>
299       *             </ul>
300       *          <li>Simple:
301       *             <ul>
302       *                <li><js>"MyClass.myField"</js>
303       *             </ul>
304       *          <li>Simple inner class:
305       *             <ul>
306       *                <li><js>"MyClass$Inner1$Inner2.myField"</js>
307       *                <li><js>"Inner1$Inner2.myField"</js>
308       *                <li><js>"Inner2.myField"</js>
309       *             </ul>
310       *       </ul>
311       *    <li>Constructors:
312       *       <ul>
313       *          <li>Fully qualified with args:
314       *             <ul>
315       *                <li><js>"com.foo.MyClass(String,int)"</js>
316       *                <li><js>"com.foo.MyClass(java.lang.String,int)"</js>
317       *                <li><js>"com.foo.MyClass()"</js>
318       *             </ul>
319       *          <li>Simple with args:
320       *             <ul>
321       *                <li><js>"MyClass(String,int)"</js>
322       *                <li><js>"MyClass(java.lang.String,int)"</js>
323       *                <li><js>"MyClass()"</js>
324       *             </ul>
325       *          <li>Simple inner class:
326       *             <ul>
327       *                <li><js>"MyClass$Inner1$Inner2()"</js>
328       *                <li><js>"Inner1$Inner2()"</js>
329       *                <li><js>"Inner2()"</js>
330       *             </ul>
331       *       </ul>
332       *    <li>A comma-delimited list of anything on this list.
333       * </ul>
334       *
335       * <h4 class='section'>See Also:</h4><ul>
336       *    <li class='ja'>{@link MarshalledConfig}
337       * </ul>
338       *
339       * @param values
340       *    The annotations to register with the context.
341       *    <br>Cannot contain <jk>null</jk> values.
342       * @return This object.
343       */
344      public SELF annotations(Annotation...values) {
345         reqnns("values", values);
346         annotations(l(values));
347         return self();
348      }
349
350      /**
351       * Same as {@link #annotations(Annotation...)} but uses a list as input.
352       *
353       * @param values
354       *    The annotations to register with the context.
355       *    <br>Cannot be <jk>null</jk> or contain <jk>null</jk> values.
356       * @return This object.
357       */
358      public SELF annotations(List<Annotation> values) {
359         annotations.addAll(reqnns("values", values));
360         return self();
361      }
362
363      /**
364       * Applies a set of applied to this builder.
365       *
366       * <p>
367       * An {@link AnnotationWork} consists of a single pair of {@link AnnotationInfo} that represents an annotation instance,
368       * and {@link AnnotationApplier} which represents the code used to apply the values in that annotation to a specific builder.
369       *
370       * <h4 class='section'>Example:</h4>
371       * <p class='bjava'>
372       *    <jc>// A class annotated with a config annotation.</jc>
373       *    <ja>@MarshalledConfig</ja>(unsortedProperties=<js>"${S:unsortedProperties:false}"</js>)
374       *    <jk>public class</jk> MyClass {...}
375       *
376       *    <jc>// Find all annotations that themselves are annotated with @ContextPropertiesApply.</jc>
377       *    Stream&lt;AnnotationInfo&lt;?&gt;&gt; <jv>annotations</jv> = ClassInfo.<jsm>of</jsm>(MyClass.<jk>class</jk>).getAnnotations().stream().filter(<jsf>CONTEXT_APPLY_FILTER</jsf>);
378       *    VarResolverSession <jv>vrs</jv> = VarResolver.<jsf>DEFAULT</jsf>.createSession();
379       *    AnnotationWorkList <jv>work</jv> = AnnotationWorkList.of(<jv>vrs</jv>, <jv>annotations</jv>);
380       *
381       *    <jc>// Apply any settings found on the annotations.</jc>
382       *    WriterSerializer <jv>serializer</jv> = JsonSerializer
383       *       .<jsm>create</jsm>()
384       *       .apply(<jv>work</jv>)
385       *       .build();
386       * </p>
387       *
388       * @param work The list of annotations and appliers to apply to this builder.
389       *    <br>Cannot be <jk>null</jk>.
390       * @return This object.
391       */
392      public SELF apply(AnnotationWorkList work) {
393         reqnn("work", work);
394         applied.addAll(work);
395         work.forEach(x -> builders.forEach(x::apply));
396         return self();
397      }
398
399      /**
400       * Same as {@link #applyAnnotations(Object...)} but explicitly specifies a class varargs to avoid compilation warnings.
401       *
402       * @param from The classes or methods on which the annotations are defined.
403       *    <br>Cannot contain <jk>null</jk> values.
404       * @return This object.
405       */
406      public SELF applyAnnotations(Class<?>...from) {
407         reqnns("from", from);
408         return applyAnnotations((Object[])from);
409      }
410
411      /**
412       * Applies any of the various <ja>@XConfig</ja> annotations on the specified classes or methods to this context.
413       *
414       * <p>
415       * Any annotations found that themselves are annotated with {@link ContextApply} will be resolved and
416       * applied as properties to this builder.  These annotations include:
417       * <ul class='javatreec'>
418       *    <li class='ja'>{@link MarshalledConfig}
419       *    <li class='ja'>{@link BsonConfig}
420       *    <li class='ja'>{@link CborConfig}
421       *    <li class='ja'>{@link CsvConfig}
422       *    <li class='ja'>{@link HtmlConfig}
423       *    <li class='ja'>{@link HtmlDocConfig}
424       *    <li class='ja'>{@link HjsonConfig}
425       *    <li class='ja'>{@link HoconConfig}
426       *    <li class='ja'>{@link IniConfig}
427       *    <li class='ja'>{@link JsonConfig}
428       *    <li class='ja'>{@link JsonlConfig}
429       *    <li class='ja'>{@link JsonSchemaConfig}
430       *    <li class='ja'>{@link JcsConfig}
431       *    <li class='ja'>{@link MarkdownConfig}
432       *    <li class='ja'>{@link MsgPackConfig}
433       *    <li class='ja'>{@link OpenApiConfig}
434       *    <li class='ja'>{@link ParserConfig}
435       *    <li class='ja'>{@link ParquetConfig}
436       *    <li class='ja'>{@link PrototextConfig}
437       *    <li class='ja'>{@link PlainTextConfig}
438       *    <li class='ja'>{@link SerializerConfig}
439       *    <li class='ja'>{@link SoapXmlConfig}
440       *    <li class='ja'>{@link TomlConfig}
441       *    <li class='ja'>{@link UonConfig}
442       *    <li class='ja'>{@link UrlEncodingConfig}
443       *    <li class='ja'>{@link XmlConfig}
444       *    <li class='ja'>{@link YamlConfig}
445       *    <li class='ja'><c>RdfConfig</c>
446       * </ul>
447       *
448       * <p>
449       * Annotations on classes are appended in the following order:
450       * <ol>
451       *    <li>On the package of this class.
452       *    <li>On interfaces ordered parent-to-child.
453       *    <li>On parent classes ordered parent-to-child.
454       *    <li>On this class.
455       * </ol>
456       *
457       * <p>
458       * Annotations on methods are appended in the following order:
459       * <ol>
460       *    <li>On the package of the method class.
461       *    <li>On interfaces ordered parent-to-child.
462       *    <li>On parent classes ordered parent-to-child.
463       *    <li>On the method class.
464       *    <li>On this method and matching methods ordered parent-to-child.
465       * </ol>
466       *
467       * <p>
468       * The default var resolver {@link VarResolver#DEFAULT} is used to resolve any variables in annotation field values.
469       *
470       * <h4 class='section'>Example:</h4>
471       * <p class='bjava'>
472       *    <jc>// A class annotated with a config annotation.</jc>
473       *    <ja>@MarshalledConfig</ja>(unsortedProperties=<js>"${S:unsortedProperties:false}"</js>)
474       *    <jk>public class</jk> MyClass {...}
475       *
476       *    <jc>// Apply any settings found on the annotations.</jc>
477       *    WriterSerializer <jv>serializer</jv> = JsonSerializer
478       *       .<jsm>create</jsm>()
479       *       .applyAnnotations(MyClass.<jk>class</jk>)
480       *       .build();
481       *
482       *    <jc>// A method annotated with a config annotation.</jc>
483       *    <jk>public class</jk> MyClass {
484       *       <ja>@MarshalledConfig</ja>(unsortedProperties=<js>"${S:unsortedProperties:false}"</js>)
485       *       <jk>public void</jk> myMethod() {...}
486       *    }
487       *
488       *    <jc>// Apply any settings found on the annotations.</jc>
489       *    WriterSerializer <jv>serializer</jv> = JsonSerializer
490       *       .<jsm>create</jsm>()
491       *       .applyAnnotations(MyClass.<jk>class</jk>.getMethod(<js>"myMethod"</js>))
492       *       .build();
493       * </p>
494       *
495       * @param from The classes or methods on which the annotations are defined.
496       *    Can be any of the following types:
497       *    <ul>
498       *       <li>{@link Class}
499       *       <li>{@link ClassInfo}
500       *       <li>{@link Method}
501       *       <li>{@link MethodInfo}
502       *    <li>A collection/stream/array of anything on this list.
503       *    </ul>
504       *    <br>Cannot contain <jk>null</jk> values.
505       * @return This object.
506       */
507      public SELF applyAnnotations(Object...from) {
508         reqnns("from", from);
509         var work = AnnotationWorkList.create();
510         Arrays.stream(from).forEach(x -> traverse(work, x));
511         return apply(work);
512      }
513
514      /**
515       * Traverses the specified object and adds applicable annotations to the work list.
516       *
517       * @param work The annotation work list to add to.
518       * @param x The object to traverse (Class, ClassInfo, Method, or MethodInfo).
519       * @return The work list.
520       */
521      private static AnnotationWorkList traverse(AnnotationWorkList work, Object x) {
522         var ap = AP;
523         CollectionUtils.traverse(x, y -> {
524            if (x instanceof Class<?> x2)
525               work.add(rstream(ap.find(info(x2))).filter(CONTEXT_APPLY_FILTER));
526            else if (x instanceof ClassInfo x2)
527               work.add(rstream(ap.find(x2)).filter(CONTEXT_APPLY_FILTER));
528            else if (x instanceof Method x2)
529               work.add(rstream(ap.find(info(x2))).filter(CONTEXT_APPLY_FILTER));
530            else if (x instanceof MethodInfo x2)
531               work.add(rstream(ap.find(x2)).filter(CONTEXT_APPLY_FILTER));
532            else
533               iaex("Invalid type passed to applyAnnotations:  %s", cn(x));
534         });
535         return work;
536      }
537
538      /**
539       * Returns this builder cast to the specified subtype if it is an instance of that type.
540       *
541       * <p>
542       * This is a type-safe way to check if this builder is an instance of a specific builder subtype
543       * and cast it accordingly. Returns an empty {@link Optional} if this builder is not an instance
544       * of the specified subtype.
545       *
546       * <h4 class='section'>Example:</h4>
547       * <p class='bjava'>
548       *    Builder <jv>b</jv> = JsonSerializer.<jsm>create</jsm>();
549       *    Optional&lt;JsonSerializer.Builder&lt;?&gt;&gt; <jv>jsonBuilder</jv> = <jv>b</jv>.asSubtype(JsonSerializer.Builder.<jk>class</jk>);
550       *    <jk>if</jk> (<jv>jsonBuilder</jv>.isPresent()) {
551       *       <jc>// Use JsonSerializer.Builder&lt;?&gt;-specific methods</jc>
552       *       <jv>jsonBuilder</jv>.get().pretty();
553       *    }
554       * </p>
555       *
556       * @param <T> The builder subtype.
557       * @param subtype The builder subtype class to cast to.
558       *    <br>Cannot be <jk>null</jk>.
559       * @return An {@link Optional} containing this builder cast to the subtype, or empty if not an instance.
560       */
561      public <T extends Builder<?>> Optional<T> asSubtype(Class<T> subtype) {
562         return o(reqnn("subtype", subtype).isInstance(this) ? subtype.cast(this) : null);
563      }
564
565      /**
566       * Build the object.
567       *
568       * @return The built object.
569       */
570      public Context build() {
571         return innerBuild();
572      }
573
574      /**
575       * Convenience method for calling {@link #build()} while avoiding a cast.
576       *
577       * @param <T> The type to cast the built object to.
578       * @param c The type to cast the built object to.
579       *    <br>Cannot be <jk>null</jk>.
580       * @return The built context bean.
581       */
582      public final <T extends Context> T build(Class<T> c) {
583         if (type == null || ! reqnn("c", c).isAssignableFrom(type))
584            type = c;
585         return (T)innerBuild();
586      }
587
588      /**
589       * Specifies a cache to use for hashkey-based caching.
590       *
591       * <p>
592       * When a cache is specified, contexts with the same hash key will be reused from the cache
593       * instead of creating new instances.  This improves performance when building multiple contexts
594       * with identical configurations.
595       *
596       * <p>
597       * If <jk>null</jk> is specified, caching is disabled and each call to {@link #build()} will
598       * create a new context instance.
599       *
600       * @param value The cache.
601       *    <br>Can be <jk>null</jk> (disables caching, each build creates a new instance).
602       * @return This object.
603       */
604      public SELF cache(Cache<HashKey,? extends Context> value) {
605         cache = value;
606         return self();
607      }
608
609      /**
610       * Returns <jk>true</jk> if any of the annotations/appliers can be applied to this builder.
611       *
612       * @param work The work to check.
613       *    <br>Cannot be <jk>null</jk>.
614       * @return <jk>true</jk> if any of the annotations/appliers can be applied to this builder.
615       */
616      public boolean canApply(AnnotationWorkList work) {
617         return reqnn("work", work).stream().anyMatch(x -> builders.stream().anyMatch(x::canApply));
618      }
619
620      /**
621       * Copy creator.
622       *
623       * @return A new mutable copy of this builder.
624       */
625      public abstract SELF copy();
626
627      /**
628       * Null-safe copy: returns a deep copy of the specified value, or <jk>null</jk> if the value is <jk>null</jk>.
629       *
630       * @param value The value to copy.  Can be <jk>null</jk> (returns <jk>null</jk>).
631       * @return A copy of the value, or <jk>null</jk> if the value was <jk>null</jk>.
632       */
633      public static Builder<?> copyOrNull(Builder<?> value) {
634         return value == null ? null : value.copy();
635      }
636
637      /**
638       * <i><l>Context</l> configuration property:&emsp;</i>  Debug mode.
639       *
640       * <p>
641       * Enables the following additional information during serialization:
642       * <ul class='spaced-list'>
643       *    <li>
644       *       When bean getters throws exceptions, the exception includes the object stack information
645       *       in order to determine how that method was invoked.
646       *    <li>
647       *       Enables {@link MarshallingTraverseContext.Builder#detectRecursions()}.
648       * </ul>
649       *
650       * <p>
651       * Enables the following additional information during parsing:
652       * <ul class='spaced-list'>
653       *    <li>
654       *       When bean setters throws exceptions, the exception includes the object stack information
655       *       in order to determine how that method was invoked.
656       * </ul>
657       *
658       * <h4 class='section'>Example:</h4>
659       * <p class='bjava'>
660       *    <jc>// Create a serializer with debug enabled.</jc>
661       *    WriterSerializer <jv>serializer</jv> = JsonSerializer
662       *       .<jsm>create</jsm>()
663       *       .debug()
664       *       .build();
665       *
666       *    <jc>// Create a POJO model with a recursive loop.</jc>
667       *    <jk>public class</jk> MyBean {
668       *       <jk>public</jk> Object <jf>f</jf>;
669       *    }
670       *    MyBean <jv>bean</jv> = <jk>new</jk> MyBean();
671       *    <jv>bean</jv>.<jf>f</jf> = <jv>bean</jv>;
672       *
673       *    <jc>// Throws a SerializeException and not a StackOverflowError</jc>
674       *    String <jv>json</jv> = <jv>serializer</jv>.write(<jv>bean</jv>);
675       * </p>
676       *
677       * <h4 class='section'>See Also:</h4><ul>
678       *    <li class='ja'>{@link MarshalledConfig#debug()}
679       *    <li class='jm'>{@link ContextSession.Builder#debug(Boolean)}
680       * </ul>
681       *
682       * @return This object.
683       */
684      public SELF debug() {
685         return debug(true);
686      }
687
688      /**
689       * Same as {@link #debug()} but allows you to explicitly specify the value.
690       *
691       * @param value The value for this setting.
692       * @return This object.
693       */
694      public SELF debug(boolean value) {
695         debug = value;
696         return self();
697      }
698
699      /**
700       * Returns all the annotations that have been applied to this builder.
701       *
702       * @return All the annotations that have been applied to this builder.
703       */
704      public AnnotationWorkList getApplied() { return applied; }
705
706      /**
707       * Returns the context class that this builder should create.
708       *
709       * @return The context class if it was specified.
710       */
711      public Optional<Class<?>> getType() { return o(type); }
712
713      /**
714       * Returns the hashkey of this builder.
715       *
716       * <p>
717       * Used to return previously instantiated context beans that have matching hashkeys.
718       * The {@link HashKey} object is suitable for use as a hashmap key of a map of context beans.
719       * A context bean is considered equivalent if the {@link HashKey#equals(Object)} method is the same.
720       *
721       * @return The hashkey of this builder.
722       */
723      public HashKey hashKey() {
724         return HashKey.of(debug, type, annotations);
725      }
726
727      /**
728       * Specifies a pre-instantiated bean for the {@link #build()} method to return.
729       *
730       * <p>
731       * If a non-null value is provided and it's an instance of the context type, {@link #build()} will return
732       * that instance instead of creating a new one.  If <jk>null</jk>, the normal build process continues.
733       *
734       * @param value The value for this setting.
735       *    <br>Can be <jk>null</jk> (normal build process will continue).
736       * @return This object.
737       */
738      public SELF impl(Context value) {
739         impl = value;
740         return self();
741      }
742
743      /**
744       * Returns <jk>true</jk> if debug is enabled.
745       *
746       * @return <jk>true</jk> if debug is enabled.
747       */
748      public boolean isDebug() { return debug; }
749
750      /**
751       * Associates a context class with this builder.
752       *
753       * <p>
754       * This is the type of object that this builder creates when the {@link #build()} method is called.
755       *
756       * <p>
757       * By default, it's the outer class of where the builder class is defined.
758       *
759       * <p>
760       * If <jk>null</jk> is set, {@link #build()} will throw an exception.  The default constructor automatically
761       * sets this to the outer class, so <jk>null</jk> should only be set explicitly if you want to override the default.
762       *
763       * @param value The context class that this builder should create.
764       *    <br>Can be <jk>null</jk> (will cause {@link #build()} to throw an exception).
765       * @return This object.
766       */
767      public SELF type(Class<? extends Context> value) {
768         type = value;
769         return self();
770      }
771
772      /**
773       * Registers the specified secondary builders with this context builder.
774       *
775       * <p>
776       * When {@link #apply(AnnotationWorkList)} is called, it gets called on all registered builders.
777       *
778       * @param values The builders to add to the list of builders.
779       *    <br>Cannot contain <jk>null</jk> values.
780       */
781      protected void registerBuilders(Object...values) {
782         reqnns("values", values);
783         for (var b : values) {
784            if (b == this)
785               builders.add(b);
786            else if (b instanceof Builder b2)
787               builders.addAll(b2.builders);
788            else
789               builders.add(b);
790         }
791      }
792
793      private ConstructorInfo getContextConstructor() {
794         return CONTEXT_CONSTRUCTORS.get(type, getClass());
795      }
796
797      private Context innerBuild() {
798         if (type == null)
799            throw rex("Type not specified for context builder %s", cn(getClass()));
800         if (nn(impl) && type.isInstance(impl))
801            return type.cast(impl);
802         if (nn(cache))
803            return cache.get(hashKey(), () -> getContextConstructor().newInstance(this));
804         return getContextConstructor().newInstance(this);
805      }
806   }
807
808   /**
809    * Cache of static <c>create</c> methods that return builder instances for context classes.
810    *
811    * <p>
812    * This cache stores {@link MethodInfo} objects for public static methods named <c>create</c> that return
813    * builder objects. The methods are discovered by:
814    * <ol>
815    *    <li>Finding public constructors that take a single parameter (the builder type)
816    *    <li>Looking for no-arg static <c>create</c> methods whose return type is assignable to one of those builder types
817    *    <li>Choosing the one declared closest to the context class (so a subclass's own <c>create</c> wins over an
818    *       inherited parent <c>create</c>)
819    *    <li>Caching the result for future lookups
820    * </ol>
821    *
822    * <p>
823    * Used by {@link #createBuilder(Class)} to efficiently locate and invoke builder creation methods.
824    *
825    * @see #createBuilder(Class)
826    */
827   private static final Cache<Class<?>,MethodInfo> BUILDER_CREATE_METHODS = Cache.<Class<?>,MethodInfo>create()
828      .supplier(type -> {
829         var c = info(type);
830         // @formatter:off
831         var builderTypes = c.getPublicConstructors().stream()
832            .filter(ci -> ci.hasNumParameters(1) && ! ci.getParameter(0).getParameterType().is(type))
833            .map(ci -> ci.getParameter(0).getParameterType())
834            .toList();
835         // A subclass's constructor can take a parent builder type (for example Json5Parser(JsonParser.Builder)
836         // or HtmlSchemaDocSerializer(HtmlDocSerializer.Builder)), so both the subclass's own create() (whose
837         // builder is assignable to that type) and the inherited parent create() match.  Prefer the create()
838         // declared closest to the type itself so the subclass's own builder defaults win.
839         return c.getPublicMethods().stream()
840            .filter(x -> x.isStatic()
841               && x.isNotDeprecated()
842               && x.hasName("create")
843               && x.hasNumParameters(0)
844               && builderTypes.stream().anyMatch(bt -> x.getReturnType().isAssignableTo(bt)))
845            .reduce((a, b) -> b.getDeclaringClass().isChildOf(a.getDeclaringClass()) ? b : a)
846            .orElseThrow(() -> rex("Could not find builder create method on class %s", cn(type)));
847         // @formatter:on
848      })
849      .build();
850
851
852   /**
853    * Cache of public constructors on context classes that accept builder instances.
854    *
855    * <p>
856    * This cache stores {@link ConstructorInfo} objects for public constructors on context classes that take
857    * a single parameter of the builder type. The constructor is discovered by:
858    * <ol>
859    *    <li>Finding public constructors on the context type that take exactly one parameter
860    *    <li>Matching constructors where the parameter type is a parent of (or equal to) the builder type
861    *    <li>Caching the result for future lookups
862    * </ol>
863    *
864    * <p>
865    * Used by {@link Builder#getContextConstructor()} to efficiently locate and invoke context constructors
866    * when building context instances from builders.
867    *
868    * @see Builder#getContextConstructor()
869    * @see Builder#innerBuild()
870    */
871   private static final Cache2<Class<? extends Context>,Class<? extends Builder>,ConstructorInfo> CONTEXT_CONSTRUCTORS = Cache2.<Class<? extends Context>,Class<? extends Builder>,ConstructorInfo>create()
872      .supplier((cacheType, builderType) -> {
873         var ct = info(cacheType);
874         var bt = info(builderType);
875         return ct
876            .getPublicConstructor(x -> x.hasNumParameters(1) && x.getParameter(0).getParameterType().isAssignableFrom(builderType))
877            .orElseThrow(() -> rex("Public constructor not found: %s(%s)", ct.getName(), bt.getName()));
878      })
879      .build();
880
881   /**
882    * Default annotation provider instance for finding annotations on classes, methods, fields, and constructors.
883    *
884    * <p>
885    * This is a static reference to {@link AnnotationProvider#INSTANCE}, used by the {@link Builder#traverse(AnnotationWorkList, Object)}
886    * method to discover annotations that can be applied to context builders.
887    *
888    * <p>
889    * The annotation provider supports:
890    * <ul>
891    *    <li>Finding annotations on classes, methods, fields, and constructors
892    *    <li>Traversing class hierarchies (parent-to-child or child-to-parent order)
893    *    <li>Supporting runtime annotations (annotations added programmatically)
894    *    <li>Caching results for performance
895    * </ul>
896    *
897    * @see AnnotationProvider
898    * @see Builder#traverse(AnnotationWorkList, Object)
899    */
900   private static final AnnotationProvider AP = AnnotationProvider.INSTANCE;
901
902   /**
903    * Predicate for annotations that themselves are annotated with {@link ContextApply}.
904    *
905    * <p>
906    * Also matches {@link BeanConfig} from {@code juneau-commons}, which intentionally lacks a
907    * {@link ContextApply @ContextApply} meta-annotation because {@code juneau-commons} cannot reference
908    * marshall-layer types. {@link AnnotationWorkList} routes {@link BeanConfig} to the
909    * {@link BeanConfigAnnotation} applier via an explicit special case.
910    */
911   public static final Predicate<AnnotationInfo<?>> CONTEXT_APPLY_FILTER = x -> x.hasAnnotation(ContextApply.class) || x.annotationType() == BeanConfig.class;
912
913   /**
914    * Instantiates a builder of the specified context class.
915    *
916    * <p>
917    * Looks for a public static method called <c>create</c> that returns an object that can be passed into a public
918    * or protected constructor of the class.
919    *
920    * @param type The builder to create.
921    *    <br>Cannot be <jk>null</jk>.
922    * @return A new builder.
923    */
924   public static Builder createBuilder(Class<? extends Context> type) {
925      reqnn("type", type);
926      try {
927         return ((Builder)BUILDER_CREATE_METHODS.get(type).invoke(null)).type(type);
928      } catch (ExecutableException e) {
929         throw toRex(e);
930      }
931   }
932
933
934   private final AnnotationProvider annotationProvider;
935   private final boolean debug;
936   private final List<Annotation> annotations;
937
938   /**
939    * Constructor for this class.
940    *
941    * @param builder The builder for this class.
942    *    <br>Cannot be <jk>null</jk>.
943    */
944   protected Context(Builder builder) {
945      reqnn("builder", builder);
946      init(builder);
947      annotations = cp(builder.annotations);
948      annotationProvider = AnnotationProvider.create().addRuntimeAnnotations(annotations).build();
949      debug = builder.debug;
950   }
951
952   /**
953    * Copy constructor.
954    *
955    * @param copyFrom The context to copy from.
956    *    <br>Cannot be <jk>null</jk>.
957    */
958   protected Context(Context copyFrom) {
959      reqnn("copyFrom", copyFrom);
960      annotationProvider = copyFrom.annotationProvider;
961      annotations = cp(copyFrom.annotations);
962      debug = copyFrom.debug;
963   }
964
965   /**
966    * Creates a builder from this context object.
967    *
968    * <p>
969    * Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.
970    *
971    * @return A new Builder object.
972    */
973   public Builder copy() {
974      throw uoex();
975   }
976
977   /**
978    * Create a session builder based on the properties defined on this context.
979    *
980    * <p>
981    * Use this method for creating sessions where you want to override basic settings.
982    * Otherwise, use {@link #getSession()} directly.
983    *
984    * @return A new session builder.
985    */
986   public ContextSession.Builder createSession() {
987      throw uoex();
988   }
989
990   /**
991    * Returns the annotation provider for this context.
992    *
993    * @return The annotation provider for this context.
994    */
995   public AnnotationProvider getAnnotationProvider() { return annotationProvider; }
996
997   /**
998    * Returns a session to use for this context.
999    *
1000    * <p>
1001    * Note that subclasses may opt to return a reusable non-modifiable session.
1002    *
1003    * @return A new session object.
1004    */
1005   public ContextSession getSession() { return createSession().build(); }
1006
1007   /**
1008    * Debug mode.
1009    *
1010    * @see Context.Builder#debug()
1011    * @return
1012    *    <jk>true</jk> if debug mode is enabled.
1013    */
1014   public boolean isDebug() { return debug; }
1015
1016   @Override /* Overridden from Object */
1017   public String toString() {
1018      return r(properties());
1019   }
1020
1021   /**
1022    * Perform optional initialization on builder before it is used.
1023    *
1024    * <p>
1025    * Default behavior is a no-op.
1026    *
1027    * @param builder The builder to initialize.
1028    */
1029   protected void init(Builder builder) {}
1030
1031   /**
1032    * Returns the properties on this bean as a map for debugging.
1033    *
1034    * @return The properties on this bean as a map for debugging.
1035    */
1036   protected FluentMap<String,Object> properties() {
1037      return filteredBeanPropertyMap()
1038         .a("annotations", annotations)
1039         .a("debug", debug);
1040   }
1041}