-
Notifications
You must be signed in to change notification settings - Fork 107
/
Util.java
1702 lines (1479 loc) · 64.1 KB
/
Util.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 (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021 Contributors to Eclipse Foundation.
*
* 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
*/
// Util.java
package com.sun.faces.util;
import static com.sun.faces.RIConstants.FACELETS_ENCODING_KEY;
import static com.sun.faces.RIConstants.FACES_SERVLET_MAPPINGS;
import static com.sun.faces.RIConstants.FACES_SERVLET_REGISTRATION;
import static com.sun.faces.RIConstants.NO_VALUE;
import static com.sun.faces.util.MessageUtils.ILLEGAL_ATTEMPT_SETTING_APPLICATION_ARTIFACT_ID;
import static com.sun.faces.util.MessageUtils.NAMED_OBJECT_NOT_FOUND_ERROR_MESSAGE_ID;
import static com.sun.faces.util.MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID;
import static com.sun.faces.util.MessageUtils.NULL_VIEW_ID_ERROR_MESSAGE_ID;
import static com.sun.faces.util.MessageUtils.getExceptionMessageString;
import static jakarta.faces.application.ViewHandler.CHARACTER_ENCODING_KEY;
import static java.lang.Character.isDigit;
import static java.util.Collections.emptyList;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.FINEST;
import static java.util.logging.Level.SEVERE;
import java.beans.FeatureDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.PrivilegedAction;
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.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.validation.SchemaFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import com.sun.faces.RIConstants;
import com.sun.faces.application.ApplicationAssociate;
import com.sun.faces.config.WebConfiguration;
import com.sun.faces.config.manager.FacesSchema;
import com.sun.faces.facelets.component.UIRepeat;
import com.sun.faces.io.FastStringWriter;
import jakarta.el.ELResolver;
import jakarta.el.ValueExpression;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.faces.FacesException;
import jakarta.faces.application.Application;
import jakarta.faces.application.ProjectStage;
import jakarta.faces.application.StateManager;
import jakarta.faces.application.ViewHandler;
import jakarta.faces.component.Doctype;
import jakarta.faces.component.NamingContainer;
import jakarta.faces.component.UIComponent;
import jakarta.faces.component.UIData;
import jakarta.faces.component.UINamingContainer;
import jakarta.faces.component.UIViewRoot;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import jakarta.faces.convert.Converter;
import jakarta.faces.event.AbortProcessingException;
import jakarta.faces.render.ResponseStateManager;
import jakarta.faces.webapp.FacesServlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRegistration;
import jakarta.servlet.http.HttpServletMapping;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.MappingMatch;
/**
* <B>Util</B> is a class ...
*
* <B>Lifetime And Scope</B>
*
*/
public class Util {
// Log instance for this class
private static final Logger LOGGER = FacesLogger.APPLICATION.getLogger();
// README - make sure to add the message identifier constant
// (ex: Util.CONVERSION_ERROR_MESSAGE_ID) and the number of substitution
// parameters to test/com/sun/faces/util/TestUtil_messages (see comment there).
/**
* Flag that, when true, enables special behavior in Mojarra to enable unit testing.
*/
private static boolean unitTestModeEnabled = false;
/**
* RegEx patterns
*/
private static final String PATTERN_CACHE_KEY = RIConstants.FACES_PREFIX + "patternCache";
private static final String CLIENT_ID_NESTED_IN_ITERATOR_PATTERN = "CLIENT_ID_NESTED_IN_ITERATOR_PATTERN";
private static final String FACES_SERVLET_CLASS = FacesServlet.class.getName();
private Util() {
throw new IllegalStateException();
}
private static Map<String, Pattern> getPatternCache(Map<String, Object> appMap) {
@SuppressWarnings("unchecked")
Map<String, Pattern> result = (Map<String, Pattern>) appMap.get(PATTERN_CACHE_KEY);
if (result == null) {
result = Collections.synchronizedMap(new LRUMap<>(15));
appMap.put(PATTERN_CACHE_KEY, result);
}
return result;
}
private static Map<String, Pattern> getPatternCache(ServletContext sc) {
@SuppressWarnings("unchecked")
Map<String, Pattern> result = (Map<String, Pattern>) sc.getAttribute(PATTERN_CACHE_KEY);
if (result == null) {
result = Collections.synchronizedMap(new LRUMap<>(15));
sc.setAttribute(PATTERN_CACHE_KEY, result);
}
return result;
}
private static Collection<String> getFacesServletMappings(ServletContext servletContext) {
// check servlet context during initialization to avoid ConfigureListener to call the servlet registration
@SuppressWarnings("unchecked")
Collection<String> mappings = (Collection<String>) servletContext.getAttribute(FACES_SERVLET_MAPPINGS);
if (mappings != null) {
return mappings;
}
ServletRegistration facesRegistration = getExistingFacesServletRegistration(servletContext);
if (facesRegistration != null) {
return facesRegistration.getMappings();
}
return emptyList();
}
private static ServletRegistration getExistingFacesServletRegistration(ServletContext servletContext) {
Map<String, ? extends ServletRegistration> existing = servletContext.getServletRegistrations();
for (ServletRegistration registration : existing.values()) {
if (FACES_SERVLET_CLASS.equals(registration.getClassName())) {
return registration;
}
}
return null;
}
public static Optional<ServletRegistration> getFacesServletRegistration(FacesContext context) {
Object unKnownContext = context.getExternalContext().getContext();
if (unKnownContext instanceof ServletContext) {
return Optional.of((ServletRegistration) ((ServletContext) unKnownContext).getAttribute(FACES_SERVLET_REGISTRATION));
}
return Optional.empty();
}
/**
* <p>
* Convenience method for determining if the request associated with the specified <code>FacesContext</code> is a
* PortletRequest submitted by the JSR-301 bridge.
* </p>
*
* @param context the <code>FacesContext</code> associated with the request.
*/
public static boolean isPortletRequest(FacesContext context) {
return context.getExternalContext().getRequestMap().get("javax.portlet.faces.phase") != null;
}
public static String generateCreatedBy(FacesContext facesContext) {
String applicationContextPath = "unitTest";
try {
applicationContextPath = facesContext.getExternalContext().getApplicationContextPath();
} catch (Throwable e) {
// ignore
}
return applicationContextPath + " " + Thread.currentThread().toString() + " " + System.currentTimeMillis();
}
/**
* <p>
* Factory method for creating the various Faces listener instances that may be referenced by <code>type</code> or
* <code>binding</code>.
* </p>
* <p>
* If <code>binding</code> is not <code>null</code> and the evaluation result is not <code>null</code> return that
* instance. Otherwise try to instantiate an instances based on <code>type</code>.
* </p>
*
* @param type the <code>Listener</code> type
* @param binding a <code>ValueExpression</code> which resolves to a <code>Listener</code> instance
* @return a <code>Listener</code> instance based off the provided <code>type</code> and <code>binding</code>
*/
public static Object getListenerInstance(ValueExpression type, ValueExpression binding) {
FacesContext faces = FacesContext.getCurrentInstance();
Object instance = null;
if (faces == null) {
return null;
}
if (binding != null) {
instance = binding.getValue(faces.getELContext());
}
if (instance == null && type != null) {
try {
instance = ReflectionUtils.newInstance((String) type.getValue(faces.getELContext()));
} catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) {
throw new AbortProcessingException(e.getMessage(), e);
}
if (binding != null) {
binding.setValue(faces.getELContext(), instance);
}
}
return instance;
}
public static void setUnitTestModeEnabled(boolean enabled) {
unitTestModeEnabled = enabled;
}
public static boolean isUnitTestModeEnabled() {
return unitTestModeEnabled;
}
public static interface ThrowingBiConsumer<T, U> {
void accept(T t, U u) throws Exception;
}
private static <F> void setFeature(ThrowingBiConsumer<F, Boolean> setter, F feature, Boolean flag) {
try {
setter.accept(feature, flag);
} catch (Exception e) {
throw new IllegalArgumentException("The feature '" + feature + "' is not supported by your XML processor.", e);
}
}
private static <F> void setPossiblyUnsupportedFeature(ThrowingBiConsumer<F, Boolean> setter, F feature, Boolean flag) {
try {
setFeature(setter, feature, flag);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.FINE, e.getMessage(), e);
}
}
public static TransformerFactory createTransformerFactory() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
TransformerFactory factory;
try {
Thread.currentThread().setContextClassLoader(Util.class.getClassLoader());
factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, NO_VALUE);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, NO_VALUE);
setFeature(factory::setFeature, XMLConstants.FEATURE_SECURE_PROCESSING, true);
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
return factory;
}
public static SAXParserFactory createSAXParserFactory() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
SAXParserFactory factory;
try {
Thread.currentThread().setContextClassLoader(Util.class.getClassLoader());
factory = SAXParserFactory.newInstance();
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
return factory;
}
public static DocumentBuilderFactory createDocumentBuilderFactory() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
DocumentBuilderFactory factory;
try {
Thread.currentThread().setContextClassLoader(Util.class.getClassLoader());
factory = createLocalDocumentBuilderFactory();
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
return factory;
}
public static DocumentBuilderFactory createLocalDocumentBuilderFactory() {
DocumentBuilderFactory factory;
factory = DocumentBuilderFactory.newInstance();
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
setFeature(factory::setFeature, XMLConstants.FEATURE_SECURE_PROCESSING, true);
setPossiblyUnsupportedFeature(factory::setFeature, "http://xml.org/sax/features/external-general-entities", false);
setPossiblyUnsupportedFeature(factory::setFeature, "http://xml.org/sax/features/external-parameter-entities", false);
setPossiblyUnsupportedFeature(factory::setFeature, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
return factory;
}
public static SchemaFactory createSchemaFactory(String uri) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
SchemaFactory factory;
try {
Thread.currentThread().setContextClassLoader(Util.class.getClassLoader());
factory = SchemaFactory.newInstance(uri);
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
return factory;
}
public static Class loadClass(String name, Object fallbackClass) throws ClassNotFoundException {
ClassLoader loader = Util.getCurrentLoader(fallbackClass);
String[] primitiveNames = { "byte", "short", "int", "long", "float", "double", "boolean", "char" };
Class<?>[] primitiveClasses = { byte.class, short.class, int.class, long.class, float.class, double.class, boolean.class, char.class };
for (int i = 0; i < primitiveNames.length; i++) {
if (primitiveNames[i].equals(name)) {
return primitiveClasses[i];
}
}
return Class.forName(name, true, loader);
}
public static Class<?> loadClass2(String name, Object fallbackClass) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
loader = fallbackClass.getClass().getClassLoader();
}
return Class.forName(name, true, loader);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<?> clazz) {
try {
return (T) clazz.getDeclaredConstructor().newInstance();
} catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
public static ClassLoader getCurrentLoader(Object fallbackClass) {
ClassLoader loader = getContextClassLoader();
if (loader == null) {
loader = fallbackClass.getClass().getClassLoader();
}
return loader;
}
private static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged((PrivilegedAction) () -> Thread.currentThread().getContextClassLoader());
}
}
/**
* <p>
* Identify and return the class loader that is associated with the calling web application.
* </p>
*
* @throws FacesException if the web application class loader cannot be identified
*/
public static ClassLoader getContextClassLoader2() throws FacesException {
// J2EE 1.3 (and later) containers are required to make the
// web application class loader visible through the context
// class loader of the current thread.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
throw new FacesException("getContextClassLoader");
}
return classLoader;
}
public static String removeAllButLastSlashPathSegment(String input) {
// Trim the leading lastSlash, if any.
if (input.charAt(0) == '/') {
input = input.substring(1);
}
int len = input.length();
// Trim the trailing lastSlash, if any.
if (input.charAt(len - 1) == '/') {
input = input.substring(0, len - 1);
}
// Trim any path segments that remain, leaving only the
// last path segment.
int slash = input.lastIndexOf("/");
// Do we have a "/"?
if (-1 != slash) {
input = input.substring(slash + 1);
}
return input;
}
public static String removeAllButNextToLastSlashPathSegment(String input) {
// Trim the leading lastSlash, if any.
if (input.charAt(0) == '/') {
input = input.substring(1);
}
int len = input.length();
// Trim the trailing lastSlash, if any.
if (input.charAt(len - 1) == '/') {
input = input.substring(0, len - 1);
}
// Trim any path segments that remain, leaving only the
// last path segment.
int lastSlash = input.lastIndexOf("/");
// Do we have a "/"?
if (-1 != lastSlash) {
int startOrPreviousSlash = input.lastIndexOf("/", lastSlash - 1);
startOrPreviousSlash = -1 == startOrPreviousSlash ? 0 : startOrPreviousSlash;
input = input.substring(startOrPreviousSlash, lastSlash);
}
return input;
}
public static String removeLastPathSegment(String input) {
int slash = input.lastIndexOf("/");
// Do we have a "/"?
if (-1 != slash) {
input = input.substring(0, slash);
}
return input;
}
public static void notNegative(String varname, long number) {
if (number < 0) {
throw new IllegalArgumentException("\"" + varname + "\" is negative");
}
}
public static void notNull(String varname, Object var) {
if (var == null) {
throw new NullPointerException(getExceptionMessageString(NULL_PARAMETERS_ERROR_MESSAGE_ID, varname));
}
}
public static void notNullViewId(String viewId) {
if (viewId == null) {
throw new IllegalArgumentException(getExceptionMessageString(NULL_VIEW_ID_ERROR_MESSAGE_ID));
}
}
public static void notNullNamedObject(Object object, String objectId, String logMsg) {
if (object == null) {
Object[] params = { objectId };
if (LOGGER.isLoggable(SEVERE)) {
LOGGER.log(SEVERE, logMsg, params);
}
throw new FacesException(getExceptionMessageString(NAMED_OBJECT_NOT_FOUND_ERROR_MESSAGE_ID, params));
}
}
public static void canSetAppArtifact(ApplicationAssociate applicationAssociate, String artifactName) {
if (applicationAssociate.hasRequestBeenServiced()) {
throw new IllegalStateException(getExceptionMessageString(ILLEGAL_ATTEMPT_SETTING_APPLICATION_ARTIFACT_ID, artifactName));
}
}
public static void notNullAttribute(String attributeName, Object attribute) {
if (attribute == null) {
throw new FacesException("The \"" + attributeName + "\" attribute is required");
}
}
public static ValueExpression getValueExpressionNullSafe(UIComponent component, String name) {
ValueExpression valueExpression = component.getValueExpression(name);
notNullAttribute(name, valueExpression);
return valueExpression;
}
/**
* Returns true if the given string is null or is empty.
*
* @param string The string to be checked on emptiness.
* @return True if the given string is null or is empty.
*/
public static boolean isEmpty(String string) {
return string == null || string.isEmpty();
}
/**
* Returns <code>true</code> if the given array is null or is empty.
*
* @param array The array to be checked on emptiness.
* @return <code>true</code> if the given array is null or is empty.
*/
public static boolean isEmpty(Object[] array) {
return array == null || array.length == 0;
}
/**
* Returns <code>true</code> if the given collection is null or is empty.
*
* @param collection The collection to be checked on emptiness.
* @return <code>true</code> if the given collection is null or is empty.
*/
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
/**
* Returns <code>true</code> if the given value is null or is empty. Types of String, Collection, Map, Optional and
* Array are recognized. If none is recognized, then examine the emptiness of the toString() representation instead.
*
* @param value The value to be checked on emptiness.
* @return <code>true</code> if the given value is null or is empty.
*/
public static boolean isEmpty(Object value) {
if (value == null) {
return true;
} else if (value instanceof String) {
return ((String) value).isEmpty();
} else if (value instanceof Collection<?>) {
return ((Collection<?>) value).isEmpty();
} else if (value instanceof Map<?, ?>) {
return ((Map<?, ?>) value).isEmpty();
} else if (value instanceof Optional<?>) {
return !((Optional<?>) value).isPresent();
} else if (value.getClass().isArray()) {
return Array.getLength(value) == 0;
} else {
return value.toString() == null || value.toString().isEmpty();
}
}
/**
* Returns true if all values are empty, false if at least one value is not empty.
*
* @param values the values to be checked on emptiness
* @return True if all values are empty, false otherwise
*/
public static boolean isAllEmpty(Object... values) {
for (Object value : values) {
if (!isEmpty(value)) {
return false;
}
}
return true;
}
/**
* Returns <code>true</code> if at least one value is empty.
*
* @param values the values to be checked on emptiness
* @return <code>true</code> if any value is empty and <code>false</code> if no values are empty
*/
public static boolean isAnyEmpty(Object... values) {
for (Object value : values) {
if (isEmpty(value)) {
return true;
}
}
return false;
}
public static boolean isAllNull(Object... values) {
for (Object value : values) {
if (value != null) {
return false;
}
}
return true;
}
public static boolean isAnyNull(Object... values) {
for (Object value : values) {
if (value == null) {
return true;
}
}
return false;
}
/**
* Returns <code>true</code> if the given object equals one of the given objects.
*
* @param <T> The generic object type.
* @param object The object to be checked if it equals one of the given objects.
* @param objects The argument list of objects to be tested for equality.
* @return <code>true</code> if the given object equals one of the given objects.
*/
@SafeVarargs
public static <T> boolean isOneOf(T object, T... objects) {
for (Object other : objects) {
if (object == null ? other == null : object.equals(other)) {
return true;
}
}
return false;
}
/**
* Returns the first non-<code>null</code> object of the argument list, or <code>null</code> if there is no such
* element.
*
* @param <T> The generic object type.
* @param objects The argument list of objects to be tested for non-<code>null</code>.
* @return The first non-<code>null</code> object of the argument list, or <code>null</code> if there is no such
* element.
*/
@SafeVarargs
public static <T> T coalesce(T... objects) {
for (T object : objects) {
if (object != null) {
return object;
}
}
return null;
}
public static <T> List<T> reverse(List<T> list) {
int length = list.size();
List<T> result = new ArrayList<>(length);
for (int i = length - 1; i >= 0; i--) {
result.add(list.get(i));
}
return result;
}
/**
* Returns <code>true</code> if the given string starts with one of the given prefixes.
*
* @param string The object to be checked if it starts with one of the given prefixes.
* @param prefixes The argument list of prefixes to be checked
*
* @return <code>true</code> if the given string starts with one of the given prefixes.
*/
public static boolean startsWithOneOf(String string, String... prefixes) {
if (prefixes == null) {
return false;
}
for (String prefix : prefixes) {
if (string.startsWith(prefix)) {
return true;
}
}
return false;
}
/**
* @param context the <code>FacesContext</code> for the current request
* @return the Locale from the UIViewRoot, the the value of Locale.getDefault()
*/
public static Locale getLocaleFromContextOrSystem(FacesContext context) {
Locale result, temp = Locale.getDefault();
UIViewRoot root;
result = temp;
if (null != context && null != (root = context.getViewRoot()) && null == (result = root.getLocale())) {
result = temp;
}
return result;
}
public static Converter getConverterForClass(Class converterClass, FacesContext context) {
if (converterClass == null) {
return null;
}
try {
Application application = context.getApplication();
return application.createConverter(converterClass);
} catch (Exception e) {
return null;
}
}
public static Converter getConverterForIdentifer(String converterId, FacesContext context) {
if (converterId == null) {
return null;
}
try {
Application application = context.getApplication();
return application.createConverter(converterId);
} catch (Exception e) {
return null;
}
}
public static StateManager getStateManager(FacesContext context) throws FacesException {
return context.getApplication().getStateManager();
}
public static Class getTypeFromString(String type) throws ClassNotFoundException {
Class result;
switch (type) {
case "byte":
result = Byte.TYPE;
break;
case "short":
result = Short.TYPE;
break;
case "int":
result = Integer.TYPE;
break;
case "long":
result = Long.TYPE;
break;
case "float":
result = Float.TYPE;
break;
case "double":
result = Double.TYPE;
break;
case "boolean":
result = Boolean.TYPE;
break;
case "char":
result = Character.TYPE;
break;
case "void":
result = Void.TYPE;
break;
default:
if (type.indexOf('.') == -1) {
type = "java.lang." + type;
}
result = Util.loadClass(type, Void.TYPE);
break;
}
return result;
}
public static ViewHandler getViewHandler(FacesContext context) throws FacesException {
// Get Application instance
Application application = context.getApplication();
assert application != null;
// Get the ViewHandler
ViewHandler viewHandler = application.getViewHandler();
assert viewHandler != null;
return viewHandler;
}
public static boolean componentIsDisabled(UIComponent component) {
return Boolean.valueOf(String.valueOf(component.getAttributes().get("disabled")));
}
public static boolean componentIsDisabledOrReadonly(UIComponent component) {
return Boolean.valueOf(String.valueOf(component.getAttributes().get("disabled")))
|| Boolean.valueOf(String.valueOf(component.getAttributes().get("readonly")));
}
// W3C XML specification refers to IETF RFC 1766 for language code
// structure, therefore the value for the xml:lang attribute should
// be in the form of language or language-country or
// language-country-variant.
public static Locale getLocaleFromString(String localeStr) throws IllegalArgumentException {
// length must be at least 2.
if (null == localeStr || localeStr.length() < 2) {
throw new IllegalArgumentException("Illegal locale String: " + localeStr);
}
Locale result = null;
try {
Method method = Locale.class.getMethod("forLanguageTag", String.class);
if (method != null) {
result = (Locale) method.invoke(null, localeStr);
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException throwable) {
// if we are NOT running JavaSE 7 we end up here and we will
// default to the previous way of determining the Locale below.
}
if (result == null || result.getLanguage().equals("")) {
String lang = null;
String country = null;
String variant = null;
char[] seps = { '-', '_' };
int inputLength = localeStr.length();
int i = 0;
int j = 0;
// to have a language, the length must be >= 2
if (inputLength >= 2 && (i = indexOfSet(localeStr, seps, 0)) == -1) {
// we have only Language, no country or variant
if (2 != localeStr.length()) {
throw new IllegalArgumentException("Illegal locale String: " + localeStr);
}
lang = localeStr.toLowerCase();
}
// we have a separator, it must be either '-' or '_'
if (i != -1) {
lang = localeStr.substring(0, i);
// look for the country sep.
// to have a country, the length must be >= 5
if (inputLength >= 5 && (j = indexOfSet(localeStr, seps, i + 1)) == -1) {
// no further separators, length must be 5
if (inputLength != 5) {
throw new IllegalArgumentException("Illegal locale String: " + localeStr);
}
country = localeStr.substring(i + 1);
}
if (j != -1) {
country = localeStr.substring(i + 1, j);
// if we have enough separators for language, locale,
// and variant, the length must be >= 8.
if (inputLength >= 8) {
variant = localeStr.substring(j + 1);
} else {
throw new IllegalArgumentException("Illegal locale String: " + localeStr);
}
}
}
if (variant != null && country != null && lang != null) {
result = new Locale(lang, country, variant);
} else if (lang != null && country != null) {
result = new Locale(lang, country);
} else if (lang != null) {
result = new Locale(lang, "");
}
}
return result;
}
/**
* @param str local string
* @param set the substring
* @param fromIndex starting index
* @return starting at <code>fromIndex</code>, the index of the first occurrence of any substring from <code>set</code>
* in <code>toSearch</code>, or -1 if no such match is found
*/
public static int indexOfSet(String str, char[] set, int fromIndex) {
int result = -1;
for (int i = fromIndex, len = str.length(); i < len; i++) {
for (int j = 0, innerLen = set.length; j < innerLen; j++) {
if (str.charAt(i) == set[j]) {
result = i;
break;
}
}
if (-1 != result) {
break;
}
}
return result;
}
/**
* <p>
* Leverage the Throwable.getStackTrace() method to produce a String version of the stack trace, with a "\n" before each
* line.
* </p>
*
* @param e the Throwable to obtain the stacktrace from
*
* @return the String representation ofthe stack trace obtained by calling getStackTrace() on the passed in exception.
* If null is passed in, we return the empty String.
*/
public static String getStackTraceString(Throwable e) {
if (null == e) {
return "";
}
StackTraceElement[] stacks = e.getStackTrace();
StringBuffer sb = new StringBuffer();
for (StackTraceElement stack : stacks) {
sb.append(stack.toString()).append('\n');
}
return sb.toString();
}
/**
* <p>
* PRECONDITION: argument <code>response</code> is non-null and has a method called <code>getContentType</code> that
* takes no arguments and returns a String, with no side-effects.
* </p>
*
* <p>
* This method allows us to get the contentType in both the servlet and portlet cases, without introducing a
* compile-time dependency on the portlet api.
* </p>
*
* @param response the current response
* @return the content type of the response
*/
public static String getContentTypeFromResponse(Object response) {
String result = null;
if (null != response) {
try {
Method method = ReflectionUtils.lookupMethod(response.getClass(), "getContentType", RIConstants.EMPTY_CLASS_ARGS);
if (null != method) {
Object obj = method.invoke(response, RIConstants.EMPTY_METH_ARGS);
if (null != obj) {
result = obj.toString();
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new FacesException(e);
}
}
return result;
}
public static FeatureDescriptor getFeatureDescriptor(String name, String displayName, String desc, boolean expert, boolean hidden, boolean preferred,
Object type, Boolean designTime) {
FeatureDescriptor fd = new FeatureDescriptor();
fd.setName(name);
fd.setDisplayName(displayName);
fd.setShortDescription(desc);
fd.setExpert(expert);
fd.setHidden(hidden);
fd.setPreferred(preferred);
fd.setValue(ELResolver.TYPE, type);
fd.setValue(ELResolver.RESOLVABLE_AT_DESIGN_TIME, designTime);
return fd;
}
/**
* <p>
* A slightly more efficient version of <code>String.split()</code> which caches the <code>Pattern</code>s in an LRUMap
* instead of creating a new <code>Pattern</code> on each invocation.
* </p>
*