/
Components.java
1908 lines (1658 loc) · 75.7 KB
/
Components.java
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 OmniFaces
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.omnifaces.util;
import static jakarta.faces.application.ResourceHandler.JSF_SCRIPT_LIBRARY_NAME;
import static jakarta.faces.application.ResourceHandler.JSF_SCRIPT_RESOURCE_NAME;
import static jakarta.faces.application.StateManager.IS_BUILDING_INITIAL_STATE;
import static jakarta.faces.component.UIComponent.getCompositeComponentParent;
import static jakarta.faces.component.behavior.ClientBehaviorContext.BEHAVIOR_EVENT_PARAM_NAME;
import static jakarta.faces.component.behavior.ClientBehaviorContext.BEHAVIOR_SOURCE_PARAM_NAME;
import static jakarta.faces.component.search.SearchExpressionContext.createSearchExpressionContext;
import static jakarta.faces.component.search.SearchExpressionHint.IGNORE_NO_RESULT;
import static jakarta.faces.component.search.SearchExpressionHint.RESOLVE_SINGLE_COMPONENT;
import static jakarta.faces.component.visit.VisitContext.createVisitContext;
import static jakarta.faces.component.visit.VisitHint.SKIP_ITERATION;
import static jakarta.faces.component.visit.VisitResult.ACCEPT;
import static jakarta.faces.event.PhaseId.RENDER_RESPONSE;
import static java.lang.Boolean.TRUE;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;
import static java.util.logging.Level.FINEST;
import static java.util.regex.Pattern.quote;
import static org.omnifaces.resourcehandler.DefaultResourceHandler.FACES_SCRIPT_RESOURCE_NAME;
import static org.omnifaces.util.Ajax.load;
import static org.omnifaces.util.Ajax.oncomplete;
import static org.omnifaces.util.Events.subscribeToRequestBeforePhase;
import static org.omnifaces.util.Faces.getApplicationAttribute;
import static org.omnifaces.util.Faces.getContext;
import static org.omnifaces.util.Faces.getELContext;
import static org.omnifaces.util.Faces.getFaceletContext;
import static org.omnifaces.util.Faces.getRequestParameter;
import static org.omnifaces.util.Faces.getViewRoot;
import static org.omnifaces.util.Faces.isDevelopment;
import static org.omnifaces.util.Faces.setContext;
import static org.omnifaces.util.Faces.validationFailed;
import static org.omnifaces.util.FacesLocal.createConverter;
import static org.omnifaces.util.FacesLocal.getRenderKit;
import static org.omnifaces.util.FacesLocal.getRequestQueryStringMap;
import static org.omnifaces.util.FacesLocal.getViewParameterMap;
import static org.omnifaces.util.FacesLocal.isAjaxRequestWithPartialRendering;
import static org.omnifaces.util.FacesLocal.normalizeViewId;
import static org.omnifaces.util.Hacks.isFacesScriptResourceAvailable;
import static org.omnifaces.util.Messages.addError;
import static org.omnifaces.util.Reflection.accessField;
import static org.omnifaces.util.Renderers.RENDERER_TYPE_JS;
import static org.omnifaces.util.Utils.coalesce;
import static org.omnifaces.util.Utils.isEmpty;
import static org.omnifaces.util.Utils.isOneInstanceOf;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import jakarta.el.MethodExpression;
import jakarta.el.ValueExpression;
import jakarta.faces.application.Application;
import jakarta.faces.application.ResourceHandler;
import jakarta.faces.application.ViewHandler;
import jakarta.faces.component.ActionSource2;
import jakarta.faces.component.EditableValueHolder;
import jakarta.faces.component.NamingContainer;
import jakarta.faces.component.UICommand;
import jakarta.faces.component.UIComponent;
import jakarta.faces.component.UIComponentBase;
import jakarta.faces.component.UIForm;
import jakarta.faces.component.UIInput;
import jakarta.faces.component.UIMessage;
import jakarta.faces.component.UIMessages;
import jakarta.faces.component.UINamingContainer;
import jakarta.faces.component.UIOutput;
import jakarta.faces.component.UIParameter;
import jakarta.faces.component.UIViewRoot;
import jakarta.faces.component.ValueHolder;
import jakarta.faces.component.behavior.AjaxBehavior;
import jakarta.faces.component.behavior.BehaviorBase;
import jakarta.faces.component.behavior.ClientBehavior;
import jakarta.faces.component.behavior.ClientBehaviorHolder;
import jakarta.faces.component.html.HtmlBody;
import jakarta.faces.component.search.SearchExpressionContext;
import jakarta.faces.component.search.SearchExpressionHint;
import jakarta.faces.component.visit.VisitCallback;
import jakarta.faces.component.visit.VisitContext;
import jakarta.faces.component.visit.VisitHint;
import jakarta.faces.component.visit.VisitResult;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.FacesContextWrapper;
import jakarta.faces.context.ResponseWriter;
import jakarta.faces.convert.Converter;
import jakarta.faces.event.ActionEvent;
import jakarta.faces.event.ActionListener;
import jakarta.faces.event.AjaxBehaviorEvent;
import jakarta.faces.event.BehaviorListener;
import jakarta.faces.event.MethodExpressionActionListener;
import jakarta.faces.render.RenderKit;
import jakarta.faces.view.ViewDeclarationLanguage;
import jakarta.faces.view.facelets.FaceletContext;
import org.omnifaces.component.ParamHolder;
import org.omnifaces.component.SimpleParam;
import org.omnifaces.component.input.Form;
import org.omnifaces.config.OmniFaces;
import org.omnifaces.el.ScopedRunner;
/**
* <p>
* Collection of utility methods for the Faces API with respect to working with {@link UIComponent}. There are several
* traversal/lookup methods, there are several {@link UIForm} and {@link UIInput} related methods which makes it easier
* to deal with forms and inputs.
*
* <h2>Usage</h2>
* <p>
* Here are <strong>some</strong> examples:
* <pre>
* // Get closest parent of given type.
* UIForm form = Components.getClosestParent(someUIInputComponent, UIForm.class);
* </pre>
* <pre>
* // Get currently submitted form.
* UIForm form = Components.getCurrentForm();
* </pre>
* <pre>
* // Get currently invoked command, useful for logging actions in a phase listener.
* UICommand command = Components.getCurrentCommand();
* </pre>
* <pre>
* // Get the label of the given UIInput component as Faces uses for validation messages.
* String label = Components.getLabel(someUIInputComponent);
* </pre>
* <pre>
* // Inside decode() and/or encode() of some custom component, validate if it has no children.
* Components.validateHasNoChildren(this);
* </pre>
* <pre>
* // Programmatically include composite component.
* Components.includeCompositeComponent(someParentComponent, libraryName, tagName, id);
* </pre>
* <pre>
* // Programmatically create value and action expressions.
* UICommand command = new HtmlCommandButton();
* command.setId("foo");
* command.setValue(Components.createValueExpression("#{bundle['button.foo']}", String.class));
* command.addClientBehavior("action", Components.createAjaxBehavior("#{bean.ajaxListener}"));
* command.addActionListener(Components.createActionListenerMethodExpression("#{bean.actionListener}"));
* command.setActionExpression(Components.createVoidMethodExpression("#{bean.action}"));
* </pre>
* <pre>
* // Programmatically capture HTML output of a given view.
* String mailHtml = Components.encodeHtml(Components.buildView("/WEB-INF/mail-template.xhtml"));
* </pre>
* <pre>
* // Collecting all queued actions and action listeners as method expression strings in a logging phase listener.
* List<String> actions = Components.getActionExpressionsAndListeners(Components.getCurrentActionSource());
* </pre>
* <p>
* For a full list, check the <a href="#method.summary">method summary</a>.
*
* @author Bauke Scholtz
* @author Arjan Tijms
*/
public final class Components {
// Constants ------------------------------------------------------------------------------------------------------
private static final Logger logger = Logger.getLogger(Components.class.getName());
/** The name of the label attribute. */
public static final String LABEL_ATTRIBUTE = "label";
/** The name of the value attribute. */
public static final String VALUE_ATTRIBUTE = "value";
private static final String ERROR_MISSING_PARENT =
"Component '%s' must have a parent of type '%s', but it cannot be found.";
private static final String ERROR_MISSING_DIRECT_PARENT =
"Component '%s' must have a direct parent of type '%s', but it cannot be found.";
private static final String ERROR_MISSING_CHILD =
"Component '%s' must have at least one child of type '%s', but it cannot be found.";
private static final String ERROR_ILLEGAL_PARENT =
"Component '%s' may not have a parent of type '%s'.";
private static final String ERROR_ILLEGAL_CHILDREN =
"Component '%s' may only have children of type '%s'. Encountered children of types '%s'.";
private static final String ERROR_CHILDREN_DISALLOWED =
"Component '%s' may not have any children. Encountered children of types '%s'.";
private static final String ERROR_ILLEGAL_UIINPUT =
"Relative client ID '%s' must represent an UIInput component, but encountered '%s'.";
private static final Set<SearchExpressionHint> RESOLVE_LABEL_FOR = EnumSet.of(RESOLVE_SINGLE_COMPONENT, IGNORE_NO_RESULT);
// Constructors ---------------------------------------------------------------------------------------------------
private Components() {
// Hide constructor.
}
// General --------------------------------------------------------------------------------------------------------
/**
* Returns the current UI component from the EL context.
* @param <C> The expected component type.
* @return The current UI component from the EL context.
* @throws ClassCastException When <code>C</code> is of wrong type.
* @see UIComponent#getCurrentComponent(FacesContext)
*/
@SuppressWarnings("unchecked")
public static <C extends UIComponent> C getCurrentComponent() {
return (C) UIComponent.getCurrentComponent(getContext());
}
/**
* Returns the attribute of the given component on the given name.
* @param <T> The expected return type.
* @param component The component to return the attribute of the given name for.
* @param name The name of the attribute of the given component to be returned.
* @return The attribute of the given component on the given name.
* @throws ClassCastException When <code>T</code> is of wrong type.
* @since 1.5
*/
@SuppressWarnings("unchecked")
public static <T> T getAttribute(UIComponent component, String name) {
return (T) component.getAttributes().get(name);
}
/**
* Returns whether the given UI component and all of its parents is rendered. This thus not only checks the
* component's own <code>rendered</code> attribute, but also of all of its parents.
* @param component The component to be checked.
* @return <code>true</code> if the given UI component and all of its parents is rendered.
* @since 1.8
*/
public static boolean isRendered(UIComponent component) {
for (UIComponent current = component; current.getParent() != null; current = current.getParent()) {
if (!current.isRendered()) {
return false;
}
}
return true;
}
// Traversal ------------------------------------------------------------------------------------------------------
/**
* Returns the UI component matching the given client ID search expression.
* @param <C> The expected component type.
* @param clientId The client ID search expression.
* @return The UI component matching the given client ID search expression.
* @throws ClassCastException When <code>C</code> is of wrong type.
* @see UIComponent#findComponent(String)
*/
@SuppressWarnings("unchecked")
public static <C extends UIComponent> C findComponent(String clientId) {
return (C) getViewRoot().findComponent(clientId);
}
/**
* Returns the UI component matching the given client ID search expression relative to the point
* in the component tree of the given component. For this search both parents and children are
* consulted, increasingly moving further away from the given component. Parents are consulted
* first, then children.
*
* @param <C> The expected component type.
* @param component the component from which the relative search is started.
* @param clientId The client ID search expression.
* @return The UI component matching the given client ID search expression.
* @throws ClassCastException When <code>C</code> is of wrong type.
* @see UIComponent#findComponent(String)
*/
@SuppressWarnings("unchecked")
public static <C extends UIComponent> C findComponentRelatively(UIComponent component, String clientId) {
if (isEmpty(clientId)) {
return null;
}
// Search first in the naming container parents of the given component
UIComponent result = findComponentInParents(component, clientId);
if (result == null) {
// If not in the parents, search from the root
result = findComponentInChildren(getViewRoot(), clientId);
}
return (C) result;
}
/**
* Returns the UI component matching the given client ID search expression relative to the point
* in the component tree of the given component, searching only in its parents.
*
* @param <C> The expected component type.
* @param component the component from which the relative search is started.
* @param clientId The client ID search expression.
* @return The UI component matching the given client ID search expression.
* @throws ClassCastException When <code>C</code> is of wrong type.
* @see UIComponent#findComponent(String)
*/
@SuppressWarnings("unchecked")
public static <C extends UIComponent> C findComponentInParents(UIComponent component, String clientId) {
if (isEmpty(clientId)) {
return null;
}
for (UIComponent parent = component; parent != null; parent = parent.getParent()) {
if (parent instanceof NamingContainer || parent instanceof UIViewRoot) {
UIComponent result = findComponentIgnoringIAE(parent, clientId);
if (result != null) {
return (C) result;
}
}
}
return null;
}
/**
* Returns the UI component matching the given client ID search expression relative to the point
* in the component tree of the given component, searching only in its children.
*
* @param <C> The expected component type.
* @param component the component from which the relative search is started.
* @param clientId The client ID search expression.
* @return The UI component matching the given client ID search expression.
* @throws ClassCastException When <code>C</code> is of wrong type.
* @see UIComponent#findComponent(String)
*/
@SuppressWarnings("unchecked")
public static <C extends UIComponent> C findComponentInChildren(UIComponent component, String clientId) {
if (isEmpty(clientId)) {
return null;
}
for (UIComponent child : component.getChildren()) {
UIComponent result = null;
if (child instanceof NamingContainer) {
result = findComponentIgnoringIAE(child, clientId);
}
if (result == null) {
result = findComponentInChildren(child, clientId);
}
if (result != null) {
return (C) result;
}
}
return null;
}
/**
* Returns a list of UI components matching the given type in children of the given component.
* @param <C> The generic component type.
* @param component The component to search in its children for UI components matching the given type.
* @param type The type of the UI components to be searched in children of the given component.
* @return A list of UI components matching the given type in children of the given component.
*/
public static <C extends UIComponent> List<C> findComponentsInChildren(UIComponent component, Class<C> type) {
List<C> components = new ArrayList<>();
findComponentsInChildren(component, type, components);
return components;
}
/**
* Helper method for {@link #findComponentsInChildren(UIComponent, Class)} utilizing tail recursion.
*/
@SuppressWarnings("unchecked")
private static <C extends UIComponent> void findComponentsInChildren(UIComponent component, Class<C> type, List<C> matches) {
for (UIComponent child : component.getChildren()) {
if (type.isInstance(child)) {
matches.add((C) child);
}
findComponentsInChildren(child, type, matches);
}
}
/**
* Returns a list of UI components matching the given type in children of the currently submitted form.
* The currently submitted form is obtained by {@link #getCurrentForm()}.
* @param <C> The generic component type.
* @param type The type of the UI components to be searched in children of the currently submitted form.
* @return A list of UI components matching the given type in children of the currently submitted form.
* @since 3.1
*/
public static <C extends UIComponent> List<C> findComponentsInCurrentForm(Class<C> type) {
UIForm currentForm = getCurrentForm();
return currentForm != null ? findComponentsInChildren(currentForm, type) : emptyList();
}
/**
* Returns from the given component the closest parent of the given parent type, or <code>null</code> if none
* is found.
* @param <C> The generic component type.
* @param component The component to return the closest parent of the given parent type for.
* @param parentType The parent type.
* @return From the given component the closest parent of the given parent type, or <code>null</code> if none
* is found.
*/
public static <C extends UIComponent> C getClosestParent(UIComponent component, Class<C> parentType) {
UIComponent parent = component.getParent();
while (parent != null && !parentType.isInstance(parent)) {
parent = parent.getParent();
}
return parentType.cast(parent);
}
/**
* Finds from the given component the closest parent of the given parent type.
* @param <C> The generic component type.
* @param component The component to find the closest parent of the given parent type for.
* @param parentType The parent type.
* @return From the given component the closest parent of the given parent type.
* @since 3.11
*/
public static <C extends UIComponent> Optional<C> findClosestParent(UIComponent component, Class<C> parentType) {
return Optional.ofNullable(getClosestParent(component, parentType));
}
// Iteration / Visiting -------------------------------------------------------------------------------------------
/**
* Invokes an operation on every component in the component tree.
* <p>
* This is a simplified version of regular component visiting that uses the builder pattern to provide the various
* optional parameters. Includes supports for only visiting components of a certain class type and two
* simplified functional interfaces / lambdas.
* <p>
* See {@link UIComponent#visitTree(VisitContext, VisitCallback)}
*
* @return A new instance of {@link ForEach}.
* @since 2.0
*/
public static ForEach forEachComponent() {
return new ForEach();
}
/**
* Invokes an operation on every component in the component tree.
* <p>
* This is a simplified version of regular component visiting that uses the builder pattern to provide the various
* optional parameters. Includes supports for only visiting components of a certain class type and two
* simplified functional interfaces / lambdas.
* <p>
* See {@link UIComponent#visitTree(VisitContext, VisitCallback)}
*
* @param facesContext the faces context used for tree visiting
* @return A new instance of {@link ForEach}, using the given faces context.
* @since 2.0
*/
public static ForEach forEachComponent(FacesContext facesContext) {
return new ForEach(facesContext);
}
/**
* Builder class used to collect a number of query parameters for a visit (for each) of components in the Faces
* component tree. The chain of collecting parameters is terminated by calling one of the invoke methods.
*
* @since 2.0
* @author Arjan Tijms
*
*/
public static class ForEach {
private FacesContext facesContext;
private UIComponent root;
private Collection<String> ids;
private Set<VisitHint> hints;
private Class<?>[] types;
public ForEach() {
facesContext = Faces.getContext();
}
public ForEach(FacesContext facesContext) {
this.facesContext = facesContext;
}
/**
* The root component where tree visiting starts
*
* @param root the root component where tree visiting starts
* @return the intermediate builder object to continue the builder chain
*/
public ForEach fromRoot(UIComponent root) {
this.root = root;
return this;
}
/**
* The IDs of the components that are visited
*
* @param ids the IDs of the components that are visited
* @return the intermediate builder object to continue the builder chain
*/
public ForEach havingIds(Collection<String> ids) {
this.ids = ids;
return this;
}
/**
* The IDs of the components that are to be visited
*
* @param ids the IDs of the components that are to be visited
* @return the intermediate builder object to continue the builder chain
*/
public ForEach havingIds(String... ids) {
this.ids = asList(ids);
return this;
}
/**
* The VisitHints that are used for the visit.
*
* @param hints the VisitHints that are used for the visit.
* @return the intermediate builder object to continue the builder chain
*/
public ForEach withHints(Set<VisitHint> hints) {
this.hints = hints;
return this;
}
/**
* The VisitHints that are used for the visit.
*
* @param hints the VisitHints that are used for the visit.
* @return the intermediate builder object to continue the builder chain
*/
public ForEach withHints(VisitHint... hints) {
if (hints.length > 0) {
EnumSet<VisitHint> hintsSet = EnumSet.noneOf(hints[0].getDeclaringClass());
Collections.addAll(hintsSet, hints);
this.hints = hintsSet;
}
return this;
}
/**
* The types of the components that are to be visited
*
* @param types the types of the components that are to be visited
* @return the intermediate builder object to continue the builder chain
*/
@SafeVarargs
public final ForEach ofTypes(Class<?>... types) {
this.types = types;
return this;
}
/**
* Invokes the given operation on the components as specified by the
* query parameters set via this builder.
*
* @param <C> The expected component type.
* @param operation the operation to invoke on each component
* @throws ClassCastException When <code>C</code> is of wrong type.
*/
@SuppressWarnings("unchecked")
public <C extends UIComponent> void invoke(Consumer<C> operation) {
invoke((context, target) -> {
operation.accept((C) target);
return ACCEPT;
});
}
/**
* Invokes the given operation on the components as specified by the
* query parameters set via this builder.
*
* @param operation the operation to invoke on each component
*/
public void invoke(VisitCallback operation) {
VisitContext visitContext = createVisitContext(getFacesContext(), getIds(), getHints());
VisitCallback visitCallback = (types == null) ? operation : new TypesVisitCallback(types, operation);
if (getFacesContext().getViewRoot().equals(getRoot())) {
getRoot().visitTree(visitContext, visitCallback);
}
else {
forEachComponent().havingIds(getRoot().getClientId()).invoke(viewRoot -> viewRoot.visitTree(visitContext, visitCallback));
}
}
protected FacesContext getFacesContext() {
return facesContext;
}
protected UIComponent getRoot() {
return root != null ? root : getFacesContext().getViewRoot();
}
protected Collection<String> getIds() {
return ids;
}
protected Set<VisitHint> getHints() {
return hints;
}
private static class TypesVisitCallback implements VisitCallback {
private Class<?>[] types;
private VisitCallback next;
public TypesVisitCallback(Class<?>[] types, VisitCallback next) {
this.types = types;
this.next = next;
}
@Override
public VisitResult visit(VisitContext context, UIComponent target) {
if (isOneInstanceOf(target.getClass(), types)) {
return next.visit(context, target);
}
return ACCEPT;
}
}
}
// Manipulation ---------------------------------------------------------------------------------------------------
/**
* Include the Facelet file at the given (relative) path as child of the given UI component parent. This has the
* same effect as using <code><ui:include></code>. The path is relative to the current view ID and absolute
* to the webcontent root.
* @param parent The parent component to include the Facelet file in.
* @param path The (relative) path to the Facelet file.
* @throws IOException Whenever given path cannot be read.
* @see FaceletContext#includeFacelet(UIComponent, String)
* @since 1.5
*/
public static void includeFacelet(UIComponent parent, String path) throws IOException {
getFaceletContext().includeFacelet(parent, path);
}
/**
* Create and include the composite component of the given library and resource name as child of the given UI
* component parent and return the created composite component.
* This has the same effect as using <code>xmlns:my="http://xmlns.jcp.org/jsf/composite/libraryName</code> and
* <code><my:tagName></code>. The given component ID must be unique relative to the current naming
* container parent and is mandatory for functioning of input components inside the composite, if any.
* @param parent The parent component to include the composite component in.
* @param libraryName The library name of the composite component (path after "http://xmlns.jcp.org/jsf/composite/").
* @param tagName The tag name of the composite component.
* @param id The component ID of the composite component.
* @return The created composite component, which can if necessary be used to set more custom attributes on it.
* @since 1.5
*/
public static UIComponent includeCompositeComponent(UIComponent parent, String libraryName, String tagName, String id) {
return includeCompositeComponent(parent, libraryName, tagName, id, null);
}
/**
* Create and include the composite component of the given library and resource name as child of the given UI
* component parent, set the given attributes on it and return the created composite component.
* This has the same effect as using <code>xmlns:my="http://xmlns.jcp.org/jsf/composite/libraryName</code> and
* <code><my:tagName></code>. The given component ID must be unique relative to the current naming
* container parent and is mandatory for functioning of input components inside the composite, if any.
* <p>
* The attribute values must represent literal values or literal EL expressions, exactly like as you would declare
* in the view file. E.g.
* <pre>
* attributes.put("foo", "#{bean.foo}");
* attributes.put("bar", "true");
* attributes.put("baz", "#{bean.baz(" + someId + ")}");
* </pre>
* @param parent The parent component to include the composite component in.
* @param libraryName The library name of the composite component (path after "http://xmlns.jcp.org/jsf/composite/").
* @param tagName The tag name of the composite component.
* @param id The component ID of the composite component.
* @param attributes The attributes to be set on the composite component.
* @return The created composite component, which can if necessary be used to set more custom attributes on it.
* @since 2.2
*/
public static UIComponent includeCompositeComponent(UIComponent parent, String libraryName, String tagName, String id, Map<String, String> attributes) {
String taglibURI = "http://xmlns.jcp.org/jsf/composite/" + libraryName;
Map<String, Object> attrs = (attributes == null) ? null : new HashMap<>(attributes);
FacesContext context = FacesContext.getCurrentInstance();
UIComponent composite = context.getApplication().getViewHandler()
.getViewDeclarationLanguage(context, context.getViewRoot().getViewId())
.createComponent(context, taglibURI, tagName, attrs);
composite.setId(id);
parent.getChildren().add(composite);
return composite;
}
/**
* Add given JavaScript code to the current view which is to be executed as an inline script when the rendering is
* completed. When the current request is {@link Faces#isAjaxRequestWithPartialRendering()}, then it will delegate
* to {@link Ajax#oncomplete(String...)}, else it will add given JavaScript code as inline script to end of body.
* @param script JavaScript code which is to be executed as an inline script.
* @since 3.6
*/
public static void addScript(String script) {
FacesContext context = FacesContext.getCurrentInstance();
if (isAjaxRequestWithPartialRendering(context)) {
oncomplete(script);
}
else if (context.getCurrentPhaseId() != RENDER_RESPONSE) {
subscribeToRequestBeforePhase(RENDER_RESPONSE, () -> addScriptToBody(script)); // Just to avoid it misses when view rebuilds in the meanwhile.
}
else {
addScriptToBody(script);
}
}
/**
* Add given JavaScript resource to the current view. This will first check if the resource isn't already rendered
* as per {@link ResourceHandler#isResourceRendered(FacesContext, String, String)}. If not, then continue as below:
* <ul>
* <li>When the current request is a {@link Faces#isAjaxRequestWithPartialRendering()}, then it will delegate to
* {@link Ajax#load(String, String)}.</li>
* <li>Else when the <code><h:head></code> has not yet been rendered, then add given JavaScript resource to
* head.</li>
* <li>Else add given JavaScript resource to end of the <code><h:body></code>.</li>
* </ul>
* @param libraryName Library name of the JavaScript resource.
* @param resourceName Resource name of the JavaScript resource.
* @since 3.6
*/
public static void addScriptResource(String libraryName, String resourceName) {
FacesContext context = FacesContext.getCurrentInstance();
if (!context.getApplication().getResourceHandler().isResourceRendered(context, resourceName, libraryName)) {
if (isAjaxRequestWithPartialRendering(context)) {
load(libraryName, resourceName);
}
else if (context.getCurrentPhaseId() != RENDER_RESPONSE) {
addScriptResourceToHead(libraryName, resourceName);
subscribeToRequestBeforePhase(RENDER_RESPONSE, () -> addScriptResourceToBody(libraryName, resourceName)); // Fallback in case view rebuilds in the meanwhile. It will re-check if already added.
}
else if (TRUE.equals(context.getAttributes().get(IS_BUILDING_INITIAL_STATE))) {
addScriptResourceToHead(libraryName, resourceName);
}
else {
addScriptResourceToBody(libraryName, resourceName);
}
}
}
/**
* Add the Faces JavaScript resource to current view. If Faces 4.0+ is present, then it will add the
* <code>jakarta.faces:faces.js</code> resource, else it will add the <code>jakarta.faces:jsf.js</code> resource.
* @since 4.0
*/
public static void addFacesScriptResource() {
addScriptResource(JSF_SCRIPT_LIBRARY_NAME, isFacesScriptResourceAvailable() ? FACES_SCRIPT_RESOURCE_NAME : JSF_SCRIPT_RESOURCE_NAME);
}
private static UIOutput createScriptResource() {
UIOutput outputScript = new UIOutput();
outputScript.setRendererType(RENDERER_TYPE_JS);
return outputScript;
}
private static UIComponent addScriptResourceToTarget(String libraryName, String resourceName, String target) {
FacesContext context = FacesContext.getCurrentInstance();
String id = (libraryName != null ? (libraryName.replaceAll("\\W+", "_") + "_") : "") + resourceName.replaceAll("\\W+", "_");
for (UIComponent existingResource : context.getViewRoot().getComponentResources(context)) {
if (id.equals(existingResource.getId())) {
return existingResource;
}
}
UIOutput outputScript = createScriptResource();
outputScript.setId(id);
if (libraryName != null) {
outputScript.getAttributes().put("library", libraryName);
}
outputScript.getAttributes().put("name", resourceName);
return addComponentResource(outputScript, target);
}
private static void addScriptResourceToHead(String libraryName, String resourceName) {
addScriptResourceToTarget(libraryName, resourceName, "head");
}
private static void addScriptResourceToBody(String libraryName, String resourceName) {
addScriptResourceToTarget(libraryName, resourceName, "body");
}
private static UIComponent addComponentResource(UIComponent resource, String target) {
FacesContext context = FacesContext.getCurrentInstance();
if (resource.getId() == null) {
Hacks.setComponentResourceUniqueId(context, resource);
}
context.getViewRoot().addComponentResource(context, resource, target);
return resource;
}
private static void addScriptToBody(String script) {
UIOutput outputScript = createScriptResource();
UIOutput content = new UIOutput();
content.setValue(script);
outputScript.getChildren().add(content);
addComponentResource(outputScript, "body");
}
// Building / rendering -------------------------------------------------------------------------------------------
/**
* Creates and builds a local view for the given view ID independently from the current view.
* @param viewId The ID of the view which needs to be created and built.
* @return A fully populated component tree of the given view ID.
* @throws IOException Whenever something fails at I/O level. This can happen when the given view ID is unavailable or malformed.
* @since 2.2
* @see ViewHandler#createView(FacesContext, String)
* @see ViewDeclarationLanguage#buildView(FacesContext, UIViewRoot)
*/
public static UIViewRoot buildView(String viewId) throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
String normalizedViewId = normalizeViewId(context, viewId);
ViewHandler viewHandler = context.getApplication().getViewHandler();
UIViewRoot view = viewHandler.createView(context, normalizedViewId);
FacesContext temporaryContext = new TemporaryViewFacesContext(context, view);
try {
setContext(temporaryContext);
viewHandler.getViewDeclarationLanguage(temporaryContext, normalizedViewId).buildView(temporaryContext, view);
}
finally {
setContext(context);
}
return view;
}
/**
* Encodes the given component locally as HTML, with UTF-8 character encoding, independently from the current view.
* The current implementation, however, uses the current faces context. The same managed beans as in the current
* faces context will be available as well, including request scoped ones. But, depending on the nature of the
* provided component, the state of the faces context may be affected because the attributes of the context,
* request, view, session and application scope could be (in)directly manipulated during the encode. This may or may
* not have the desired effect. If the given view does not have any component resources, Faces forms, dynamically
* added components, component event listeners, then it should mostly be safe.
* In other words, use this at most for "simple templates" only, e.g. a HTML based mail template, which usually
* already doesn't have a HTML head nor body.
* @param component The component to capture HTML output for.
* @return The encoded HTML output of the given component.
* @throws UncheckedIOException Whenever something fails at I/O level. This would be quite unexpected as it happens locally.
* @since 2.2
* @see UIComponent#encodeAll(FacesContext)
*/
public static String encodeHtml(UIComponent component) {
FacesContext context = FacesContext.getCurrentInstance();
ResponseWriter originalWriter = context.getResponseWriter();
StringWriter output = new StringWriter();
context.setResponseWriter(getRenderKit(context).createResponseWriter(output, "text/html", "UTF-8"));
try {
component.encodeAll(context);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
finally {
if (originalWriter != null) {
context.setResponseWriter(originalWriter);
}
}
return output.toString();
}
// Forms ----------------------------------------------------------------------------------------------------------
/**
* Returns the currently submitted UI form component, or <code>null</code> if there is none, which may happen when
* the current request is not a postback request at all, or when the view has been changed by for example a
* successful navigation. If the latter is the case, you'd better invoke this method before navigation.
* @return The currently submitted UI form component.
* @see UIForm#isSubmitted()
*/
public static UIForm getCurrentForm() {
FacesContext context = FacesContext.getCurrentInstance();
if (!context.isPostback()) {
return null;
}
UIViewRoot viewRoot = context.getViewRoot();
if (viewRoot == null) {
return null;
}
// The initial implementation has visited the tree for UIForm components which returns true on isSubmitted().
// But with testing it turns out to return false on ajax requests where the form is not included in execute!
// The current implementation just walks through the request parameter map instead.
for (String name : context.getExternalContext().getRequestParameterMap().keySet()) {
if (name.startsWith("jakarta.faces.")) {
continue; // Quick skip.
}
UIComponent component = findComponentIgnoringIAE(viewRoot, name);
if (component instanceof UIForm) {
return (UIForm) component;
}
else if (component != null) {
UIForm form = getClosestParent(component, UIForm.class);
if (form != null) {
return form;
}
}
}
return null;
}
/**
* Returns the currently invoked UI command component, or <code>null</code> if there is none, which may happen when
* the current request is not a postback request at all, or when the view has been changed by for example a
* successful navigation. If the latter is the case, you'd better invoke this method before navigation.
* @return The currently invoked UI command component.
* @since 1.6
*/
public static UICommand getCurrentCommand() {
UIComponent source = getCurrentActionSource();
return source instanceof UICommand ? (UICommand) source : null;
}
/**
* Returns the source of the currently invoked action, or <code>null</code> if there is none, which may happen when
* the current request is not a postback request at all, or when the view has been changed by for example a
* successful navigation. If the latter is the case, you'd better invoke this method before navigation.
* @param <C> The expected component type.
* @return The source of the currently invoked action.
* @since 2.4
*/
@SuppressWarnings("unchecked")
public static <C extends UIComponent> C getCurrentActionSource() {
FacesContext context = FacesContext.getCurrentInstance();
if (!context.isPostback()) {
return null;
}
return (C) getCurrentActionSource(context, context.getViewRoot());
}
/**
* Helper method for {@link #getCurrentActionSource()}.
*/
static UIComponent getCurrentActionSource(FacesContext context, UIComponent parent) {
if (parent == null) {
return null;
}
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
if (context.getPartialViewContext().isAjaxRequest()) {
String sourceClientId = params.get(BEHAVIOR_SOURCE_PARAM_NAME);
if (sourceClientId != null) {
UIComponent actionSource = findComponentIgnoringIAE(parent, sourceClientId);