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.html;
018
019import static org.apache.juneau.commons.utils.CollectionUtils.*;
020import static org.apache.juneau.commons.utils.IoUtils.*;
021import static org.apache.juneau.commons.utils.ObjectUtils.*;
022import static org.apache.juneau.commons.utils.Shorts.*;
023import static org.apache.juneau.commons.utils.StringUtils.*;
024import static org.apache.juneau.commons.utils.ThrowableUtils.*;
025import static org.apache.juneau.marshall.xml.XmlSerializerSession.ContentResult.*;
026
027import java.io.*;
028import java.time.*;
029import java.time.temporal.*;
030import java.util.*;
031import java.util.function.*;
032import java.util.regex.*;
033
034import org.apache.juneau.commons.bean.*;
035import org.apache.juneau.commons.lang.*;
036import org.apache.juneau.marshall.*;
037import org.apache.juneau.marshall.serializer.*;
038import org.apache.juneau.marshall.swap.spi.*;
039import org.apache.juneau.marshall.xml.*;
040
041/**
042 * Session object that lives for the duration of a single use of {@link HtmlSerializer}.
043 *
044 * <h2 class='section'>Notes:</h2><ul>
045 *    <li class='warn'>This class is not thread safe and is typically discarded after one use.
046 * </ul>
047 *
048 * <h2 class='section'>See Also:</h2><ul>
049 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/HtmlSupport">HTML</a>
050
051 * </ul>
052 */
053@SuppressWarnings({
054   "java:S110", // Inheritance depth acceptable for this class hierarchy
055   "java:S115", // Constants use UPPER_snakeCase naming convention
056   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
057   "java:S1452", // Builder<?> create(), doSerialize()/getHtmlWriter() returning XmlWriter<?>/HtmlWriter<?>, and getRender() returning HtmlRender<?> intentionally expose wildcard types.
058   "java:S3776", // Branching is inherent to writeAnything(), writeCollection() and getTableHeaders(), which decide table/list/bean/map layout per type.
059   "java:S6541", // Brain method acceptable for writeAnything; refactoring would reduce clarity
060   "rawtypes", // Raw types necessary for generic type handling throughout HTML serializer session
061   "resource", // Resource management handled externally
062   "unchecked" // Type erasure requires unchecked casts throughout HTML serializer session
063})
064public class HtmlSerializerSession extends XmlSerializerSession {
065
066   /**
067    * Builder class.
068    */
069   @SuppressWarnings({
070      "java:S119" // 'SELF' (CRTP self-type) is intentional and clearer than a single-letter name.
071   })
072   public abstract static class Builder<SELF extends Builder<SELF>> extends XmlSerializerSession.Builder<SELF> {
073
074      private boolean addKeyValueTableHeaders;
075      private boolean detectLabelParameters;
076      private boolean detectLinksInStrings;
077      private String labelParameter;
078      private AnchorText uriAnchorText;
079      private final HtmlSerializer ctx;
080
081      /**
082       * Constructor
083       *
084       * @param ctx The context creating this session.
085       *    <br>Cannot be <jk>null</jk>.
086       */
087      protected Builder(HtmlSerializer ctx) {
088         super(reqnn("ctx", ctx));
089         this.ctx = ctx;
090         addKeyValueTableHeaders = ctx.isAddKeyValueTableHeaders();
091         detectLabelParameters = ctx.isDetectLabelParameters();
092         detectLinksInStrings = ctx.isDetectLinksInStrings();
093         labelParameter = ctx.getLabelParameter();
094         uriAnchorText = ctx.getUriAnchorText();
095      }
096
097      @Override
098      public HtmlSerializerSession build() {
099         return new HtmlSerializerSession(this);
100      }
101
102      /**
103       * Add key/value headers on bean/map tables.
104       *
105       * @param value The new value for this setting.
106       * @return This object.
107       */
108      public SELF addKeyValueTableHeaders(boolean value) {
109         addKeyValueTableHeaders = value;
110         return self();
111      }
112
113      /**
114       * Look for link labels in URIs.
115       *
116       * @param value The new value for this setting.
117       * @return This object.
118       */
119      public SELF detectLabelParameters(boolean value) {
120         detectLabelParameters = value;
121         return self();
122      }
123
124      /**
125       * Look for URLs in Strings.
126       *
127       * @param value The new value for this setting.
128       * @return This object.
129       */
130      public SELF detectLinksInStrings(boolean value) {
131         detectLinksInStrings = value;
132         return self();
133      }
134
135      /**
136       * The label parameter name.
137       *
138       * @param value The new value for this setting.
139       * @return This object.
140       */
141      public SELF labelParameter(String value) {
142         labelParameter = value;
143         return self();
144      }
145
146      /**
147       * The anchor text to use for URL objects.
148       *
149       * @param value The new value for this setting.
150       * @return This object.
151       */
152      public SELF uriAnchorText(AnchorText value) {
153         uriAnchorText = value;
154         return self();
155      }
156
157      @Override /* Overridden from Builder */
158      public SELF property(String key, Object value) {
159         if (key == null) { super.property(key, value); return self(); }
160         switch (key) {
161            case "addKeyValueTableHeaders", "HtmlSerializerSession.addKeyValueTableHeaders":
162               return addKeyValueTableHeaders(cvt(value, Boolean.class));
163            case "detectLabelParameters", "HtmlSerializerSession.detectLabelParameters":
164               return detectLabelParameters(cvt(value, Boolean.class));
165            case "detectLinksInStrings", "HtmlSerializerSession.detectLinksInStrings":
166               return detectLinksInStrings(cvt(value, Boolean.class));
167            case "labelParameter", "HtmlSerializerSession.labelParameter":
168               return labelParameter(cvt(value, String.class));
169            case "uriAnchorText", "HtmlSerializerSession.uriAnchorText":
170               return uriAnchorText(cvt(value, AnchorText.class));
171            default:
172               super.property(key, value);
173               return self();
174         }
175      }
176
177   }
178
179   /**
180    * Concrete default builder leaf for the non-subclassed {@code create()} path (CRTP terminal).
181    */
182   public static final class DefaultBuilder extends Builder<DefaultBuilder> {
183
184      DefaultBuilder(HtmlSerializer ctx) {
185         super(ctx);
186      }
187   }
188
189   /**
190    * Creates a new builder for this object.
191    *
192    * @param ctx The context creating this session.
193    *    <br>Cannot be <jk>null</jk>.
194    * @return A new builder.
195    */
196   public static Builder<?> create(HtmlSerializer ctx) {
197      return new DefaultBuilder(reqnn("ctx", ctx));
198   }
199
200   private final HtmlSerializer ctx;
201   private final boolean addKeyValueTableHeaders;
202   private final boolean detectLabelParameters;
203   private final boolean detectLinksInStrings;
204   private final String labelParameter;
205   private final AnchorText uriAnchorText;
206   private final Pattern labelPattern;
207
208   /**
209    * Constructor.
210    *
211    * @param builder The builder for this object.
212    */
213   protected HtmlSerializerSession(Builder<?> builder) {
214      super(builder);
215      ctx = builder.ctx;
216      addKeyValueTableHeaders = builder.addKeyValueTableHeaders;
217      detectLabelParameters = builder.detectLabelParameters;
218      detectLinksInStrings = builder.detectLinksInStrings;
219      labelParameter = builder.labelParameter;
220      uriAnchorText = builder.uriAnchorText;
221      labelPattern = Pattern.compile("[\\?\\&]" + Pattern.quote(labelParameter) + "=([^\\&]*)");
222   }
223
224   /**
225    * Returns the anchor text to use for the specified URL object.
226    *
227    * @param pMeta
228    *    The property metadata of the bean property of the object.
229    *    Can be <jk>null</jk> if the object isn't from a bean property; the {@code PROPERTY_NAME} anchor-text mode
230    *    then falls back to the URL string itself.
231    * @param o The URL object.
232    * @return The anchor text to use for the specified URL object.
233    */
234   public String getAnchorText(BeanPropertyMeta pMeta, Object o) {
235      var s = o.toString();
236      if (isDetectLabelParameters()) {
237         Matcher m = labelPattern.matcher(s);
238         if (m.find())
239            return urlDecode(m.group(1));
240      }
241      return switch (getUriAnchorText()) {
242         case LAST_TOKEN -> {
243            s = resolveUri(s);
244            if (s.indexOf('/') != -1)
245               s = s.substring(s.lastIndexOf('/') + 1);
246            if (s.indexOf('?') != -1)
247               s = s.substring(0, s.indexOf('?'));
248            if (s.indexOf('#') != -1)
249               s = s.substring(0, s.indexOf('#'));
250            if (s.isEmpty())
251               s = "/";
252            yield urlDecode(s);
253         }
254         case URI_ANCHOR -> {
255            if (s.indexOf('#') != -1)
256               s = s.substring(s.lastIndexOf('#') + 1);
257            yield urlDecode(s);
258         }
259         case PROPERTY_NAME -> pMeta == null ? s : pMeta.getName();
260         case URI -> resolveUri(s);
261         case CONTEXT_RELATIVE -> relativizeUri("context:/", s);
262         case SERVLET_RELATIVE -> relativizeUri("servlet:/", s);
263         case PATH_RELATIVE -> relativizeUri("request:/", s);
264         default /* TO_STRING */ -> s;
265      };
266   }
267
268   @Override /* Overridden from XmlSerializer */
269   public boolean isHtmlMode() { return true; }
270
271   /**
272    * Returns <jk>true</jk> if the specified object is a URL.
273    *
274    * @param cm The ClassMeta of the object being serialized.
275    * @param pMeta
276    *    The property metadata of the bean property of the object.
277    *    Can be <jk>null</jk> if the object isn't from a bean property; bean-property-level URI detection is then
278    *    skipped, relying solely on <c>cm</c>.
279    * @param o The object.
280    * @return <jk>true</jk> if the specified object is a URL.
281    */
282   public boolean isUri(ClassMeta<?> cm, BeanPropertyMeta pMeta, Object o) {
283      return (cm.isUri() || (nn(pMeta) && pMeta.isUri()))
284         || (isDetectLinksInStrings() && o instanceof CharSequence && isHttpUrl(o.toString()));
285   }
286
287   /**
288    * Returns <jk>true</jk> if the specified URI, after resolution, has an allowed scheme or is relative.
289    *
290    * @param uri The URI.  Can be <jk>null</jk>.
291    * @return <jk>true</jk> if the URI can be rendered as a link.
292    */
293   protected boolean isAllowedUri(Object uri) {
294      if (uri == null)
295         return true;
296      // Juneau's own URI-resolution schemes are same-origin; they resolve to real URLs (or stay relative) at write time.
297      var rawScheme = schemeOf(uri.toString());
298      if (rawScheme != null && RESOLVED_SCHEMES.contains(rawScheme))
299         return true;
300      var resolved = schemeOf(getUriResolver().resolve(uri));
301      return resolved == null || ctx.uriSchemes.contains(resolved);
302   }
303
304   private static final Set<String> RESOLVED_SCHEMES = Set.of("servlet", "context", "request");
305
306   // Returns the lower-cased scheme, or null if the URI is relative.
307   private static String schemeOf(String uri) {
308      // Browsers ignore tabs, CR/LF and leading control characters/spaces when parsing the scheme.
309      var s = uri.replaceAll("^[\\x00-\\x20]+", "").replaceAll("[\\t\\r\\n]", "");
310      for (var i = 0; i < s.length(); i++) {
311         var c = s.charAt(i);
312         if (c == '/' || c == '?' || c == '#')
313            return null;
314         if (c == ':')
315            return s.substring(0, i).toLowerCase(Locale.ROOT);
316      }
317      return null;
318   }
319
320   private String checkedLink(String link) {
321      return link != null && isAllowedUri(link) ? link : null;
322   }
323
324   // Programmatic equivalent of the full match https?\:\/\/.* (Pattern.matcher(s).matches()).
325   // The trailing .* does not cross a line terminator under matches(), so the remainder must contain none.
326   private static boolean isHttpUrl(String s) {
327      int start;
328      if (s.startsWith("http://"))
329         start = 7;
330      else if (s.startsWith("https://"))
331         start = 8;
332      else
333         return false;
334      for (var i = start; i < s.length(); i++) {
335         var c = s.charAt(i);
336         if (c == '\n' || c == '\r' || c == '\u0085' || c == '\u2028' || c == '\u2029')
337            return false;
338      }
339      return true;
340   }
341
342   /**
343    * Main serialization routine.
344    *
345    * @param o The object being serialized.
346    * @param w The writer to serialize to.
347    * @return The same writer passed in.
348    * @throws SerializeException If a problem occurred trying to send output to the writer.
349    */
350   private XmlWriter<?> doSerialize(Object o, XmlWriter<?> w) throws SerializeException {
351      writeAnything(w, o, getExpectedRootType(o), null, null, getInitialDepth() - 1, true, false);
352      return w;
353   }
354
355   private String getAnchorText(BeanPropertyMeta pMeta) {
356      return pMeta == null ? null : getHtmlBeanPropertyMeta(pMeta).getAnchorText();
357   }
358
359   private String getLink(BeanPropertyMeta pMeta) {
360      return pMeta == null ? null : getHtmlBeanPropertyMeta(pMeta).getLink();
361   }
362
363   private HtmlRender<?> getRender(HtmlSerializerSession session, BeanPropertyMeta pMeta, Object value) {
364      if (pMeta == null)
365         return null;
366      HtmlRender<?> render = getHtmlBeanPropertyMeta(pMeta).getRender();
367      if (nn(render))
368         return render;
369      var cMeta = session.getClassMetaForObject(value);
370      render = cMeta == null ? null : getHtmlClassMeta(cMeta).getRender();
371      return render;
372   }
373
374   
375   private String getStyle(HtmlSerializerSession session, BeanPropertyMeta pMeta, Object value) {
376      // Check for annotation style first
377      if (nn(pMeta)) {
378         String annotationStyle = getHtmlBeanPropertyMeta(pMeta).getStyle();
379         if (nn(annotationStyle))
380            return annotationStyle;
381      }
382      // Fall back to render
383      HtmlRender render = getRender(session, pMeta, value);
384      return render == null ? null : render.getStyle(session, value);
385   }
386
387   /**
388    * Returns the property names of a bean map that can be read, skipping write-only properties.
389    */
390   private static Object[] readableKeys(BeanMap<?> bm) {
391      return bm.keySet().stream().filter(k -> bm.getProperty(k).getMeta().canRead()).toArray(String[]::new);
392   }
393
394   /*
395    * Returns the table column headers for the specified collection of objects.
396    * Returns null if collection should not be serialized as a 2-dimensional table.
397    * Returns an empty array if it should be treated as a table but without headers.
398    * 2-dimensional tables are used for collections of objects that all have the same set of property names.
399    *
400    * Null vs empty array have distinct semantics here (don't use table vs table with no headers).
401    * Consider Optional or separate method to avoid null return.
402    */
403   @SuppressWarnings({
404      "java:S1168" // Null vs empty array have distinct semantics (don't use table vs table with no headers)
405   })
406   private Object[] getTableHeaders(Collection c, HtmlBeanPropertyMeta bpHtml) throws SerializeException {
407
408      if (c.isEmpty())
409         return null;
410
411      c = sort(c);
412
413      Object o1 = null;
414      for (var o : c)
415         if (nn(o)) {
416            o1 = o;
417            break;
418         }
419      if (o1 == null)
420         return null;
421
422      var cm1 = getClassMetaForObject(o1);
423
424      ObjectSwap swap = cm1.getSwap(this);
425      o1 = swap(swap, o1);
426      if (nn(swap))
427         cm1 = swap.getSwapClassMeta(this);
428
429      if (cm1 == null || ! cm1.isMapOrBean() || getAnnotationProvider().has(HtmlLink.class, cm1))
430         return null;
431
432      HtmlClassMeta cHtml = getHtmlClassMeta(cm1);
433
434      if (cHtml.isNoTables() || bpHtml.isNoTables() || cHtml.isXml() || bpHtml.isXml() || canIgnoreValue(cm1, null, o1))
435         return null;
436
437      if (cHtml.isNoTableHeaders() || bpHtml.isNoTableHeaders())
438         return new Object[0];
439
440      // If it's a non-bean map, only use table if all entries are also maps.
441      if (cm1.isMap() && ! cm1.isBeanMap()) {
442
443         Set<Object> set = set();
444         for (var o : c) {
445            o = swap(swap, o);
446            if (! canIgnoreValue(cm1, null, o)) {
447               if (! cm1.isInstance(o))
448                  return null;
449               forEachEntry((Map)o, x -> set.add(x.getKey()));
450            }
451         }
452         return set.toArray(new Object[set.size()]);
453      }
454
455      // Must be a bean or BeanMap.
456      for (var o : c) {
457         o = swap(swap, o);
458         if (! canIgnoreValue(cm1, null, o) && ! cm1.isInstance(o))
459            return null;
460      }
461
462      return readableKeys(toBeanMap(o1));
463   }
464
465   private void writeBeanMap(XmlWriter<?> out, BeanMap<?> m, ClassMeta<?> eType, BeanPropertyMeta ppMeta) throws SerializeException {
466
467      var mcm = (ClassMeta<?>) m.getBeanInfo();
468      HtmlClassMeta cHtml = getHtmlClassMeta(mcm);
469      HtmlBeanPropertyMeta bpHtml = getHtmlBeanPropertyMeta(ppMeta);
470
471      int i = indent;
472
473      out.oTag(i, "table");
474
475      String typeName = m.getMeta().getDictionaryName();
476      if (nn(typeName) && eType != mcm)
477         out.attr(getBeanTypePropertyName(mcm), typeName);
478
479      out.w('>').nl(i);
480      if (isAddKeyValueTableHeaders() && ! (cHtml.isNoTableHeaders() || bpHtml.isNoTableHeaders())) {
481         out.sTag(i + 1, "tr").nl(i + 1);
482         out.sTag(i + 2, "th").append("key").eTag("th").nl(i + 2);
483         out.sTag(i + 2, "th").append("value").eTag("th").nl(i + 2);
484         out.ie(i + 1).eTag("tr").nl(i + 1);
485      }
486
487      Predicate<Object> checkNull = x -> isKeepNullProperties() || nn(x);
488
489      m.forEachValue(checkNull, (pMeta, key, value, thrown) -> {
490         var cMeta = (ClassMeta<?>) pMeta.getBeanInfo();
491
492         if (nn(thrown))
493            onBeanGetterException(pMeta, thrown);
494
495         if (canIgnoreValue(pMeta, key, value))
496            return;
497
498         String link = null;
499         String anchorText = null;
500         if (! cMeta.isCollectionOrArray()) {
501            link = checkedLink(m.resolveVars(getLink(pMeta)));
502            anchorText = m.resolveVars(getAnchorText(pMeta));
503         }
504
505         if (nn(anchorText))
506            value = anchorText;
507
508         out.sTag(i + 1, "tr").nl(i + 1);
509         out.sTag(i + 2, "td").text(key).eTag("td").nl(i + 2);
510         out.oTag(i + 2, "td");
511         String style = getStyle(this, pMeta, value);
512         if (nn(style))
513            out.attr("style", style);
514         out.cTag();
515
516         try {
517            if (nn(link))
518               out.oTag(i + 3, "a").attrUri("href", link).cTag();
519            ContentResult cr = writeAnything(out, value, cMeta, key, pMeta, 2, false, true);
520            if (cr == CR_ELEMENTS)
521               out.i(i + 2);
522            if (nn(link))
523               out.eTag("a");
524         } catch (SerializeException e) {
525            throw e;
526         } catch (Exception e) {
527            onBeanGetterException(pMeta, e);
528         }
529         out.eTag("td").nl(i + 2);
530         out.ie(i + 1).eTag("tr").nl(i + 1);
531      });
532
533      out.ie(i).eTag("table").nl(i);
534   }
535
536   
537   private void writeCollection(XmlWriter<?> out, Object in, ClassMeta<?> sType, ClassMeta<?> eType, String name, BeanPropertyMeta ppMeta) throws SerializeException {
538
539      HtmlClassMeta cHtml = getHtmlClassMeta(sType);
540      HtmlBeanPropertyMeta bpHtml = getHtmlBeanPropertyMeta(ppMeta);
541
542      Collection c = (sType.isCollection() ? (Collection)in : toList(sType.inner(), in));
543
544      boolean isCdc = cHtml.isHtmlCdc() || bpHtml.isHtmlCdc();
545      boolean isSdc = cHtml.isHtmlSdc() || bpHtml.isHtmlSdc();
546      boolean isDc = isCdc || isSdc;
547
548      int i = indent;
549      if (c.isEmpty()) {
550         out.appendln(i, "<ul></ul>");
551         return;
552      }
553
554      String type2 = null;
555      if (sType != eType)
556         type2 = sType.getBeanDictionaryName();
557      if (type2 == null)
558         type2 = "array";
559
560      c = sort(c);
561
562      String btpn = getBeanTypePropertyName(eType);
563
564      // Look at the objects to see how we're going to handle them.  Check the first object to see how we're going to
565      // handle this.
566      // If it's a map or bean, then we'll create a table.
567      // Otherwise, we'll create a list.
568      Object[] th = getTableHeaders(c, bpHtml);
569
570      if (nn(th)) {
571
572         out.oTag(i, "table").attr(btpn, type2).w('>').nl(i + 1);
573         if (th.length > 0) {
574            out.sTag(i + 1, "tr").nl(i + 2);
575            for (var key : th) {
576               out.sTag(i + 2, "th");
577               out.text(convertToType(key, String.class));
578               out.eTag("th").nl(i + 2);
579            }
580            out.ie(i + 1).eTag("tr").nl(i + 1);
581         } else {
582            th = null;
583         }
584
585         for (var o : c) {
586            var cm = getClassMetaForObject(o);
587
588            if (nn(cm) && nn(cm.getSwap(this))) {
589               ObjectSwap swap = cm.getSwap(this);
590               o = swap(swap, o);
591               cm = swap.getSwapClassMeta(this);
592            }
593
594            out.oTag(i + 1, "tr");
595            String typeName = (cm == null ? null : cm.getBeanDictionaryName());
596            String typeProperty = getBeanTypePropertyName(cm);
597
598            if (nn(typeName) && eType.getElementType() != cm)
599               out.attr(typeProperty, typeName);
600            out.cTag().nl(i + 2);
601
602            if (cm == null) {
603               out.i(i + 2);
604               writeAnything(out, o, null, null, null, 1, false, false);
605               out.nl(0);
606
607            } else if (cm.isMap() && ! (cm.isBeanMap())) {
608               Map m2 = sort((Map)o);
609
610               if (th == null)
611                  th = m2.keySet().toArray(new Object[m2.size()]);
612
613               for (var k : th) {
614                  out.sTag(i + 2, "td");
615                  ContentResult cr = writeAnything(out, m2.get(k), eType.getElementType(), toString(k), null, 2, false, true);
616                  if (cr == CR_ELEMENTS)
617                     out.i(i + 2);
618                  out.eTag("td").nl(i + 2);
619               }
620            } else {
621               BeanMap m2 = toBeanMap(o);
622
623               if (th == null)
624                  th = readableKeys(m2);
625
626               for (var k : th) {
627                  BeanMapEntry p = m2.getProperty(toString(k));
628                  BeanPropertyMeta pMeta = p.getMeta();
629                  if (pMeta.canRead()) {
630                     Object value = p.getValue();
631
632                     String link = null;
633                     String anchorText = null;
634                     if (! pMeta.getBeanInfo().isCollectionOrArray()) {
635                        link = checkedLink(m2.resolveVars(getLink(pMeta)));
636                        anchorText = m2.resolveVars(getAnchorText(pMeta));
637                     }
638
639                     if (nn(anchorText))
640                        value = anchorText;
641
642                     String style = getStyle(this, pMeta, value);
643                     out.oTag(i + 2, "td");
644                     if (nn(style))
645                        out.attr("style", style);
646                     out.cTag();
647                     if (nn(link))
648                        out.oTag("a").attrUri("href", link).cTag();
649                     ContentResult cr = writeAnything(out, value, (ClassMeta<?>) pMeta.getBeanInfo(), p.getKey(), pMeta, 2, false, true);
650                     if (cr == CR_ELEMENTS)
651                        out.i(i + 2);
652                     if (nn(link))
653                        out.eTag("a");
654                     out.eTag("td").nl(i + 2);
655                  }
656               }
657            }
658            out.ie(i + 1).eTag("tr").nl(i + 1);
659         }
660         out.ie(i).eTag("table").nl(i);
661
662      } else {
663         out.oTag(i, isDc ? "p" : "ul");
664         if (! type2.equals("array"))
665            out.attr(btpn, type2);
666         out.w('>').nl(i + 1);
667         var isFirst = true;
668         for (var o : c) {
669            if (isDc && ! isFirst)
670               out.append(isCdc ? ", " : " ");
671            if (! isDc)
672               out.oTag(i + 1, "li");
673            String style = getStyle(this, ppMeta, o);
674            String link = checkedLink(getLink(ppMeta) == null ? null : getLink(ppMeta).replace("{#}", s(o)));
675            if (nn(style) && ! isDc)
676               out.attr("style", style);
677            if (! isDc)
678               out.cTag();
679            if (nn(link))
680               out.oTag(i + 2, "a").attrUri("href", link).cTag();
681            ContentResult cr = writeAnything(out, o, eType.getElementType(), name, null, 1, false, true);
682            if (nn(link))
683               out.eTag("a");
684            if (cr == CR_ELEMENTS)
685               out.ie(i + 1);
686            if (! isDc)
687               out.eTag("li").nl(i + 1);
688            isFirst = false;
689         }
690         out.ie(i).eTag(isDc ? "p" : "ul").nl(i);
691      }
692   }
693
694   
695   private void writeMap(XmlWriter<?> out, Map m, ClassMeta<?> sType, ClassMeta<?> eKeyType, ClassMeta<?> eValueType, String typeName, BeanPropertyMeta ppMeta) throws SerializeException {
696
697      var keyType = eKeyType == null ? string() : eKeyType;
698      var valueType = eValueType == null ? object() : eValueType;
699      var aType = getClassMetaForObject(m);       // The actual type
700      HtmlClassMeta cHtml = getHtmlClassMeta(aType);
701      HtmlBeanPropertyMeta bpHtml = getHtmlBeanPropertyMeta(ppMeta);
702
703      int i = indent;
704
705      out.oTag(i, "table");
706
707      if (nn(typeName) && nn(ppMeta) && ppMeta.getBeanInfo() != aType)
708         out.attr(getBeanTypePropertyName(sType), typeName);
709
710      out.append(">").nl(i + 1);
711      if (isAddKeyValueTableHeaders() && ! (cHtml.isNoTableHeaders() || bpHtml.isNoTableHeaders())) {
712         out.sTag(i + 1, "tr").nl(i + 2);
713         out.sTag(i + 2, "th").append("key").eTag("th").nl(i + 3);
714         out.sTag(i + 2, "th").append("value").eTag("th").nl(i + 3);
715         out.ie(i + 1).eTag("tr").nl(i + 2);
716      }
717
718      forEachEntry(m, x -> writeMapEntry(out, x, keyType, valueType, i, ppMeta));
719
720      out.ie(i).eTag("table").nl(i);
721   }
722
723   private void writeMapEntry(XmlWriter<?> out, Map.Entry e, ClassMeta<?> keyType, ClassMeta<?> valueType, int i, BeanPropertyMeta ppMeta) throws SerializeException {
724      Object key = generalize(e.getKey(), keyType);
725      Object value = null;
726      try {
727         value = e.getValue();
728      } catch (StackOverflowError t) {
729         throw t;
730      } catch (Exception t) {
731         onError(t, "Could not call getValue() on property '%s', %s", e.getKey(), localizedMessage(t));
732      }
733
734      String link = getLink(ppMeta);
735      link = link == null ? null : checkedLink(link.replace("{#}", s(value)));
736      String style = getStyle(this, ppMeta, value);
737
738      out.sTag(i + 1, "tr").nl(i + 2);
739      out.oTag(i + 2, "td");
740      if (nn(style))
741         out.attr("style", style);
742      out.cTag();
743      if (nn(link))
744         out.oTag(i + 3, "a").attrUri("href", link).cTag();
745      ContentResult cr = writeAnything(out, key, keyType, null, null, 2, false, false);
746      if (nn(link))
747         out.eTag("a");
748      if (cr == CR_ELEMENTS)
749         out.i(i + 2);
750      out.eTag("td").nl(i + 2);
751      out.sTag(i + 2, "td");
752      cr = writeAnything(out, value, valueType, (key == null ? "_x0000_" : toString(key)), null, 2, false, true);
753      if (cr == CR_ELEMENTS)
754         out.ie(i + 2);
755      out.eTag("td").nl(i + 2);
756      out.ie(i + 1).eTag("tr").nl(i + 1);
757
758   }
759
760   @Override /* Overridden from Serializer */
761   protected void doWrite(SerializerPipe out, Object o) throws IOException, SerializeException {
762      doSerialize(o, getHtmlWriter(out));
763   }
764
765   /**
766    * Returns the language-specific metadata on the specified bean property.
767    *
768    * @param bpm The bean property to return the metadata on.
769    * @return The metadata.
770    */
771   protected HtmlBeanPropertyMeta getHtmlBeanPropertyMeta(BeanPropertyMeta bpm) {
772      return ctx.getHtmlBeanPropertyMeta(bpm);
773   }
774
775   /**
776    * Returns the language-specific metadata on the specified class.
777    *
778    * @param cm The class to return the metadata on.
779    * @return The metadata.
780    */
781   protected HtmlClassMeta getHtmlClassMeta(ClassMeta<?> cm) {
782      return ctx.getHtmlClassMeta(cm);
783   }
784
785   /**
786    * Converts the specified output target object to an {@link HtmlWriter}.
787    *
788    * @param out The output target object.
789    *    <br>Must not be <jk>null</jk>.
790    * @return The output target object wrapped in an {@link HtmlWriter}.
791    */
792   protected final HtmlWriter<?> getHtmlWriter(SerializerPipe out) {
793      Object output = out.getRawOutput();
794      if (output instanceof HtmlWriter<?> output2)
795         return output2;
796      var w = new BasicHtmlWriter(out.getWriter(), isUseWhitespace(), getMaxIndent(), isTrimStrings(), getQuoteChar(), getUriResolver());
797      out.setWriter(w);
798      return w;
799   }
800
801   /**
802    * Link label parameter name.
803    *
804    * @see HtmlSerializer.Builder#labelParameter(String)
805    * @return
806    *    The parameter name to look for when resolving link labels.
807    */
808   protected final String getLabelParameter() { return labelParameter; }
809
810   /**
811    * Anchor text source.
812    *
813    * @see HtmlSerializer.Builder#uriAnchorText(AnchorText)
814    * @return
815    *    When creating anchor tags (e.g. <code><xt>&lt;a</xt> <xa>href</xa>=<xs>'...'</xs>
816    *    <xt>&gt;</xt>text<xt>&lt;/a&gt;</xt></code>) in HTML, this setting defines what to set the inner text to.
817    */
818   protected final AnchorText getUriAnchorText() { return uriAnchorText; }
819
820   @Override
821   public final boolean isAddBeanTypes() { return super.isAddBeanTypes(); }
822
823   /**
824    * Add key/value headers on bean/map tables.
825    *
826    * @see HtmlSerializer.Builder#addKeyValueTableHeaders()
827    * @return
828    *    <jk>true</jk> if <bc>key</bc> and <bc>value</bc> column headers are added to tables.
829    */
830   protected final boolean isAddKeyValueTableHeaders() { return addKeyValueTableHeaders; }
831
832   /**
833    * Look for link labels in URIs.
834    *
835    * @see HtmlSerializer.Builder#disableDetectLabelParameters()
836    * @return
837    *    <jk>true</jk> if we should ook for URL label parameters (e.g. <js>"?label=foobar"</js>).
838    */
839   protected final boolean isDetectLabelParameters() { return detectLabelParameters; }
840
841   /**
842    * Look for URLs in {@link String Strings}.
843    *
844    * @see HtmlSerializer.Builder#disableDetectLinksInStrings()
845    * @return
846    *    <jk>true</jk> if we should automatically convert strings to URLs if they look like a URL.
847    */
848   protected final boolean isDetectLinksInStrings() { return detectLinksInStrings; }
849
850   /**
851    * Serialize the specified object to the specified writer.
852    *
853    * @param out The writer.
854    * @param o The object to serialize.
855    * @param eType The expected type of the object if this is a bean property.
856    * @param name
857    *    The attribute name of this object if this object was a field in a JSON object (i.e. key of a
858    *    {@link Map.Entry} or property name of a bean).
859    * @param pMeta The bean property being serialized, or <jk>null</jk> if we're not serializing a bean property.
860    * @param xIndent The current indentation value.
861    * @param isRoot <jk>true</jk> if this is the root element of the document.
862    * @param nlIfElement <jk>true</jk> if we should add a newline to the output before serializing only if the object is an element and not text.
863    * @return The type of content encountered.  Either simple (no whitespace) or normal (elements with whitespace).
864    * @throws SerializeException Generic serialization error occurred.
865    */
866   
867   @SuppressWarnings({
868      "java:S107", // Method has many parameters; acceptable for builder/configuration methods
869      "null" // Null handling verified by context or framework
870   })
871   protected ContentResult writeAnything(XmlWriter<?> out, Object o, ClassMeta<?> eType, String name, BeanPropertyMeta pMeta, int xIndent, boolean isRoot, boolean nlIfElement)
872      throws SerializeException {
873
874      ClassMeta<?> aType = null;       // The actual type
875      ClassMeta<?> wType = null;     // The wrapped type (delegate)
876      ClassMeta<?> sType;   // The serialized type
877
878      var addJsonTags = isAddJsonTags();
879
880      if (eType == null)
881         eType = object();
882
883      aType = push2(name, o, eType);
884
885      // Handle recursion
886      if (aType == null) {
887         o = null;
888         aType = object();
889      }
890
891      // Handle Optional<X>
892      if (isOptional(aType)) {
893         o = getOptionalValue(o);
894         eType = getOptionalType(eType);
895         aType = getClassMetaForObject(o, object());
896      }
897
898      indent += xIndent;
899
900      ContentResult cr = CR_ELEMENTS;
901
902      // Determine the type.
903      if (o == null || (aType.isChar() && ((Character)o).charValue() == 0)) {
904         if (addJsonTags)
905            out.tag("null");
906         cr = ContentResult.CR_MIXED;
907
908      } else {
909
910         if (aType.isDelegate()) {
911            wType = aType;
912            aType = (ClassMeta)((Delegate)o).getBeanInfo();
913         }
914
915         sType = aType;
916
917         String typeName = null;
918         if (isAddBeanTypes() && ! eType.equals(aType))
919            typeName = aType.getBeanDictionaryName();
920
921         // Swap if necessary
922         ObjectSwap swap = aType.getSwap(this);
923         if (nn(swap)) {
924            o = swap(swap, o);
925            sType = swap.getSwapClassMeta(this);
926
927            // If the getSwapClass() method returns Object, we need to figure out
928            // the actual type now.
929            if (sType.isObject())
930               sType = getClassMetaForObject(o);
931         }
932
933         // Handle the case where we're serializing a raw stream or re-serializable raw content.
934         if (sType.isReader() || sType.isInputStream() || o instanceof RawContent) {
935            pop();
936            indent -= xIndent;
937            if (sType.isReader())
938               pipe((Reader)o, out, SerializerSession::handleThrown);
939            else if (sType.isInputStream())
940               pipe((InputStream)o, out, SerializerSession::handleThrown);
941            else
942               out.append(o.toString());
943            return ContentResult.CR_MIXED;
944         }
945
946         HtmlClassMeta cHtml = getHtmlClassMeta(sType);
947         HtmlBeanPropertyMeta bpHtml = getHtmlBeanPropertyMeta(pMeta);
948
949         HtmlRender render = coalesce(bpHtml.getRender(), cHtml.getRender());
950
951         if (nn(render)) {
952            Object o2 = render.getContent(this, o);
953            if (o2 != o) {
954               indent -= xIndent;
955               pop();
956               out.nl(indent);
957               return writeAnything(out, o2, null, typeName, null, xIndent, false, false);
958            }
959         }
960
961         if (cHtml.isXml() || bpHtml.isXml()) {
962            pop();
963            indent++;
964            if (nlIfElement)
965               out.nl(0);
966            super.writeAnything(out, o, null, null, null, null, false, XmlFormat.MIXED, false, false, null);
967            indent -= xIndent + 1;
968            return cr;
969
970         } else if (cHtml.isPlainText() || bpHtml.isPlainText()) {
971            out.w(o == null ? "null" : o.toString());
972            cr = CR_MIXED;
973
974         } else if (o == null || (sType.isChar() && ((Character)o).charValue() == 0)) {
975            if (addJsonTags)
976               out.tag("null");
977            cr = CR_MIXED;
978
979         } else if (sType.isBean()) {
980            BeanMap m = toBeanMap(o);
981            if (getAnnotationProvider().has(HtmlLink.class, aType)) {
982               var uriProperty = Holder.<String>empty();
983               var nameProperty = Holder.<String>empty();
984               aType.forEachAnnotation(HtmlLink.class, x -> ine(x.uriProperty()), x -> uriProperty.set(x.uriProperty()));
985               aType.forEachAnnotation(HtmlLink.class, x -> ine(x.nameProperty()), x -> nameProperty.set(x.nameProperty()));
986               Object urlProp = m.get(uriProperty.orElse(""));
987               Object nameProp = m.get(nameProperty.orElse(""));
988
989               if (isAllowedUri(urlProp))
990                  out.oTag("a").attrUri("href", urlProp).w('>').text(nameProp).eTag("a");
991               else
992                  out.text(nameProp);
993               cr = CR_MIXED;
994            } else {
995               out.nlIf(! isRoot, xIndent + 2);
996               writeBeanMap(out, m, eType, pMeta);
997            }
998
999         } else if (sType.isMap() || (nn(wType) && wType.isMap())) {
1000            out.nlIf(! isRoot, xIndent + 1);
1001            if (o instanceof BeanMap o2)
1002               writeBeanMap(out, o2, eType, pMeta);
1003            else
1004               writeMap(out, (Map)o, sType, eType.getKeyType(), eType.getValueType(), typeName, pMeta);
1005
1006         } else if (sType.isCollection() || sType.isArray() || (nn(wType) && wType.isCollection())) {
1007            out.nlIf(! isRoot, xIndent + 1);
1008            writeCollection(out, o, sType, eType, name, pMeta);
1009
1010         } else if (sType.isStreamable()) {
1011            // HTML must inspect elements to decide table vs. list layout (getTableHeaders), so materialization is unavoidable.
1012            out.nlIf(! isRoot, xIndent + 1);
1013            var list = toListFromStreamable(o, sType);
1014            writeCollection(out, list, getClassMeta(List.class), eType, name, pMeta);
1015
1016         } else if (sType.isNumber()) {
1017            if (eType.isNumber() && ! (isRoot && addJsonTags))
1018               out.append(o);
1019            else
1020               out.sTag("number").append(o).eTag("number");
1021            cr = CR_MIXED;
1022
1023         } else if (sType.isBoolean()) {
1024            if (eType.isBoolean() && ! (isRoot && addJsonTags))
1025               out.append(o);
1026            else
1027               out.sTag("boolean").append(o).eTag("boolean");
1028            cr = CR_MIXED;
1029
1030         } else if (isUri(sType, pMeta, o)) {
1031            String label = getAnchorText(pMeta, o);
1032            if (isAllowedUri(o)) {
1033               out.oTag("a").attrUri("href", o).w('>');
1034               out.text(label);
1035               out.eTag("a");
1036            } else {
1037               out.text(label);
1038            }
1039            cr = CR_MIXED;
1040
1041         } else if (sType.isDate()) {
1042            String s = writeDate((Date)o, sType);
1043            if (isRoot && addJsonTags)
1044               out.sTag("string").text(s).eTag("string");
1045            else
1046               out.text(s);
1047            cr = CR_MIXED;
1048
1049         } else if (sType.isCalendar()) {
1050            String s = writeCalendar(o, sType);
1051            if (isRoot && addJsonTags)
1052               out.sTag("string").text(s).eTag("string");
1053            else
1054               out.text(s);
1055            cr = CR_MIXED;
1056
1057         } else if (sType.isTemporal()) {
1058            String s = writeTemporal((TemporalAccessor)o, sType);
1059            if (isRoot && addJsonTags)
1060               out.sTag("string").text(s).eTag("string");
1061            else
1062               out.text(s);
1063            cr = CR_MIXED;
1064
1065         } else if (sType.isDuration()) {
1066            String s = writeDuration((Duration)o);
1067            if (isRoot && addJsonTags)
1068               out.sTag("string").text(s).eTag("string");
1069            else
1070               out.text(s);
1071            cr = CR_MIXED;
1072
1073         } else if (sType.isPeriod()) {
1074            String s = writePeriod((Period)o);
1075            if (isRoot && addJsonTags)
1076               out.sTag("string").text(s).eTag("string");
1077            else
1078               out.text(s);
1079            cr = CR_MIXED;
1080
1081         } else {
1082            if (isRoot && addJsonTags)
1083               out.sTag("string").text(toString(o)).eTag("string");
1084            else
1085               out.text(toString(o));
1086            cr = CR_MIXED;
1087         }
1088      }
1089      pop();
1090      indent -= xIndent;
1091      return cr;
1092   }
1093
1094   @Override /* Overridden from XmlSerializerSession */
1095   protected ContentResult writeAnything(XmlWriter<?> out, Object o, ClassMeta<?> eType, String keyName, String elementName, Namespace elementNamespace, boolean addNamespaceUris, XmlFormat format,
1096      boolean isMixed, boolean preserveWhitespace, BeanPropertyMeta pMeta) throws SerializeException {
1097
1098      // If this is a bean, then we want to serialize it as HTML unless it's @Html(format=XML).
1099      var type = push2(elementName, o, eType);
1100      pop();
1101
1102      if (type == null)
1103         type = object();
1104      else if (type.isDelegate())
1105         type = (ClassMeta)((Delegate)o).getBeanInfo();
1106      ObjectSwap swap = type.getSwap(this);
1107      if (nn(swap)) {
1108         o = swap(swap, o);
1109         type = swap.getSwapClassMeta(this);
1110         if (type.isObject())
1111            type = getClassMetaForObject(o);
1112      }
1113
1114      HtmlClassMeta cHtml = getHtmlClassMeta(type);
1115
1116      if (type.isMapOrBean() && ! cHtml.isXml())
1117         return writeAnything(out, o, eType, elementName, pMeta, 0, false, false);
1118
1119      return super.writeAnything(out, o, eType, keyName, elementName, elementNamespace, addNamespaceUris, format, isMixed, preserveWhitespace, pMeta);
1120   }
1121}