-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDOM.java
More file actions
2006 lines (1941 loc) · 64.7 KB
/
DOM.java
File metadata and controls
2006 lines (1941 loc) · 64.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.labkey.api.util;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import jakarta.servlet.jsp.PageContext;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.labkey.api.action.LabKeyError;
import org.labkey.api.action.SpringActionController;
import org.labkey.api.jsp.taglib.ErrorsTag;
import org.labkey.api.view.HttpView;
import org.labkey.api.view.ViewContext;
import org.springframework.context.NoSuchMessageException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static org.labkey.api.util.DOM.Element.script;
import static org.labkey.api.util.HtmlString.unsafe;
import static org.labkey.api.util.PageFlowUtil.filter;
/// A Java DSL for safely building properly encoded HTML. All text content is automatically
/// HTML-encoded via [PageFlowUtil#filter], preventing XSS vulnerabilities. Uppercase static
/// factory methods (`DIV()`, `TABLE()`, `SPAN()`, etc.) return [Renderable] objects that nest
/// to compose an HTML tree.
///
/// ## Recommended imports
///
/// ```java
/// import static org.labkey.api.util.DOM.*;
/// import static org.labkey.api.util.DOM.Attribute.*;
/// ```
///
/// ## Elements, attributes, and classes
///
/// Elements accept an optional [Attributes] argument followed by var-arg children.
/// Use [#at(Attribute, Object, Object...)] for attributes, [#cl(String...)] for CSS classes,
/// and chain them together via the [_Attributes] builder:
///
/// ```java
/// DIV(cl("container"),
/// H1(id("title"), "Hello World"),
/// A(at(href, "https://example.com").cl("nav-link").data("section", "main"), "Click here"),
/// P(at(style, "color:red"), "Styled text"),
/// TR(cl(isOdd, "labkey-alternate-row", "labkey-row"), TD("cell"))
/// )
/// ```
///
/// ## Dynamic content
///
/// Children can be arrays, [Iterable]s, or [Stream]s of supported types:
///
/// ```java
/// // Stream of options in a select
/// SELECT(id("users"), Stream.of("alice", "bob", "charles").map(DOM::OPTION))
///
/// // Building rows in a loop
/// List<Renderable> rows = new ArrayList<>();
/// for (var item : items)
/// rows.add(TR(TD(item.getName()), TD(String.valueOf(item.getCount()))));
/// TABLE(cl("labkey-data-region"), THEAD(TR(TH("Name"), TH("Count"))), TBODY(rows))
/// ```
///
/// ## LabKey extensions ([LK])
///
/// ```java
/// LK.FORM(at(method, "POST", action, url), INPUT(at(type, "text", name, "q")), INPUT(at(type, "submit")))
/// LK.CHECKBOX(at(name, "enabled")) // checkbox + hidden field marker
/// LK.FA("plus-square") // font-awesome icon
/// LK.ERRORS(bindingResult) // render Spring validation errors
/// ```
///
/// ## Rendering to output
///
/// ```java
/// HtmlString html = DOM.createHtmlFragment(DIV("hello"), BR(), DIV("world")); // to HtmlString
/// myRenderable.appendTo(out); // to Appendable (JspWriter, StringBuilder)
/// String raw = DIV("test").renderToString(); // to String
/// ```
///
/// ## Template support
///
/// Use [#renderTemplate(Renderable, Appendable)] with [#BODY_PLACE_HOLDER] to split rendering
/// around a body that is not yet available (e.g. for JSP `BodyTagSupport` or `WebPartFrame`):
///
/// ```java
/// Renderable frame = DIV(cl("frame"), DIV(cl("header"), "Title"), BODY_PLACE_HOLDER, DIV(cl("footer"), "Footer"));
/// HtmlString endMarkup = DOM.renderTemplate(frame, out);
/// // ... render body content to out ...
/// out.write(endMarkup.toString());
/// ```
///
/// Supported child types: `null` (ignored), [CharSequence] (HTML-encoded), [Number]/[Boolean]
/// (rendered as-is), [Renderable], [HtmlString] (no encoding), arrays, [Iterable]s, and [Stream]s
/// of these types. See [#appendBody(Appendable, Object)] for details and [DomTestCase] for more examples.
public class DOM
{
public interface Attributes extends Iterable<Map.Entry<Object,Object>> {}
public static Attributes NOAT = null;
public interface ClassNames {} // just a marker interface for better typing since this is used as .toString() at runtime
public interface Renderable
{
Appendable appendTo(Appendable sb);
default String renderToString()
{
return appendTo(new StringBuilder()).toString();
}
}
/*
* BODY_PLACE_HOLDER and TemplateAppendableWrapper are used to make it possible to efficiently implement an HTML wrapper
* frame using DOM, even if the 'body' of the frame is not available yet. For instance, this can be used to implement
* Jsp tags that extend BodyTagSupport. It can also be used to implement subclasses of WebPartFrame.
*
* The DOM Renderable objects write to the normal output Appendable until it hits BODY_PLACE_HOLDER. At that point the
* output is captured in a StringBuilder. The caller can stash the markup generated after BODY_PLACE_HOLDER and
* render that markup after the body is rendered.
*/
private static final String BODY_PLACE_HOLDER_STRING = "<!-- org.labkey.api.util.DOM.BODYCONTENT!" + GUID.makeHash() + "-->";
public static final Renderable BODY_PLACE_HOLDER = sb -> {
try
{
if (sb instanceof TemplateAppendableWrapper)
((TemplateAppendableWrapper)sb).bufferRemainingOutput();
else
sb.append(BODY_PLACE_HOLDER_STRING);
return sb;
}
catch (Exception x)
{
throw UnexpectedException.wrap(x);
}
};
private static final class TemplateAppendableWrapper implements Appendable
{
final Appendable out;
final StringBuilder sb = new StringBuilder();
Appendable current;
TemplateAppendableWrapper(Appendable out)
{
this.out = out;
this.current = out;
}
void bufferRemainingOutput()
{
this.current = sb;
}
HtmlString getEndMarkup()
{
return HtmlString.unsafe(sb.toString());
}
@Override
public Appendable append(CharSequence csq) throws IOException
{
current.append(csq);
return this;
}
@Override
public Appendable append(CharSequence csq, int start, int end) throws IOException
{
current.append(csq, start, end);
return this;
}
@Override
public Appendable append(char c) throws IOException
{
current.append(c);
return this;
}
}
public static HtmlString renderTemplate(Renderable r, Appendable out)
{
var wrapper = new TemplateAppendableWrapper(out);
r.appendTo(wrapper);
return wrapper.getEndMarkup();
}
public enum Element
{
a,
abbr,
address,
area(true),
article,
aside,
audio,
b,
base(true),
bdi,
bdo,
big,
blockquote,
body,
br(true),
button,
canvas,
caption,
cite,
code,
col(true),
colgroup,
data,
datalist,
dd,
del,
details,
dfn,
dialog,
div,
dl,
dt,
em,
embed(true),
fieldset,
figcaption,
figure,
footer,
font,
form,
h1,
h2,
h3,
h4,
h5,
h6,
head,
header,
hgroup,
hr(true),
html,
i,
iframe,
img(true),
input(true),
ins,
kbd,
keygen(true),
label,
legend,
li,
link(true),
main,
map,
mark,
menu,
menuitem(true),
meta(true),
meter,
nav,
noindex,
noscript,
object,
ol,
optgroup,
option,
output,
p,
param(true),
picture,
pre,
progress,
q,
rp,
rt,
ruby,
s,
samp,
script,
section,
select,
small,
source(true),
span,
strong,
style,
sub,
summary,
sup,
table,
tbody,
td,
textarea,
tfoot,
th,
thead,
time,
title,
tr,
track(true),
u,
ul,
var,
video,
wbr(true),
webview;
final boolean _selfClosing;
Element()
{
_selfClosing = false;
}
Element(boolean b)
{
_selfClosing = b;
}
private Appendable _render(Appendable builder, Iterable<Map.Entry<Object, Object>> attrs, Object... body) throws IOException
{
return appendElement(builder, name(), _selfClosing, attrs, body);
}
final Appendable render(Appendable builder, Iterable<Map.Entry<Object,Object>> attrs, Object...body)
{
try
{
return _render(builder, attrs, body);
}
catch (IOException io)
{
throw new RuntimeException(io);
}
}
}
public enum Attribute
{
accept,
accesskey,
action,
align,
alt,
async,
autocomplete,
autofocus,
autoplay,
bgcolor,
border,
cellpadding,
charset,
checked
{
@Override
Appendable render(Appendable builder, Object value) throws IOException
{
if (value != Boolean.FALSE)
builder.append(" checked");
return builder;
}
},
cite,
color,
cols,
colspan,
content,
contenteditable,
controls,
coords,
data,
datetime,
defaultValue,
defer,
dir,
dirname,
disabled,
download,
draggable,
dropzone,
enctype,
form,
formaction,
headers,
height,
hidden,
high,
href,
hreflang,
id,
ismap,
kind,
label,
lang,
list,
loop,
low,
max,
maxlength,
media,
method,
min,
multiple,
muted,
name
{
@Override
Appendable render(Appendable builder, Object value) throws IOException
{
if (value instanceof String s)
value = PageFlowUtil.encodeFormName(s);
return super.render(builder, value);
}
},
nonce,
novalidate
{
@Override
Appendable render(Appendable builder, Object value) throws IOException
{
if (value != Boolean.FALSE)
builder.append(" novalidate");
return builder;
}
},
open,
optimum,
pattern,
placeholder,
poster,
preload,
readonly,
rel,
required,
reversed,
rows,
rowspan,
sandbox,
scope,
selected
{
@Override
Appendable render(Appendable builder, Object value) throws IOException
{
if (value != Boolean.FALSE)
builder.append(" selected");
return builder;
}
},
shape,
size,
sizes,
span,
spellcheck,
src,
srcdoc,
srclang,
srcset,
start,
step,
style
{
@Override
Appendable render(Appendable builder, Object value) throws IOException
{
if (value instanceof Map)
{
throw new NotImplementedException("not yet");
}
return super.render(builder,value);
}
},
tabindex,
target,
title,
translate,
type,
usemap,
valign,
value,
width,
wrap,
;
Appendable render(Appendable builder, Object value) throws IOException
{
return appendAttribute(builder, this, value);
}
static boolean isa(String name)
{
try
{
Attribute.valueOf(name);
return true;
}
catch (IllegalArgumentException x)
{
return false;
}
}
}
public static class _Attributes implements Attributes
{
static Joiner j = Joiner.on(" ").skipNulls();
ArrayList<Map.Entry<Attribute,Object>> attrs = new ArrayList<>();
Set<String> classes = new TreeSet<>();
ArrayList<Map.Entry<String,Object>> expandos = null;
_Attributes()
{
}
_Attributes(Attribute firstKey, Object firstValue, Object... keyvalues)
{
at(firstKey, firstValue, keyvalues);
}
public _Attributes at(Attribute firstKey, Object firstValue, Object... keyvalues)
{
at(firstKey, firstValue);
assert keyvalues.length % 2 == 0;
for (int i=0 ; i<keyvalues.length ; i+=2)
at((Attribute)keyvalues[i], keyvalues[i+1]);
return this;
}
public _Attributes at(Attribute key, Object value)
{
attrs.add(new Pair<>(key,value));
return this;
}
public _Attributes at(boolean test, Attribute key, Object value)
{
if (test)
attrs.add(new Pair<>(key,value));
return this;
}
public _Attributes at(boolean test, Attribute key, Object ifValue, Object elseValue)
{
if (test)
attrs.add(new Pair<>(key,ifValue));
else
attrs.add(new Pair<>(key,elseValue));
return this;
}
public _Attributes data(String datakey, Object value)
{
if (null == expandos)
expandos = new ArrayList<>();
expandos.add(new Pair<>("data-"+datakey,value));
return this;
}
public _Attributes data(boolean condition, String datakey, Object value)
{
if (condition)
{
if (null == expandos)
expandos = new ArrayList<>();
expandos.add(new Pair<>("data-"+datakey,value));
}
return this;
}
public _Attributes aria(String ariakey, Object value)
{
if (null == expandos)
expandos = new ArrayList<>();
expandos.add(new Pair<>("aria-" + ariakey,value));
return this;
}
public _Attributes aria(boolean condition, String ariakey, Object value)
{
if (condition)
{
if (null == expandos)
expandos = new ArrayList<>();
expandos.add(new Pair<>("aria-" + ariakey,value));
}
return this;
}
public _Attributes cl(String...names)
{
if (null != names)
Arrays.stream(names).filter(Objects::nonNull).forEach(name -> classes.add(name));
return this;
}
public _Attributes cl(boolean test, String className)
{
if (test && null!=className)
classes.add(className);
return this;
}
// Calculates the className only if test is true
public _Attributes cl(boolean test, Supplier<String> classNameSupplier)
{
String className;
if (test && null != (className = classNameSupplier.get()))
classes.add(className);
return this;
}
public _Attributes cl(boolean test, String trueName, String falseName)
{
if (test && null != trueName)
classes.add(trueName);
else if (!test && null != falseName)
classes.add(falseName);
return this;
}
@NotNull
@Override
public Iterator<Map.Entry<Object, Object>> iterator()
{
var it = (Iterator<Map.Entry<Object, Object>>)(Iterator)attrs.iterator();
if (!classes.isEmpty())
it = Iterators.concat(it, Iterators.singletonIterator(new Pair<>("class", j.join(classes))));
if (null != expandos)
it = Iterators.concat(it,(Iterator<Map.Entry<Object, Object>>)(Iterator)expandos.iterator());
return it;
}
// builder style methods
public _Attributes colspan(int c)
{
return at(Attribute.colspan,c);
}
public _Attributes id(String id)
{
return at(Attribute.id,id);
}
public _Attributes method(String m)
{
return at(Attribute.method,m.toUpperCase());
}
public _Attributes name(String n)
{
return at(Attribute.name,n);
}
public _Attributes type(String t)
{
return at(Attribute.type,t);
}
public _Attributes value(String v)
{
return at(Attribute.value,v);
}
public _Attributes value(int v)
{
return at(Attribute.value,String.valueOf(v));
}
}
public static _Attributes at()
{
return new _Attributes();
}
public static _Attributes at(Map map)
{
var ret = new _Attributes();
map.forEach( (k,v) -> {
if (k instanceof Attribute)
{
ret.at((Attribute) k, v);
}
else
{
if (!(k instanceof String sk))
throw new IllegalStateException("expected Attribute or String");
if (sk.startsWith("data-"))
ret.data(sk.substring("data-".length()), v);
else
ret.at(Attribute.valueOf(sk), v);
}
});
return ret;
}
/* copy attributes, useful for extended/custom elements */
public static _Attributes at(Attributes attrsIn)
{
if (!(attrsIn instanceof _Attributes in))
throw new UnsupportedOperationException();
_Attributes copy = new _Attributes();
copy.attrs.addAll(in.attrs);
copy.classes.addAll(in.classes);
if (in.expandos != null)
{
copy.expandos = new ArrayList<>();
copy.expandos.addAll(in.expandos);
}
return copy;
}
public static _Attributes at(Attribute firstKey, Object firstValue, Object... keyvalues)
{
return new _Attributes(firstKey,firstValue,keyvalues);
}
public static _Attributes at(boolean test, Attribute key, Object value)
{
return new _Attributes().at(test, key, value);
}
public static _Attributes at(boolean test, Attribute key, Object ifValue, Object elseValue)
{
return new _Attributes().at(test, key, ifValue, elseValue);
}
public static _Attributes cl(boolean f, String className)
{
return new _Attributes().cl(f, className);
}
public static _Attributes cl(boolean f, String trueName, String falseName)
{
return new _Attributes().cl(f, trueName, falseName);
}
public static _Attributes cl(String... classNames)
{
var ret = new _Attributes();
Arrays.stream(classNames).filter(Objects::nonNull).forEach(ret::cl);
return ret;
}
public static _Attributes id(String value)
{
return new _Attributes(Attribute.id, value);
}
// TODO parse css selector style strings e.g. css("#header1.bold")
public static _Attributes css(String selector)
{
// TODO
return new _Attributes();
}
public static Renderable el(Element element, Iterable<Map.Entry<Object, Object>> attrs, ClassNames classNames, Object... body)
{
return (html) -> element.render(html, attrs, classNames, body);
}
public static HtmlString createHtml(Renderable fn)
{
return unsafe(fn.appendTo(new StringBuilder()).toString());
}
public static Appendable createHtml(Appendable html, Renderable fn)
{
fn.appendTo(html);
return html;
}
public static HtmlString createHtmlFragment(Object... body)
{
try
{
return unsafe(appendElement(new StringBuilder(), null, false, null, body).toString());
}
catch (IOException x)
{
throw new RuntimeException(x);
}
}
public static Appendable createHtmlFragment(Appendable html, Object... body)
{
try
{
return appendElement(html, null, false, null, body);
}
catch (IOException x)
{
throw new RuntimeException(x);
}
}
// LabKey extensions, any helpers that are not directly representations of native browser DOM
public static class LK
{
public static Renderable CHECKBOX(Attributes attrs)
{
// find name attribute
String name = null;
for (var attr : attrs)
{
if (attr.getKey()==Attribute.name)
{
name = String.valueOf(attr.getValue());
break;
}
}
return createHtmlFragment(
DOM.INPUT((at(attrs).at(Attribute.type,"checkbox"))),
null==name?null:DOM.INPUT(at(Attribute.type,"hidden", Attribute.name, SpringActionController.FIELD_MARKER+name))
);
}
/** font-awesome */
public static Renderable FA(String icon)
{
return (html) -> Element.i.render(html, cl("fa", "fa-"+icon));
}
public static Renderable FORM(Object... body)
{
return FORM(at(Attribute.method,"GET"), body);
}
public static Renderable FORM(Attributes attrs, Object... body)
{
boolean isPost = false;
if (null != attrs)
for (var attr : attrs)
{
if (attr.getKey() == Attribute.method && "POST".equalsIgnoreCase(String.valueOf(attr.getValue())))
{
isPost = true;
break;
}
}
var csrfInput = !isPost ? null : new CsrfInput(HttpView.currentContext());
// Put the CSRF token first to ensure it's available even if the full HTTP POST body hasn't been parsed
return DOM.FORM(attrs, csrfInput, body);
}
public static Renderable ERRORS(PageContext pageContext)
{
Enumeration<String> e = pageContext.getAttributeNamesInScope(PageContext.REQUEST_SCOPE);
List<Renderable> list = new ArrayList<>();
while (e.hasMoreElements())
{
String s = e.nextElement();
if (s.startsWith(BindingResult.MODEL_KEY_PREFIX))
{
Object o = pageContext.getAttribute(s, PageContext.REQUEST_SCOPE);
if (o instanceof BindingResult)
list.add(ERRORS((BindingResult)o));
}
}
if (list.isEmpty())
return null;
return createHtmlFragment(list.toArray());
}
public static Renderable ERRORS(BindingResult errors)
{
return ERRORS(errors.getAllErrors());
}
public static Renderable ERRORS(List<ObjectError> z)
{
if (null == z || z.isEmpty())
return HtmlString.EMPTY_STRING;
final ViewContext context = HttpView.getRootContext();
return DIV(cl("labkey-error"),
z.stream().map(error ->
{
try
{
if (error instanceof LabKeyError)
return createHtmlFragment((((LabKeyError)error).renderToHTML(context)),BR());
else
return createHtmlFragment(HtmlString.unsafe(PageFlowUtil.filter(context.getMessage(error), true)),BR());
}
catch (NoSuchMessageException nsme)
{
ExceptionUtil.logExceptionToMothership(context.getRequest(), nsme);
Logger log = LogManager.getLogger(ErrorsTag.class);
log.error("Failed to find a message: " + error, nsme);
return createHtmlFragment("Unknown error: " + error, BR());
}
})
);
}
}
private static Appendable appendAttribute(Appendable html, String key, Object value) throws IOException
{
if (null==value)
return html;
html.append(" ");
if (StringUtils.containsAny(key," \t\"\'<>"))
throw new IllegalArgumentException(key);
html.append(filter(key));
html.append("=\"");
String s = String.valueOf(value);
if (StringUtils.isNotBlank(s))
html.append(filter(s));
html.append("\"");
return html;
}
private static Appendable appendAttribute(Appendable html, Attribute key, Object value) throws IOException
{
if (null==value)
return html;
html.append(" ");
html.append(key.name());
html.append("=\"");
// NOTE it is somewhat unusual to pass in a Renderable, but it is possible that we
// want to render HTML into an attribute. We still need to re-encode the value before trying to wrap with "".
if (value instanceof Renderable r)
{
html.append(filter(r.renderToString()));
}
else
{
String s = String.valueOf(value);
if (StringUtils.isNotBlank(s))
html.append(filter(s));
}
html.append("\"");
return html;
}
/**
* @param body supported values include null (nothing is included in the generated HTML),
* CharSequence (like String, StringBuilder, etc),
* Number (assumed to be safe to render without encoding),
* DOM.Renderable (like the DIV, SPAN, or TABLE methods return),
* any kind of array or Iterable containing the other supported elements,
* or any kind of Stream containing the other supported elements
* This method doesn't throw checked exception, because it makes using lambdas a big pain
*/
private static Appendable appendBody(Appendable builder, Object body)
{
if (null == body)
return builder;
else if (body instanceof CharSequence cs)
{
try
{
builder.append(filter(cs));
}
catch (IOException io)
{
throw new RuntimeException(io);
}
}
else if (body instanceof Number)
{
try
{
builder.append(body.toString());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
else if (body instanceof Boolean b)
{
try
{
builder.append(Boolean.toString(b));
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
else if (body instanceof DOM.Renderable)
{
((DOM.Renderable) body).appendTo(builder);
}
else if (body.getClass().isArray())
{
for (var i : (Object[]) body)
appendBody(builder, i);
}
else if (body instanceof Iterable)
{
for (var i : ((Iterable<?>)body))
appendBody(builder, i);
}
else if (body instanceof Stream)
{
((Stream<Object>) body).forEach(i -> appendBody(builder, i));