-
Notifications
You must be signed in to change notification settings - Fork 107
/
MenuRenderer.java
907 lines (731 loc) · 34.6 KB
/
MenuRenderer.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
/*
* 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
*/
// MenuRenderer.java
package com.sun.faces.renderkit.html_basic;
import static com.sun.faces.RIConstants.NO_VALUE;
import static com.sun.faces.renderkit.RenderKitUtils.getSelectItems;
import static com.sun.faces.renderkit.RenderKitUtils.renderOnchange;
import static com.sun.faces.renderkit.RenderKitUtils.renderPassThruAttributes;
import static com.sun.faces.renderkit.RenderKitUtils.renderXHTMLStyleBooleanAttributes;
import static com.sun.faces.util.MessageUtils.CONVERSION_ERROR_MESSAGE_ID;
import static com.sun.faces.util.MessageUtils.getExceptionMessage;
import static com.sun.faces.util.ReflectionUtils.lookupMethod;
import static com.sun.faces.util.RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME;
import static com.sun.faces.util.Util.getConverterForClass;
import static com.sun.faces.util.Util.isAllNull;
import static java.lang.Integer.MIN_VALUE;
import static java.lang.reflect.Array.get;
import static java.lang.reflect.Array.getLength;
import static java.lang.reflect.Array.set;
import static java.lang.reflect.Modifier.isAbstract;
import static java.util.Arrays.stream;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.SEVERE;
import static java.util.stream.Collectors.joining;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import com.sun.faces.RIConstants;
import com.sun.faces.io.FastStringWriter;
import com.sun.faces.renderkit.Attribute;
import com.sun.faces.renderkit.AttributeManager;
import com.sun.faces.renderkit.RenderKitUtils;
import com.sun.faces.renderkit.SelectItemsIterator;
import com.sun.faces.util.RequestStateManager;
import com.sun.faces.util.Util;
import jakarta.el.ELException;
import jakarta.el.ExpressionFactory;
import jakarta.el.ValueExpression;
import jakarta.faces.FacesException;
import jakarta.faces.component.UIComponent;
import jakarta.faces.component.UISelectMany;
import jakarta.faces.component.UISelectOne;
import jakarta.faces.component.ValueHolder;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.ResponseWriter;
import jakarta.faces.convert.Converter;
import jakarta.faces.convert.ConverterException;
import jakarta.faces.model.SelectItem;
import jakarta.faces.model.SelectItemGroup;
/**
* <B>MenuRenderer</B> is a class that renders the current value of <code>UISelectOne</code> or <code>UISelectMany</code>
* component as a list of menu options.
*/
public class MenuRenderer extends HtmlBasicInputRenderer {
private static final Attribute[] ATTRIBUTES = AttributeManager.getAttributes(AttributeManager.Key.SELECTMANYMENU);
// ---------------------------------------------------------- Public Methods
public Object convertSelectManyValue(FacesContext context, UISelectMany uiSelectMany, String[] newValues) throws ConverterException {
// If we have no local value, try to get the valueExpression.
ValueExpression valueExpression = uiSelectMany.getValueExpression("value");
Object convertedValue = newValues; // default case, set local value
// If we have a ValueExpression
if (valueExpression != null) {
Class<?> modelType = valueExpression.getType(context.getELContext());
// Does the valueExpression resolve properly to something with a type?
if (modelType != null) {
convertedValue = convertSelectManyValuesForModel(context, uiSelectMany, modelType, newValues);
}
// If it could not be converted, as a fall back try the type of
// the valueExpression's current value covering some edge cases such
// as where the current value came from a Map.
if (convertedValue == null) {
Object value = valueExpression.getValue(context.getELContext());
if (value != null) {
convertedValue = convertSelectManyValuesForModel(context, uiSelectMany, value.getClass(), newValues);
}
}
if (convertedValue == null) {
Object[] params = { newValues == null ? "" : stream(newValues).collect(joining("")), valueExpression.getExpressionString() };
throw new ConverterException(getExceptionMessage(CONVERSION_ERROR_MESSAGE_ID, params));
}
} else {
// No ValueExpression, just use Object array.
convertedValue = convertSelectManyValuesForArray(context, uiSelectMany, Object.class, newValues);
}
// At this point, result is ready to be set as the value
if (logger.isLoggable(FINE)) {
logger.fine("SelectMany Component " + uiSelectMany.getId() + " convertedValues " + convertedValue);
}
return convertedValue;
}
public Object convertSelectOneValue(FacesContext context, UISelectOne uiSelectOne, String newValue) throws ConverterException {
if (isNoValueOrNull(newValue, uiSelectOne)) {
return null;
}
Object convertedValue = super.getConvertedValue(context, uiSelectOne, newValue);
if (logger.isLoggable(FINE)) {
logger.fine("SelectOne Component " + uiSelectOne.getId() + " convertedValue " + convertedValue);
}
return convertedValue;
}
@Override
public void decode(FacesContext context, UIComponent component) {
rendererParamsNotNull(context, component);
if (!shouldDecode(component)) {
return;
}
String clientId = decodeBehaviors(context, component);
if (clientId == null) {
clientId = component.getClientId(context);
}
// Currently we assume the model type to be of type string or
// convertible to string and localized by the application.
if (component instanceof UISelectMany) {
decodeUISelectMany(context, (UISelectMany) component, clientId);
} else {
decodeUISelectOne(context, component, clientId);
}
}
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
rendererParamsNotNull(context, component);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
rendererParamsNotNull(context, component);
if (!shouldEncode(component)) {
return;
}
renderSelect(context, component);
}
@Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
if (component instanceof UISelectMany) {
// Need to set the 'TARGET_COMPONENT_ATTRIBUTE_NAME' request attr so the
// coerce-value call in the faces-api UISelectMany.matchValue will work
// (need a better way to determine the currently processing UIComponent ...)
RequestStateManager.set(context, TARGET_COMPONENT_ATTRIBUTE_NAME, component);
return convertSelectManyValue(context, (UISelectMany) component, (String[]) submittedValue);
} else {
return convertSelectOneValue(context, (UISelectOne) component, (String) submittedValue);
}
}
// ------------------------------------------------------- Protected Methods
/*
* Converts the provided string array and places them into the correct provided model type.
*/
@SuppressWarnings("unchecked")
protected Object convertSelectManyValuesForModel(FacesContext context, UISelectMany uiSelectMany, Class<?> modelType, String[] newValues) {
if (modelType.isArray()) {
return convertSelectManyValuesForArray(context, uiSelectMany, modelType.getComponentType(), newValues);
}
if (Collection.class.isAssignableFrom(modelType)) {
return convertSelectManyValuesForCollection(context, uiSelectMany, (Class<? extends Collection<Object>>) modelType, newValues);
}
if (Object.class.equals(modelType)) {
if (uiSelectMany.getAttributes().get("collectionType") != null) {
return convertSelectManyValuesForCollection(context, uiSelectMany, null, newValues);
}
else {
return convertSelectManyValuesForArray(context, uiSelectMany, modelType, newValues);
}
}
throw new FacesException("Target model Type is no a Collection or Array");
}
protected Object convertSelectManyValuesForArray(FacesContext context, UISelectMany uiSelectMany, Class<?> elementType, String[] newValues)
throws ConverterException {
Object array;
Converter<?> converter;
int length = newValues != null ? newValues.length : 0;
// Optimization: If the elementType is String, we don't need conversion. Just
// return newValues.
if (elementType.equals(String.class)) {
return newValues;
}
try {
array = Array.newInstance(elementType, length);
} catch (Exception e) {
throw new ConverterException(e);
}
// Bail out now if we have no new values, returning our oh-so-useful zero-length
// array.
if (newValues == null) {
return array;
}
// Obtain a converter.
converter = uiSelectMany.getConverter();
if (converter == null) {
// Look for a by-type converter based on model value.
converter = getConverterForClass(elementType, context);
if (converter == null) {
// If that also fails, and the attached values are of Object type, we
// don't need conversion.
if (elementType.equals(Object.class)) {
return newValues;
}
Object[] params = { stream(newValues).collect(joining(" ")), "null Converter" };
throw new ConverterException(getExceptionMessage(CONVERSION_ERROR_MESSAGE_ID, params));
}
}
for (int i = 0; i < length; i++) {
Object converted = converter.getAsObject(context, uiSelectMany, newValues[i]);
set(array, i, converted);
if (!elementType.isPrimitive() && logger.isLoggable(FINE)) {
logger.fine("String value: " + newValues[i] + " converts to : " + converted);
}
}
return array;
}
protected Collection<Object> convertSelectManyValuesForCollection(FacesContext context, UISelectMany uiSelectMany,
Class<? extends Collection<Object>> collectionType, String[] newValues) {
Collection<Object> collection = null;
Converter<?> converter;
int length = null != newValues ? newValues.length : 0;
// See if the collectionType hint is available, if so, use that.
Object collectionTypeHint = uiSelectMany.getAttributes().get("collectionType");
if (collectionTypeHint != null) {
collection = createCollectionFromHint(collectionTypeHint);
} else {
// Try to get a new Collection to store the values based by trying to create a
// clone.
@SuppressWarnings("unchecked")
Collection<Object> currentValue = (Collection<Object>) uiSelectMany.getValue();
if (currentValue != null) {
collection = cloneValue(currentValue);
}
// No cloned instance so if the modelType happens to represent a concrete type
// (probably not the norm).
// Try to reflect a no-argument constructor and invoke if available.
if (collection == null) {
collection = createCollection(currentValue, collectionType);
}
// No suitable instance to work with, make our best guess based on the type.
if (collection == null) {
collection = bestGuess(collectionType, length);
}
}
// Bail out now if we have no new values, returning our oh-so-useful empty
// collection.
if (newValues == null) {
return collection;
}
// Obtain a converter.
converter = uiSelectMany.getConverter();
if (converter != null) {
// Convert the usual way.
for (String newValue : newValues) {
Object converted = converter.getAsObject(context, uiSelectMany, newValue);
if (logger.isLoggable(FINE)) {
logger.fine("String value: " + newValue + " converts to : " + converted);
}
collection.add(converted);
}
} else {
// First collect all available object items as string.
SelectItemsIterator<SelectItem> iterator = new SelectItemsIterator<>(context, uiSelectMany);
Map<String, Object> availableItems = new HashMap<>();
while (iterator.hasNext()) {
SelectItem item = iterator.next();
if (item instanceof SelectItemGroup) {
for (SelectItem groupItem : ((SelectItemGroup) item).getSelectItems()) {
String asString = getFormattedValue(context, uiSelectMany, groupItem.getValue());
availableItems.put(asString, groupItem.getValue());
}
} else {
String asString = getFormattedValue(context, uiSelectMany, item.getValue());
availableItems.put(asString, item.getValue());
}
}
// Then "convert" submitted value to object based on collected available
// object items.
for (String newValue : newValues) {
collection.add(availableItems.containsKey(newValue) ? availableItems.get(newValue) : newValue);
}
}
return collection;
}
protected boolean renderOption(FacesContext context, UIComponent component, UIComponent selectComponent, Converter<?> converter, SelectItem curItem,
Object currentSelections, Object[] submittedValues, OptionComponentInfo optionInfo) throws IOException {
Object valuesArray;
Object itemValue;
String valueString = getFormattedValue(context, component, curItem.getValue(), converter);
boolean containsValue;
if (submittedValues != null) {
containsValue = containsaValue(submittedValues);
if (containsValue) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
boolean isSelected = isSelected(context, component, itemValue, valuesArray, converter);
if (optionInfo.isHideNoSelection() && curItem.isNoSelectionOption() && currentSelections != null && !isSelected) {
return false;
}
ResponseWriter writer = context.getResponseWriter();
assert writer != null;
writer.writeText("\t", component, null);
writer.startElement("option", null != selectComponent ? selectComponent : component);
writer.writeAttribute("value", valueString, "value");
if (isSelected) {
writer.writeAttribute("selected", true, "selected");
}
// if the component is disabled, "disabled" attribute would be rendered
// on "select" tag, so don't render "disabled" on every option.
if (!optionInfo.isDisabled() && curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
if (curItem.isEscape()) {
String label = curItem.getLabel();
if (label == null) {
label = valueString;
}
writer.writeText(label, component, "label");
} else {
writer.write(curItem.getLabel());
}
writer.endElement("option");
writer.writeText("\n", component, null);
return true;
}
protected void writeDefaultSize(ResponseWriter writer, int itemCount) throws IOException {
// if size is not specified default to 1.
writer.writeAttribute("size", "1", "size");
}
protected boolean containsaValue(Object valueArray) {
if (valueArray != null) {
int len = getLength(valueArray);
for (int i = 0; i < len; i++) {
Object value = Array.get(valueArray, i);
if (value != null && !value.equals(NO_VALUE)) {
return true;
}
}
}
return false;
}
@SuppressWarnings("unchecked")
protected Object getCurrentSelectedValues(UIComponent component) {
if (component instanceof UISelectMany) {
UISelectMany select = (UISelectMany) component;
Object value = select.getValue();
if (value == null) {
return null;
}
if (value instanceof Collection) {
return ((Collection<Object>) value).toArray();
} else if (value.getClass().isArray()) {
if (getLength(value) == 0) {
return null;
}
} else if (!value.getClass().isArray()) {
logger.warning("The UISelectMany value should be an array or a collection type, the actual type is " + value.getClass().getName());
}
return value;
}
UISelectOne select = (UISelectOne) component;
Object val = select.getValue();
if (val != null) {
return new Object[] { val };
}
return null;
}
// To derive a selectOne type component from this, override
// these methods.
protected String getMultipleText(UIComponent component) {
if (component instanceof UISelectMany) {
return " multiple ";
}
return "";
}
protected Object[] getSubmittedSelectedValues(UIComponent component) {
if (component instanceof UISelectMany) {
UISelectMany select = (UISelectMany) component;
return (Object[]) select.getSubmittedValue();
}
UISelectOne select = (UISelectOne) component;
Object val = select.getSubmittedValue();
if (val != null) {
return new Object[] { val };
}
return null;
}
protected boolean isSelected(FacesContext context, UIComponent component, Object itemValue, Object valueArray, Converter<?> converter) {
if (isAllNull(itemValue, valueArray)) {
return true;
}
if (valueArray != null) {
if (!valueArray.getClass().isArray()) {
logger.warning("valueArray is not an array, the actual type is " + valueArray.getClass());
return valueArray.equals(itemValue);
}
int len = getLength(valueArray);
for (int i = 0; i < len; i++) {
Object value = get(valueArray, i);
if (isAllNull(itemValue, value)) {
return true;
}
if (value == null ^ itemValue == null) {
continue;
}
Object compareValue;
if (converter == null) {
compareValue = coerceToModelType(context, itemValue, value.getClass());
} else {
compareValue = itemValue;
if (compareValue instanceof String && !(value instanceof String)) {
// type mismatch between the time and the value we're
// comparing. Invoke the Converter.
compareValue = converter.getAsObject(context, component, (String) compareValue);
}
}
if (value.equals(compareValue)) {
return true;
}
}
}
return false;
}
protected int renderOptions(FacesContext context, UIComponent component, SelectItemsIterator<SelectItem> items) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Converter<?> converter = null;
if (component instanceof ValueHolder) {
converter = ((ValueHolder) component).getConverter();
}
int count = 0;
Object currentSelections = getCurrentSelectedValues(component);
Object[] submittedValues = getSubmittedSelectedValues(component);
OptionComponentInfo optionInfo = new OptionComponentInfo(component);
RequestStateManager.set(context, TARGET_COMPONENT_ATTRIBUTE_NAME, component);
while (items.hasNext()) {
SelectItem item = items.next();
UIComponent selectComponent = items.currentSelectComponent();
if (item instanceof SelectItemGroup) {
// render OPTGROUP
writer.startElement("optgroup", null != selectComponent ? selectComponent : component);
writer.writeAttribute("label", item.getLabel(), "label");
// if the component is disabled, "disabled" attribute would be rendered
// on "select" tag, so don't render "disabled" on every option.
if (!optionInfo.isDisabled() && item.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
count++;
// render options of this group.
SelectItem[] itemsArray = ((SelectItemGroup) item).getSelectItems();
for (SelectItem element : itemsArray) {
if (renderOption(context, component, selectComponent, converter, element, currentSelections, submittedValues, optionInfo)) {
count++;
}
}
writer.endElement("optgroup");
} else {
if (renderOption(context, component, selectComponent, converter, item, currentSelections, submittedValues, optionInfo)) {
count++;
}
}
}
return count;
}
// Render the "select" portion..
//
protected void renderSelect(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
if (logger.isLoggable(FINER)) {
logger.log(FINER, "Rendering 'select'");
}
writer.startElement("select", component);
writeIdAttributeIfNecessary(context, writer, component);
writer.writeAttribute("name", component.getClientId(context), "clientId");
// Render styleClass attribute if present.
String styleClass;
if ((styleClass = (String) component.getAttributes().get("styleClass")) != null) {
writer.writeAttribute("class", styleClass, "styleClass");
}
if (!getMultipleText(component).equals("")) {
writer.writeAttribute("multiple", true, "multiple");
}
// Determine how many option(s) we need to render, and update
// the component's "size" attribute accordingly; The "size"
// attribute will be rendered as one of the "pass thru" attributes
SelectItemsIterator<SelectItem> items = getSelectItems(context, component);
// Render the options to a buffer now so that we can determine
// the size
FastStringWriter bufferedWriter = new FastStringWriter(128);
context.setResponseWriter(writer.cloneWithWriter(bufferedWriter));
int count = renderOptions(context, component, items);
context.setResponseWriter(writer);
// If "size" is *not* set explicitly, we have to default it correctly
Integer size = (Integer) component.getAttributes().get("size");
if (size == null || size == MIN_VALUE) {
size = count;
}
writeDefaultSize(writer, size);
renderPassThruAttributes(context, writer, component, ATTRIBUTES, getNonOnChangeBehaviors(component));
renderXHTMLStyleBooleanAttributes(writer, component);
renderOnchange(context, component, false);
// Now, write the buffered option content
writer.write(bufferedWriter.toString());
writer.endElement("select");
}
protected Object coerceToModelType(FacesContext ctx, Object value, Class<?> itemValueType) {
Object newValue;
try {
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
newValue = ef.coerceToType(value, itemValueType);
} catch (ELException | IllegalArgumentException ele) {
// If coerceToType fails, per the docs it should throw
// an ELException, however, GF 9.0 and 9.0u1 will throw
// an IllegalArgumentException instead (see GF issue 1527).
newValue = value;
}
return newValue;
}
/**
* @param collection a Collection instance
*
* @return a new <code>Collection</code> instance or null if the instance cannot be created
*/
protected Collection<Object> createCollection(Collection<Object> collection, Class<? extends Collection<Object>> fallBackType) {
Class<?> lookupClass = fallBackType;
if (collection != null) {
lookupClass = collection.getClass();
if (lookupClass.getName().equals(Arrays.class.getName() + "$ArrayList")) {
lookupClass = ArrayList.class;
}
}
if (!lookupClass.isInterface() && !isAbstract(lookupClass.getModifiers())) {
try {
return (Collection<Object>) lookupClass.getDeclaredConstructor().newInstance();
} catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) {
if (logger.isLoggable(SEVERE)) {
logger.log(SEVERE, "Unable to create new Collection instance for type " + lookupClass.getName(), e);
}
}
}
return null;
}
/**
* <p>
* Utility method to invoke the the <code>clone</code> method on the provided value.
* </p>
*
* @param value the value to clone
* @return the result of invoking <code>clone()</code> or <code>null</code> if the value could not be cloned or does not
* implement the {@link Cloneable} interface
*/
protected Collection<Object> cloneValue(Object value) {
if (value instanceof Cloneable) {
// Even though Clonable marks an instance of a Class as being
// safe to call .clone(), .clone() by default is protected.
// The Collection classes that do implement Clonable do so at variable
// locations within the class hierarchy, so we're stuck having to
// use reflection.
Method cloneMethod = lookupMethod(value, "clone");
if (cloneMethod != null) {
try {
@SuppressWarnings("unchecked")
Collection<Object> clonedCollected = (Collection<Object>) cloneMethod.invoke(value);
clonedCollected.clear();
return clonedCollected;
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
if (logger.isLoggable(SEVERE)) {
logger.log(SEVERE, "Unable to clone collection type: {0}", value.getClass().getName());
logger.log(SEVERE, e.toString(), e);
}
}
} else {
// No public clone method
if (logger.isLoggable(FINE)) {
logger.log(FINE, "Type {0} implements Cloneable, but has no public clone method.", value.getClass().getName());
}
}
}
return null;
}
/**
* @param type the target model type
* @param initialSize the initial size of the <code>Collection</code>
* @return a <code>Collection</code> instance that best matches <code>type</code>
*/
protected Collection<Object> bestGuess(Class<? extends Collection<Object>> type, int initialSize) {
if (SortedSet.class.isAssignableFrom(type)) {
return new TreeSet<>();
}
if (Queue.class.isAssignableFrom(type)) {
return new LinkedList<>();
}
if (Set.class.isAssignableFrom(type)) {
return new HashSet<>(initialSize);
}
// This covers the where type is List or Collection
return new ArrayList<>(initialSize);
}
/**
* <p>
* Create a collection from the provided hint.
*
* @param collectionTypeHint the Collection type as either a String or Class
* @return a new Collection instance
*/
@SuppressWarnings("unchecked")
protected Collection<Object> createCollectionFromHint(Object collectionTypeHint) {
Class<? extends Collection<Object>> collectionType;
if (collectionTypeHint instanceof Class) {
collectionType = (Class<? extends Collection<Object>>) collectionTypeHint;
} else if (collectionTypeHint instanceof String) {
try {
collectionType = Util.loadClass((String) collectionTypeHint, this);
} catch (ClassNotFoundException cnfe) {
throw new FacesException(cnfe);
}
} else {
throw new FacesException("'collectionType' should resolve to type String or Class. Found: " + collectionTypeHint.getClass().getName());
}
Collection<Object> createdCollection = createCollection(null, collectionType);
if (createdCollection == null) {
throw new FacesException("Unable to create collection type " + collectionType);
}
return createdCollection;
}
protected static boolean isHideNoSelection(UIComponent component) {
Object result = component.getAttributes().get("hideNoSelectionOption");
return result != null ? (Boolean) result : false;
}
// ------------------------------------------------------- Private Methods
private void decodeUISelectMany(FacesContext context, UISelectMany component, String clientId) {
Map<String, String[]> requestParameterValuesMap = context.getExternalContext().getRequestParameterValuesMap();
if (requestParameterValuesMap.containsKey(clientId)) {
String newValues[] = requestParameterValuesMap.get(clientId);
if (newValues != null && newValues.length > 0) {
Set<String> disabledSelectItemValues = getDisabledSelectItemValues(context, component);
if (!disabledSelectItemValues.isEmpty()) {
List<String> newValuesList = new ArrayList<>(Arrays.asList(newValues));
if (newValuesList.removeAll(disabledSelectItemValues)) {
newValues = newValuesList.toArray(new String[newValuesList.size()]);
}
}
}
setSubmittedValue(component, newValues);
if (logger.isLoggable(FINE)) {
logger.fine("submitted values for UISelectMany component " + component.getId() + " after decoding " + Arrays.toString(newValues));
}
} else {
// Use the empty array, not null, to distinguish between an deselected UISelectMany and a disabled one
setSubmittedValue(component, new String[0]);
if (logger.isLoggable(FINE)) {
logger.fine("Set empty array for UISelectMany component " + component.getId() + " after decoding ");
}
}
}
private void decodeUISelectOne(FacesContext context, UIComponent component, String clientId) {
Map<String, String> requestParameterMap = context.getExternalContext().getRequestParameterMap();
if (requestParameterMap.containsKey(clientId)) {
String newValue = requestParameterMap.get(clientId);
if (newValue != null && !newValue.isEmpty()) {
Set<String> disabledSelectItemValues = getDisabledSelectItemValues(context, component);
if (disabledSelectItemValues.contains(newValue)) {
newValue = RIConstants.NO_VALUE;
}
}
setSubmittedValue(component, newValue);
if (logger.isLoggable(FINE)) {
logger.fine("submitted value for UISelectOne component " + component.getId() + " after decoding " + newValue);
}
} else {
// there is no value, but this is different from a null value.
setSubmittedValue(component, NO_VALUE);
}
}
private Set<String> getDisabledSelectItemValues(FacesContext context, UIComponent component) {
Set<String> disabledSelectItemValues = new HashSet<>(2);
RenderKitUtils.getSelectItems(context, component).forEachRemaining(selectItem -> {
if (selectItem.isDisabled()) {
disabledSelectItemValues.add(getFormattedValue(context, component, selectItem.getValue()));
}
});
return disabledSelectItemValues;
}
private boolean isNoValueOrNull(String newValue, UIComponent component) {
if (NO_VALUE.equals(newValue)) {
return true;
}
if (newValue == null) {
if (logger.isLoggable(FINE)) {
logger.fine("No conversion necessary for SelectOne Component " + component.getId() + " since the new value is null ");
}
return true;
}
return false;
}
}