-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathRenderKitUtils.java
More file actions
1734 lines (1459 loc) · 73.5 KB
/
RenderKitUtils.java
File metadata and controls
1734 lines (1459 loc) · 73.5 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
/*
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.faces.renderkit;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.BEHAVIOR_EVENT_PARAM;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.BEHAVIOR_SOURCE_PARAM;
import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EVENT_PARAM;
import static jakarta.faces.application.ResourceHandler.FACES_SCRIPT_LIBRARY_NAME;
import static jakarta.faces.application.ResourceHandler.FACES_SCRIPT_RESOURCE_NAME;
import static java.util.stream.Collectors.toList;
import java.io.IOException;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.el.ValueExpression;
import jakarta.faces.FacesException;
import jakarta.faces.FactoryFinder;
import jakarta.faces.application.Application;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.application.ProjectStage;
import jakarta.faces.application.Resource;
import jakarta.faces.application.ResourceHandler;
import jakarta.faces.component.ActionSource;
import jakarta.faces.component.Doctype;
import jakarta.faces.component.UIComponent;
import jakarta.faces.component.UIComponentBase;
import jakarta.faces.component.UIForm;
import jakarta.faces.component.UIOutput;
import jakarta.faces.component.UIViewRoot;
import jakarta.faces.component.behavior.AjaxBehavior;
import jakarta.faces.component.behavior.ClientBehavior;
import jakarta.faces.component.behavior.ClientBehaviorContext;
import jakarta.faces.component.behavior.ClientBehaviorHint;
import jakarta.faces.component.behavior.ClientBehaviorHolder;
import jakarta.faces.component.html.HtmlEvents.HtmlDocumentElementEvent;
import jakarta.faces.component.html.HtmlMessages;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.PartialViewContext;
import jakarta.faces.context.ResponseWriter;
import jakarta.faces.event.BehaviorEvent.FacesComponentEvent;
import jakarta.faces.model.SelectItem;
import jakarta.faces.render.RenderKit;
import jakarta.faces.render.RenderKitFactory;
import jakarta.faces.render.Renderer;
import jakarta.faces.render.ResponseStateManager;
import com.sun.faces.RIConstants;
import com.sun.faces.application.ApplicationAssociate;
import com.sun.faces.el.ELUtils;
import com.sun.faces.facelets.util.DevTools;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.RequestStateManager;
import com.sun.faces.util.Util;
/**
* <p>
* A set of utilities for use in {@link RenderKit}s.
* </p>
*/
public class RenderKitUtils {
/**
* <p>
* The prefix to append to certain attributes when renderking <code>XHTML Transitional</code> content.
*/
private static final String XHTML_ATTR_PREFIX = "xml:";
/**
* <p>
* <code>Boolean</code> attributes to be rendered using <code>XHMTL</code> semantics.
*/
private static final String[] BOOLEAN_ATTRIBUTES = { "disabled", "ismap", "readonly", "multiple" };
/**
* <p>
* An array of attributes that must be prefixed by {@link #XHTML_ATTR_PREFIX} when rendering
* <code>XHTML Transitional</code> content.
*/
private static final String[] XHTML_PREFIX_ATTRIBUTES = { "lang" };
/**
* <p>
* The maximum number of content type parts. For example: for the type: "text/html; level=1; q=0.5" The parts of this
* type would be: "text" - type "html; level=1" - subtype "0.5" - quality value "1" - level value
* </p>
*/
private final static int MAX_CONTENT_TYPE_PARTS = 4;
/**
* The character that is used to delimit content types in an accept String.
* </p>
*/
private final static String CONTENT_TYPE_DELIMITER = ",";
/**
* The character that is used to delimit the type and subtype portions of a content type in an accept String. Example:
* text/html
* </p>
*/
private final static String CONTENT_TYPE_SUBTYPE_DELIMITER = "/";
/**
* This represents the base package that can leverage the <code>attributesThatAreSet</code> List for optimized attribute
* rendering.
*
* IMPLEMENTATION NOTE: This must be kept in sync with the array in UIComponentBase$AttributesMap and
* HtmlComponentGenerator.
*
* Hopefully Faces X will remove the need for this.
*/
private static final String OPTIMIZED_PACKAGE = "jakarta.faces.component.";
/**
* IMPLEMENTATION NOTE: This must be kept in sync with the Key in UIComponentBase$AttributesMap and
* HtmlComponentGenerator.
*
* Hopefully Faces X will remove the need for this.
*/
private static final String ATTRIBUTES_THAT_ARE_SET_KEY = UIComponentBase.class.getName() + ".attributesThatAreSet";
private static final String BEHAVIOR_EVENT_ATTRIBUTE_PREFIX = "on";
protected static final Logger LOGGER = FacesLogger.RENDERKIT.getLogger();
public static final String DEVELOPMENT_STAGE_MESSAGES_ID = "jakarta_faces_developmentstage_messages";
/**
* @see UIViewRoot#encodeChildren(FacesContext)
*/
public enum PredefinedPostbackParameter {
VIEW_STATE_PARAM(ResponseStateManager.VIEW_STATE_PARAM), CLIENT_WINDOW_PARAM(ResponseStateManager.CLIENT_WINDOW_PARAM),
RENDER_KIT_ID_PARAM(ResponseStateManager.RENDER_KIT_ID_PARAM), BEHAVIOR_SOURCE_PARAM(ClientBehaviorContext.BEHAVIOR_SOURCE_PARAM_NAME),
BEHAVIOR_EVENT_PARAM(ClientBehaviorContext.BEHAVIOR_EVENT_PARAM_NAME), PARTIAL_EVENT_PARAM(PartialViewContext.PARTIAL_EVENT_PARAM_NAME),
PARTIAL_EXECUTE_PARAM(PartialViewContext.PARTIAL_EXECUTE_PARAM_NAME), PARTIAL_RENDER_PARAM(PartialViewContext.PARTIAL_RENDER_PARAM_NAME),
PARTIAL_RESET_VALUES_PARAM(PartialViewContext.RESET_VALUES_PARAM_NAME);
private String name;
private PredefinedPostbackParameter(String name) {
this.name = name;
}
public String getValue(FacesContext context) {
return context.getExternalContext().getRequestParameterMap().get(getName(context));
}
public String getName(FacesContext context) {
return getParameterName(context, name);
}
}
// ------------------------------------------------------------ Constructors
private RenderKitUtils() {
}
// ---------------------------------------------------------- Public Methods
/**
* <p>
* Return the {@link RenderKit} for the current request.
* </p>
*
* @param context the {@link FacesContext} of the current request
* @return the {@link RenderKit} for the current request.
*/
public static RenderKit getCurrentRenderKit(FacesContext context) {
RenderKitFactory renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
return renderKitFactory.getRenderKit(context, context.getViewRoot().getRenderKitId());
}
/**
* <p>
* Obtain and return the {@link ResponseStateManager} for the specified #renderKitId.
* </p>
*
* @param context the {@link FacesContext} of the current request
* @param renderKitId {@link RenderKit} ID
* @return the {@link ResponseStateManager} for the specified #renderKitId
* @throws FacesException if an exception occurs while trying to obtain the <code>ResponseStateManager</code>
*/
public static ResponseStateManager getResponseStateManager(FacesContext context, String renderKitId) throws FacesException {
assert null != renderKitId;
assert null != context;
RenderKit renderKit = context.getRenderKit();
if (renderKit == null) {
// check request scope for a RenderKitFactory implementation
RenderKitFactory factory = (RenderKitFactory) RequestStateManager.get(context, RequestStateManager.RENDER_KIT_IMPL_REQ);
if (factory != null) {
renderKit = factory.getRenderKit(context, renderKitId);
} else {
factory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
if (factory == null) {
throw new FacesException("Unable to locate RenderKitFactory for " + FactoryFinder.RENDER_KIT_FACTORY);
} else {
RequestStateManager.set(context, RequestStateManager.RENDER_KIT_IMPL_REQ, factory);
}
renderKit = factory.getRenderKit(context, renderKitId);
if (renderKit == null) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE, "Unable to locate renderkit " + "instance for render-kit-id {0}. Using {1} instead.",
new String[] { renderKitId, RenderKitFactory.HTML_BASIC_RENDER_KIT });
}
renderKitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
UIViewRoot root = context.getViewRoot();
if (null != root) {
root.setRenderKitId(renderKitId);
}
}
renderKit = factory.getRenderKit(context, renderKitId);
if (renderKit == null) {
throw new FacesException("Unable to locate renderkit instance for render-kit-id " + renderKitId);
}
}
}
return renderKit.getResponseStateManager();
}
/**
* <p>
* Return a List of {@link jakarta.faces.model.SelectItem} instances representing the available options for this
* component, assembled from the set of {@link jakarta.faces.component.UISelectItem} and/or
* {@link jakarta.faces.component.UISelectItems} components that are direct children of this component. If there are no
* such children, an empty <code>Iterator</code> is returned.
* </p>
*
* @param context The {@link jakarta.faces.context.FacesContext} for the current request. If null, the UISelectItems
* behavior will not work.
* @param component the component
* @throws IllegalArgumentException if <code>context</code> is <code>null</code>
* @return a List of the select items for the specified component
*/
public static SelectItemsIterator<SelectItem> getSelectItems(FacesContext context, UIComponent component) {
Util.notNull("context", context);
Util.notNull("component", component);
return new SelectItemsIterator<>(context, component);
}
/**
* <p>
* Render any "passthru" attributes, where we simply just output the raw name and value of the attribute. This method is
* aware of the set of HTML4 attributes that fall into this bucket. Examples are all the javascript attributes, alt,
* rows, cols, etc.
* </p>
*
* @param context the FacesContext for this request
* @param writer writer the {@link jakarta.faces.context.ResponseWriter} to be used when writing the attributes
* @param component the component
* @param attributes an array of attributes to be processed
* @throws IOException if an error occurs writing the attributes
*/
public static void renderPassThruAttributes(FacesContext context, ResponseWriter writer, UIComponent component, Attribute[] attributes) throws IOException {
assert null != context;
assert null != writer;
assert null != component;
Map<String, List<ClientBehavior>> behaviors = null;
if (component instanceof ClientBehaviorHolder) {
behaviors = ((ClientBehaviorHolder) component).getClientBehaviors();
}
// Don't render behavior scripts if component is disabled
if (null != behaviors && behaviors.size() > 0 && Util.componentIsDisabled(component)) {
behaviors = null;
}
renderPassThruAttributes(context, writer, component, attributes, behaviors);
}
/**
* <p>
* Render any "passthru" attributes, where we simply just output the raw name and value of the attribute. This method is
* aware of the set of HTML4 attributes that fall into this bucket. Examples are all the javascript attributes, alt,
* rows, cols, etc.
* </p>
*
* @param context the FacesContext for this request
* @param writer writer the {@link jakarta.faces.context.ResponseWriter} to be used when writing the attributes
* @param component the component
* @param attributes an array of attributes to be processed
* @param behaviors the behaviors for this component, or null if component is not a ClientBehaviorHolder
* @throws IOException if an error occurs writing the attributes
*/
@SuppressWarnings("unchecked")
public static void renderPassThruAttributes(FacesContext context, ResponseWriter writer, UIComponent component, Attribute[] attributes,
Map<String, List<ClientBehavior>> behaviors) throws IOException {
assert null != writer;
assert null != component;
if (behaviors == null) {
behaviors = Collections.emptyMap();
}
List<String> setAttributes = (List<String>) component.getAttributes().get(ATTRIBUTES_THAT_ARE_SET_KEY);
if (setAttributes != null && canBeOptimized(component, behaviors)) {
renderPassThruAttributesOptimized(context, writer, component, attributes, setAttributes, behaviors);
} else {
// this block should only be hit by custom components leveraging
// the RI's rendering code, or in cases where we have behaviors
// attached to multiple events. We make no assumptions and loop
// through
renderPassThruAttributesUnoptimized(context, writer, component, attributes, setAttributes, behaviors);
}
}
// Renders the onchange handler for input components. Handles
// chaining together the user-provided onchange handler with
// any Behavior scripts.
public static void renderOnchange(FacesContext context, UIComponent component, boolean incExec) throws IOException {
final String handlerName = "onchange";
final Object userHandler = component.getAttributes().get(handlerName);
String behaviorEventName = FacesComponentEvent.valueChange.name();
String domEventName = HtmlDocumentElementEvent.change.name();
if (component instanceof ClientBehaviorHolder) {
Map<?, ?> behaviors = ((ClientBehaviorHolder) component).getClientBehaviors();
if (null != behaviors && behaviors.containsKey(domEventName)) {
behaviorEventName = domEventName;
}
}
List<ClientBehaviorContext.Parameter> params;
if (!incExec) {
params = Collections.emptyList();
} else {
params = new LinkedList<>();
params.add(new ClientBehaviorContext.Parameter("incExec", true));
}
renderHandler(context, component, params, handlerName, userHandler, behaviorEventName, null, false, incExec);
}
// Renders onclick handler for SelectRaidio and SelectCheckbox
public static void renderSelectOnclick(FacesContext context, UIComponent component, boolean incExec) throws IOException {
final String handlerName = "onclick";
final Object userHandler = component.getAttributes().get(handlerName);
String behaviorEventName = FacesComponentEvent.valueChange.name();
String domEventName = HtmlDocumentElementEvent.click.name();
if (component instanceof ClientBehaviorHolder) {
Map<?, ?> behaviors = ((ClientBehaviorHolder) component).getClientBehaviors();
if (null != behaviors && behaviors.containsKey(domEventName)) {
behaviorEventName = domEventName;
}
}
List<ClientBehaviorContext.Parameter> params;
if (!incExec) {
params = Collections.emptyList();
} else {
params = new LinkedList<>();
params.add(new ClientBehaviorContext.Parameter("incExec", true));
}
renderHandler(context, component, params, handlerName, userHandler, behaviorEventName, null, false, incExec);
}
// Renders the onclick handler for command buttons. Handles
// chaining together the user-provided onclick handler, any
// Behavior scripts, plus the default button submit script.
public static void renderOnclick(FacesContext context, UIComponent component, Collection<ClientBehaviorContext.Parameter> params, String submitTarget,
boolean needsSubmit) throws IOException {
final String handlerName = "onclick";
final Object userHandler = component.getAttributes().get(handlerName);
String behaviorEventName = FacesComponentEvent.action.name();
String domEventName = HtmlDocumentElementEvent.click.name();
if (component instanceof ClientBehaviorHolder) {
Map<String, List<ClientBehavior>> behaviors = ((ClientBehaviorHolder) component).getClientBehaviors();
boolean mixed = null != behaviors && behaviors.containsKey(domEventName) && behaviors.containsKey(behaviorEventName);
if (mixed) {
List<ClientBehavior> actionBehaviors = behaviors.get(behaviorEventName);
behaviorEventName = domEventName;
List<ClientBehavior> clickBehaviors = behaviors.get(domEventName);
clickBehaviors.addAll(actionBehaviors);
actionBehaviors.clear();
} else if (null != behaviors && behaviors.containsKey(domEventName)) {
behaviorEventName = domEventName;
}
}
renderHandler(context, component, params, handlerName, userHandler, behaviorEventName, submitTarget, needsSubmit, false);
}
// Renders the script function for command scripts.
public static void renderFunction(FacesContext context, UIComponent component, Collection<ClientBehaviorContext.Parameter> params, String submitTarget)
throws IOException {
ClientBehaviorContext behaviorContext = ClientBehaviorContext.createClientBehaviorContext(context, component, FacesComponentEvent.action.name(), submitTarget, params);
AjaxBehavior behavior = (AjaxBehavior) context.getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
mapAttributes(component, behavior, "execute", "render", "onerror", "onevent", "resetValues");
context.getResponseWriter().append(behavior.getScript(behaviorContext));
}
private static void mapAttributes(UIComponent component, AjaxBehavior behavior, String... attributeNames) {
for (String attributeName : attributeNames) {
ValueExpression binding = component.getValueExpression(attributeName);
if (binding == null) {
Object value = component.getAttributes().get(attributeName);
if (value != null) {
binding = ELUtils.createValueExpression(value.toString(), value.getClass());
}
}
behavior.setValueExpression(attributeName, binding);
}
}
public static String prefixAttribute(final String attrName, final ResponseWriter writer) {
return prefixAttribute(attrName, RIConstants.XHTML_CONTENT_TYPE.equals(writer.getContentType()));
}
public static String prefixAttribute(final String attrName, boolean isXhtml) {
if (isXhtml) {
if (Arrays.binarySearch(XHTML_PREFIX_ATTRIBUTES, attrName) > -1) {
return XHTML_ATTR_PREFIX + attrName;
} else {
return attrName;
}
} else {
return attrName;
}
}
/**
* <p>
* Renders the attributes from {@link #BOOLEAN_ATTRIBUTES} using <code>XHMTL</code> semantics (i.e.,
* disabled="disabled").
* </p>
*
* @param writer writer the {@link ResponseWriter} to be used when writing the attributes
* @param component the component
* @throws IOException if an error occurs writing the attributes
*/
public static void renderXHTMLStyleBooleanAttributes(ResponseWriter writer, UIComponent component) throws IOException {
assert writer != null;
assert component != null;
List<String> excludedAttributes = null;
renderXHTMLStyleBooleanAttributes(writer, component, excludedAttributes);
}
/**
* <p>
* Renders the attributes from {@link #BOOLEAN_ATTRIBUTES} using <code>XHMTL</code> semantics (i.e.,
* disabled="disabled").
* </p>
*
* @param writer writer the {@link ResponseWriter} to be used when writing the attributes
* @param component the component
* @param excludedAttributes a <code>List</code> of attributes that are to be excluded from rendering
* @throws IOException if an error occurs writing the attributes
*/
public static void renderXHTMLStyleBooleanAttributes(ResponseWriter writer, UIComponent component, List<String> excludedAttributes) throws IOException {
assert writer != null;
assert component != null;
Map<?, ?> attrMap = component.getAttributes();
for (String attrName : BOOLEAN_ATTRIBUTES) {
if (isExcludedAttribute(attrName, excludedAttributes)) {
continue;
}
Object val = attrMap.get(attrName);
if (val == null) {
continue;
}
if (Boolean.valueOf(val.toString())) {
writer.writeAttribute(attrName, true, attrName);
}
}
}
/**
* <p>
* Given an accept String from the client, and a <code>String</code> of server supported content types, determine the
* best qualified content type for the client. If no match is found, or either of the arguments are <code>null</code>,
* <code>null</code> is returned.
* </p>
*
* @param accept The client accept String
* @param serverSupportedTypes The types that the server supports
* @param preferredType The preferred content type if another type is found with the same highest quality factor.
* @return The content type <code>String</code>
*/
public static String determineContentType(String accept, String serverSupportedTypes, String preferredType) {
String contentType = null;
if (null == accept || null == serverSupportedTypes) {
return contentType;
}
String[][] clientContentTypes = buildTypeArrayFromString(accept);
String[][] serverContentTypes = buildTypeArrayFromString(serverSupportedTypes);
String[][] preferredContentType = buildTypeArrayFromString(preferredType);
String[][] matchedInfo = findMatch(clientContentTypes, serverContentTypes, preferredContentType);
// if best match exits and best match is not some wildcard,
// return best match
if (matchedInfo[0][1] != null && !matchedInfo[0][2].equals("*")) {
contentType = matchedInfo[0][1] + CONTENT_TYPE_SUBTYPE_DELIMITER + matchedInfo[0][2];
}
return contentType;
}
/**
* @param contentType the content type in question
* @return <code>true</code> if the content type is a known XML-based content type, otherwise, <code>false</code>
*/
public static boolean isXml(String contentType) {
return RIConstants.XHTML_CONTENT_TYPE.equals(contentType) || RIConstants.APPLICATION_XML_CONTENT_TYPE.equals(contentType)
|| RIConstants.TEXT_XML_CONTENT_TYPE.equals(contentType);
}
// --------------------------------------------------------- Private Methods
/**
* @param component the UIComponent in question
* @return <code>true</code> if the component is within the <code>jakarta.faces.component</code> or
* <code>jakarta.faces.component.html</code> packages, otherwise return <code>false</code>
*/
private static boolean canBeOptimized(UIComponent component, Map<String, List<ClientBehavior>> behaviors) {
assert component != null;
assert behaviors != null;
String name = component.getClass().getName();
if (name != null && name.startsWith(OPTIMIZED_PACKAGE)) {
// If we've got behaviors attached to multiple events
// it is difficult to optimize, so fall back to the
// non-optimized code path. Behaviors attached to
// multiple event handlers should be a fairly rare case.
return behaviors.size() < 2;
}
return false;
}
/**
* <p>
* For each attribute in <code>setAttributes</code>, perform a binary search against the array of
* <code>knownAttributes</code> If a match is found and the value is not <code>null</code>, render the attribute.
*
* @param context the {@link FacesContext} of the current request
* @param writer the current writer
* @param component the component whose attributes we're rendering
* @param knownAttributes an array of pass-through attributes supported by this component
* @param setAttributes a <code>List</code> of attributes that have been set on the provided component
* @param behaviors the non-null behaviors map for this request.
* @throws IOException if an error occurs during the write
*/
private static void renderPassThruAttributesOptimized(FacesContext context, ResponseWriter writer, UIComponent component, Attribute[] knownAttributes,
List<String> setAttributes, Map<String, List<ClientBehavior>> behaviors) throws IOException {
// We should only come in here if we've got zero or one behavior event
assert behaviors != null && behaviors.size() < 2;
String behaviorEventName = getSingleBehaviorEventName(behaviors);
boolean renderedBehavior = false;
Collections.sort(setAttributes);
boolean isXhtml = RIConstants.XHTML_CONTENT_TYPE.equals(writer.getContentType());
Map<String, Object> attrMap = component.getAttributes();
for (String name : setAttributes) {
// Note that this search can be optimized by switching from
// an array to a Map<String, Attribute>. This would change
// the search time from O(log n) to O(1).
int index = Arrays.binarySearch(knownAttributes, Attribute.attr(name));
if (index >= 0) {
Object value = attrMap.get(name);
if (value != null && shouldRenderAttribute(value)) {
Attribute attr = knownAttributes[index];
if (isBehaviorEventAttribute(attr, behaviorEventName)) {
renderHandler(context, component, null, name, value, behaviorEventName, null, false, false);
renderedBehavior = true;
} else {
writer.writeAttribute(prefixAttribute(name, isXhtml), value, name);
}
}
}
else if (isBehaviorEventAttribute(name)) {
Object value = attrMap.get(name);
if (value != null && shouldRenderAttribute(value)) {
if (name.substring(2).equals(behaviorEventName)) {
renderHandler(context, component, null, name, value, behaviorEventName, null, false, false);
renderedBehavior = true;
} else {
writer.writeAttribute(prefixAttribute(name, isXhtml), value, name);
}
}
}
}
// We did not render out the behavior as part of our optimized
// attribute rendering. Need to manually render it out now.
if (behaviorEventName != null && !renderedBehavior) {
List<String> behaviorAttributes = setAttributes.stream().filter(RenderKitUtils::isBehaviorEventAttribute).collect(toList());
for (String attrName : behaviorAttributes) {
String eventName = attrName.substring(2);
if (behaviorEventName.equals(eventName)) {
renderPassthruAttribute(context, writer, component, behaviors, isXhtml, attrMap, attrName, behaviorEventName);
return;
}
}
// Note that we can optimize this search by providing
// an event name -> Attribute inverse look up map.
// This would change the search time from O(n) to O(1).
for (Attribute attribute : knownAttributes) {
String attrName = attribute.getName();
String[] events = attribute.getEvents();
if (events != null && events.length > 0 && behaviorEventName.equals(events[0])) {
renderHandler(context, component, null, attrName, null, behaviorEventName, null, false, false);
return;
}
}
renderPassthruAttribute(context, writer, component, behaviors, isXhtml, attrMap, BEHAVIOR_EVENT_ATTRIBUTE_PREFIX + behaviorEventName, behaviorEventName);
}
}
/**
* <p>
* Loops over all known attributes and attempts to render each one.
*
* @param context the {@link FacesContext} of the current request
* @param writer the current writer
* @param component the component whose attributes we're rendering
* @param knownAttributes an array of pass-through attributes supported by this component
* @param setAttributes a <code>List</code> of attributes that have been set on the provided component
* @param behaviors the non-null behaviors map for this request.
* @throws IOException if an error occurs during the write
*/
private static void renderPassThruAttributesUnoptimized(FacesContext context, ResponseWriter writer, UIComponent component, Attribute[] knownAttributes,
List<String> setAttributes, Map<String, List<ClientBehavior>> behaviors) throws IOException {
boolean isXhtml = RIConstants.XHTML_CONTENT_TYPE.equals(writer.getContentType());
Map<String, Object> attrMap = component.getAttributes();
Set<String> behaviorEventNames = new LinkedHashSet<>(behaviors.size() + 2);
behaviorEventNames.addAll(behaviors.keySet());
if (setAttributes != null) {
setAttributes.stream().filter(RenderKitUtils::isBehaviorEventAttribute).map(a -> a.substring(BEHAVIOR_EVENT_ATTRIBUTE_PREFIX.length())).forEach(behaviorEventNames::add);
}
for (Attribute attribute : knownAttributes) {
String attrName = attribute.getName();
String[] events = attribute.getEvents();
String eventName = events != null && events.length > 0 ? events[0] : null;
renderPassthruAttribute(context, writer, component, behaviors, isXhtml, attrMap, attrName, eventName);
behaviorEventNames.remove(eventName);
}
for (String eventName : behaviorEventNames) {
renderPassthruAttribute(context, writer, component, behaviors, isXhtml, attrMap, BEHAVIOR_EVENT_ATTRIBUTE_PREFIX + eventName, eventName);
}
}
private static void renderPassthruAttribute(FacesContext context, ResponseWriter writer, UIComponent component,
Map<String, List<ClientBehavior>> behaviors, boolean isXhtml, Map<String, Object> attrMap, String attrName,
String eventName) throws IOException {
boolean hasBehavior = eventName != null && behaviors.containsKey(eventName);
Object value = attrMap.get(attrName);
if (value != null && shouldRenderAttribute(value) && !hasBehavior) {
writer.writeAttribute(prefixAttribute(attrName, isXhtml), value, attrName);
} else if (hasBehavior) {
// If we've got a behavior for this attribute,
// we may need to chain scripts together, so use
// renderHandler().
renderHandler(context, component, null, attrName, value, eventName, null, false, false);
}
}
public static boolean isBehaviorEventAttribute(String name) {
return name.startsWith(BEHAVIOR_EVENT_ATTRIBUTE_PREFIX) && name.length() > 2;
}
/**
* <p>
* Determines if an attribute should be rendered based on the specified #attributeVal.
* </p>
*
* @param attributeVal the attribute value
* @return <code>true</code> if and only if #attributeVal is an instance of a wrapper for a primitive type and its value
* is equal to the default value for that type as given in the specification.
*/
private static boolean shouldRenderAttribute(Object attributeVal) {
if (attributeVal instanceof String) {
return true;
} else if (attributeVal instanceof Boolean && Boolean.FALSE.equals(attributeVal)) {
return false;
} else if (attributeVal instanceof Integer && (Integer) attributeVal == Integer.MIN_VALUE) {
return false;
} else if (attributeVal instanceof Double && (Double) attributeVal == Double.MIN_VALUE) {
return false;
} else if (attributeVal instanceof Character && (Character) attributeVal == Character.MIN_VALUE) {
return false;
} else if (attributeVal instanceof Float && (Float) attributeVal == Float.MIN_VALUE) {
return false;
} else if (attributeVal instanceof Short && (Short) attributeVal == Short.MIN_VALUE) {
return false;
} else if (attributeVal instanceof Byte && (Byte) attributeVal == Byte.MIN_VALUE) {
return false;
} else if (attributeVal instanceof Long && (Long) attributeVal == Long.MIN_VALUE) {
return false;
}
return true;
}
/**
* <p>
* This method expects a <code>List</code> of attribute names that are to be excluded from rendering. A
* <code>Renderer</code> may include an attribute name in this list for exclusion. For example, <code>h:link</code> may
* use the <code>disabled</code> attribute with a value of <code>true</code>. However we don't want
* <code>disabled</code> passed through and rendered on the <code>span</code> element as it is invalid HTML.
* </p>
*
* @param attributeName the attribute name that is to be tested for exclusion
* @param excludedAttributes the list of attribute names that are to be excluded from rendering
* @return <code>true</code> if the attribute name is not in the exclude list.
*/
private static boolean isExcludedAttribute(String attributeName, List<String> excludedAttributes) {
if (null == excludedAttributes) {
return false;
}
if (excludedAttributes.contains(attributeName)) {
return true;
}
return false;
}
/**
* <p>
* This method builds a two element array structure as follows: Example: Given the following accept string: text/html;
* level=1, text/plain; q=0.5 [0][0] 1 (quality is 1 if none specified) [0][1] "text" (type) [0][2] "html; level=1"
* (subtype) [0][3] 1 (level, if specified; null if not)
*
* [1][0] .5 [1][1] "text" [1][2] "plain" [1][3] (level, if specified; null if not)
*
* The array is used for comparison purposes in the findMatch method.
* </p>
*
* @param accept An accept <code>String</code>
* @return an two dimensional array containing content-type/quality info
*/
private static String[][] buildTypeArrayFromString(String accept) {
// return if empty
if (accept == null || accept.length() == 0) {
return new String[0][0];
}
// some helper variables
StringBuilder typeSubType;
String type;
String subtype;
String level = null;
String quality = null;
Map<String, Object> appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
// Parse "types"
String[] types = Util.split(appMap, accept, CONTENT_TYPE_DELIMITER);
String[][] arrayAccept = new String[types.length][MAX_CONTENT_TYPE_PARTS];
int index = -1;
for (int i = 0; i < types.length; i++) {
String token = types[i].trim();
index += 1;
// Check to see if our accept string contains the delimiter that is used
// to add uniqueness to a type/subtype, and/or delimits a qualifier value:
// Example: text/html;level=1,text/html;level=2; q=.5
if (token.contains(";")) {
String[] typeParts = Util.split(appMap, token, ";");
typeSubType = new StringBuilder(typeParts[0].trim());
for (int j = 1; j < typeParts.length; j++) {
quality = "not set";
token = typeParts[j].trim();
// if "level" is present, make sure it gets included in the "type/subtype"
if (token.contains("level")) {
typeSubType.append(';').append(token);
String[] levelParts = Util.split(appMap, token, "=");
level = levelParts[0].trim();
if (level.equalsIgnoreCase("level")) {
level = levelParts[1].trim();
}
} else {
quality = token;
String[] qualityParts = Util.split(appMap, quality, "=");
quality = qualityParts[0].trim();
if (quality.equalsIgnoreCase("q")) {
quality = qualityParts[1].trim();
break;
} else {
quality = "not set"; // to identifiy that no quality was supplied
}
}
}
} else {
typeSubType = new StringBuilder(token);
quality = "not set"; // to identifiy that no quality was supplied
}
// now split type and subtype
if (typeSubType.indexOf(CONTENT_TYPE_SUBTYPE_DELIMITER) >= 0) {
String[] typeSubTypeParts = Util.split(appMap, typeSubType.toString(), CONTENT_TYPE_SUBTYPE_DELIMITER);
// Apparently there are user-agents that send invalid
// Accept headers containing no subtype (i.e. text/).
// For those cases, assume "*" for the subtype.
if (typeSubTypeParts.length == 1) {
type = typeSubTypeParts[0].trim();
subtype = "*";
} else if (typeSubTypeParts.length == 0) {
type = typeSubType.toString();
subtype = "";
} else {
type = typeSubTypeParts[0].trim();
subtype = typeSubTypeParts[1].trim();
}
} else {
type = typeSubType.toString();
subtype = "";
}
// check quality and assign values
if ("not set".equals(quality)) {
if (type.equals("*") && subtype.equals("*")) {
quality = "0.01";
} else if (!type.equals("*") && subtype.equals("*")) {
quality = "0.02";
} else if (type.equals("*") && subtype.length() == 0) {
quality = "0.01";
} else {
quality = "1";
}
}
arrayAccept[index][0] = quality;
arrayAccept[index][1] = type;
arrayAccept[index][2] = subtype;
arrayAccept[index][3] = level;
}
return arrayAccept;
}
/**
* <p>
* For each server supported type, compare client (browser) specified types. If a match is found, keep track of the
* highest quality factor. The end result is that for all matches, only the one with the highest quality will be
* returned.
* </p>
*
* @param clientContentTypes An <code>array</code> of accept <code>String</code> information for the client built
* from @{link #buildTypeArrayFromString}.
* @param serverSupportedContentTypes An <code>array</code> of accept <code>String</code> information for the server
* supported types built from @{link #buildTypeArrayFromString}.
* @param preferredContentType An <code>array</code> of preferred content type information.
* @return An <code>array</code> containing the parts of the preferred content type for the client. The information is
* stored as outlined in @{link #buildTypeArrayFromString}.
*/
private static String[][] findMatch(String[][] clientContentTypes, String[][] serverSupportedContentTypes, String[][] preferredContentType) {
List<String[]> resultList = new ArrayList<>(serverSupportedContentTypes.length);
// the highest quality
double highestQFactor = 0;
// the record with the highest quality
int idx = 0;
for (int sidx = 0, slen = serverSupportedContentTypes.length; sidx < slen; sidx++) {
// get server type
String serverType = serverSupportedContentTypes[sidx][1];
if (serverType != null) {
for (int cidx = 0, clen = clientContentTypes.length; cidx < clen; cidx++) {
// get browser type
String browserType = clientContentTypes[cidx][1];
if (browserType != null) {
// compare them and check for wildcard
if (browserType.equalsIgnoreCase(serverType) || browserType.equals("*")) {
// types are equal or browser type is wildcard - compare subtypes
if (clientContentTypes[cidx][2].equalsIgnoreCase(serverSupportedContentTypes[sidx][2])
|| clientContentTypes[cidx][2].equals("*")) {
// subtypes are equal or browser subtype is wildcard
// found match: multiplicate qualities and add to result array
// if there was a level associated, this gets higher precedence, so
// factor in the level in the calculation.
double cLevel = 0.0;
double sLevel = 0.0;
if (clientContentTypes[cidx][3] != null) {
cLevel = Double.parseDouble(clientContentTypes[cidx][3]) * .10;
}
if (serverSupportedContentTypes[sidx][3] != null) {
sLevel = Double.parseDouble(serverSupportedContentTypes[sidx][3]) * .10;
}
double cQfactor = Double.parseDouble(clientContentTypes[cidx][0]) + cLevel;
double sQfactor = Double.parseDouble(serverSupportedContentTypes[sidx][0]) + sLevel;
double resultQuality = cQfactor * sQfactor;
String[] curResult = new String[MAX_CONTENT_TYPE_PARTS];
resultList.add(curResult);
curResult[0] = String.valueOf(resultQuality);
if (clientContentTypes[cidx][2].equals("*")) {
// browser subtype is wildcard
// return type and subtype (wildcard)
curResult[1] = clientContentTypes[cidx][1];
curResult[2] = clientContentTypes[cidx][2];
} else {
// return server type and subtype
curResult[1] = serverSupportedContentTypes[sidx][1];
curResult[2] = serverSupportedContentTypes[sidx][2];
curResult[3] = serverSupportedContentTypes[sidx][3];
}
// check if this was the highest factor
if (resultQuality > highestQFactor) {
idx = resultList.size() - 1;
highestQFactor = resultQuality;
}
}
}
}
}
}
}
// First, determine if we have a type that has the highest quality factor that
// also matches the preferred type (if there is one):
String[][] match = new String[1][3];
if (preferredContentType.length != 0 && preferredContentType[0][0] != null) {
BigDecimal highestQual = BigDecimal.valueOf(highestQFactor);
for (int i = 0, len = resultList.size(); i < len; i++) {
String[] result = resultList.get(i);
if (BigDecimal.valueOf(Double.parseDouble(result[0])).compareTo(highestQual) == 0 && result[1].equals(preferredContentType[0][1])
&& result[2].equals(preferredContentType[0][2])) {
match[0][0] = result[0];
match[0][1] = result[1];
match[0][2] = result[2];
return match;
}
}
}