- java.lang.Object
-
- org.omnifaces.util.Utils
-
public final class Utils extends Object
Collection of general utility methods that do not fit in one of the more specific classes.
This class is not listed in showcase! Should I use it?
This class is indeed intented for internal usage only. We won't add methods here on user request. We only add methods here once we encounter non-DRY code in OmniFaces codebase. The methods may be renamed/changed without notice.
We don't stop you from using it if you found it in the Javadoc and you think you find it useful, but you have to accept the risk that the method signatures can be changed without notice. This utility class exists because OmniFaces intends to be free of 3rd party dependencies.
- Author:
- Arjan Tijms, Bauke Scholtz
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static IOExceptionclose(Closeable resource)Check if the given resource is notnulland then close it, whereby any caughtIOExceptionis been returned instead of thrown, so that the caller can if necessary handle (log) or just ignore it without the need to put another try-catch.static <T> Tcoalesce(T... objects)Returns the first non-nullobject of the argument list, ornullif there is no such element.static booleancontainsByClassName(Collection<?> objects, String className)Checks if the given collection contains an object with the given class name.static List<String>csvToList(String values)Converts comma separated values in a string into a list with those values.static List<String>csvToList(String values, String delimiter)Converts comma separated values in a string into a list with those values.static StringdecodeURL(String string)URL-decode the given string using UTF-8.static StringencodeURI(String string)URI-encode the given string using UTF-8.static StringencodeURL(String string)URL-encode the given string using UTF-8.static booleanendsWithOneOf(String string, String... suffixes)Returnstrueif the given string ends with one of the given suffixes.static StringescapeJS(String string, boolean escapeSingleQuote)Escapes the given string according the JavaScript code rules.static voidforEach(Object object, Consumer<? super Object> action)Performs an action for each element of given object which is streamed usingstream(Object).static StringformatRFC1123(Date date)static StringformatURLWithQueryString(String url, String queryString)Format given URL with given query string.static <D> DfromZonedDateTime(ZonedDateTime zonedDateTime, Class<?> type)ConvertZonedDateTimetoD.static ObjectgetDefaultValue(Class<?> cls)Returns the default value of the given class, covering primitives.static Class<?>getPrimitiveType(Class<?> cls)Returns the primitive type of the given class, if any.static <D> ZoneIdgetZoneId(D date)ObtainZoneIdfromD.static booleanisAnyEmpty(Object... values)Returnstrueif at least one value is empty.static booleanisBlank(String string)Returnstrueif the given string is null or is empty or contains whitespace only.static booleanisDecimal(String string)Returnstrueif the given string is parseable as a decimal.static booleanisEmpty(Part part)Returnstrueif the given part is null or is empty.static booleanisEmpty(Object value)Returnstrueif the given object is null or an empty array or has an empty toString() result.static booleanisEmpty(String string)Returnstrueif the given string is null or is empty.static booleanisEmpty(Collection<?> collection)Returnstrueif the given collection is null or is empty.static booleanisEmpty(Map<?,?> map)Returnstrueif the given map is null or is empty.static booleanisNumber(String string)Returnstrueif the given string is parseable as a number.static booleanisOneAnnotationPresent(Class<?> cls, Class<? extends Annotation>... annotations)Returnstrueif the given class has at least one of the given annotations.static booleanisOneInstanceOf(Class<?> cls, Class<?>... classes)Returnstrueif an instance of the given class could also be an instance of one of the given classes.static <T> booleanisOneOf(T object, T... objects)Returnstrueif the given object equals one of the given objects.static booleanisSerializable(Object object)Returnstrueif the given object is guaranteed to be serializable.static <E> List<E>iterableToList(Iterable<E> iterable)Converts an iterable into a list.static URLConnectionopenConnection(FacesContext context, Resource resource)Returns connection to given resource, taking into account possibly buggy component libraries.static LocaleparseLocale(Object locale)Parses the given object representing the locale to aLocaleobject.static DateparseRFC1123(String string)static <T> Map<T,T>reverse(Map<T,T> source)Returns a new map that contains the reverse of the given map.static StringserializeURLSafe(String string)Serialize the given string to the short possible unique URL-safe representation.static booleanstartsWithOneOf(String string, String... prefixes)Returnstrueif the given string starts with one of the given prefixes.static longstream(File file, OutputStream output, long start, long length)Stream a specified range of the given file to the given output via NIOChannelsand a directly allocated NIOByteBuffer.static longstream(InputStream input, OutputStream output)Stream the given input to the given output via NIOChannelsand a directly allocated NIOByteBuffer.static <E> Stream<E>stream(Iterable<E> iterable)Returns a stream of given iterable.static <T> Stream<T>stream(Object object)Returns a stream of given object.static <K,V>
Stream<Map.Entry<K,V>>stream(Map<K,V> map)Returns a stream of given map.static <T> Stream<T>stream(T[] array)Returns a stream of given array.static byte[]toByteArray(InputStream input)Read the given input stream into a byte array.static <D> ZonedDateTimetoZonedDateTime(D date)ConvertDtoZonedDateTime.static <Z> ZoneIdtoZoneId(Z timezone)ConvertZtoZoneId.static <E> Set<E>unmodifiableSet(Object... values)Creates an unmodifiable set based on the given values.static StringunserializeURLSafe(String string)Unserialize the given serialized URL-safe string.
-
-
-
Method Detail
-
isEmpty
public static boolean isEmpty(String string)
Returnstrueif the given string is null or is empty.- Parameters:
string- The string to be checked on emptiness.- Returns:
trueif the given string is null or is empty.
-
isEmpty
public static boolean isEmpty(Collection<?> collection)
Returnstrueif the given collection is null or is empty.- Parameters:
collection- The collection to be checked on emptiness.- Returns:
trueif the given collection is null or is empty.
-
isEmpty
public static boolean isEmpty(Map<?,?> map)
Returnstrueif the given map is null or is empty.- Parameters:
map- The map to be checked on emptiness.- Returns:
trueif the given map is null or is empty.
-
isEmpty
public static boolean isEmpty(Part part)
Returnstrueif the given part is null or is empty.- Parameters:
part- The part to be checked on emptiness.- Returns:
trueif the given part is null or is empty.- Since:
- 2.6
-
isEmpty
public static boolean isEmpty(Object value)
Returnstrueif the given object is null or an empty array or has an empty toString() result.- Parameters:
value- The value to be checked on emptiness.- Returns:
trueif the given object is null or an empty array or has an empty toString() result.
-
isAnyEmpty
public static boolean isAnyEmpty(Object... values)
Returnstrueif at least one value is empty.- Parameters:
values- the values to be checked on emptiness- Returns:
trueif any value is empty andfalseif no values are empty- Since:
- 1.8
-
isBlank
public static boolean isBlank(String string)
Returnstrueif the given string is null or is empty or contains whitespace only. In addition toisEmpty(String), this thus also returnstruewhenstring.trim().isEmpty()returnstrue.- Parameters:
string- The string to be checked on blankness.- Returns:
- True if the given string is null or is empty or contains whitespace only.
- Since:
- 1.5
-
isNumber
public static boolean isNumber(String string)
Returnstrueif the given string is parseable as a number. I.e. it is not null, nor blank and contains solely digits. I.e., it won't throw aNumberFormatExceptionwhen parsing asLong.- Parameters:
string- The string to be checked as number.- Returns:
trueif the given string is parseable as a number.- Since:
- 1.5.
-
isDecimal
public static boolean isDecimal(String string)
Returnstrueif the given string is parseable as a decimal. I.e. it is not null, nor blank and contains solely digits. I.e., it won't throw aNumberFormatExceptionwhen parsing asDouble.- Parameters:
string- The string to be checked as decimal.- Returns:
trueif the given string is parseable as a decimal.- Since:
- 1.5.
-
coalesce
@SafeVarargs public static <T> T coalesce(T... objects)
Returns the first non-nullobject of the argument list, ornullif there is no such element.- Type Parameters:
T- The generic object type.- Parameters:
objects- The argument list of objects to be tested for non-null.- Returns:
- The first non-
nullobject of the argument list, ornullif there is no such element.
-
isOneOf
@SafeVarargs public static <T> boolean isOneOf(T object, T... objects)
Returnstrueif the given object equals one of the given objects.- Type Parameters:
T- The generic object type.- Parameters:
object- The object to be checked if it equals one of the given objects.objects- The argument list of objects to be tested for equality.- Returns:
trueif the given object equals one of the given objects.
-
startsWithOneOf
public static boolean startsWithOneOf(String string, String... prefixes)
Returnstrueif the given string starts with one of the given prefixes.- Parameters:
string- The object to be checked if it starts with one of the given prefixes.prefixes- The argument list of prefixes to be checked- Returns:
trueif the given string starts with one of the given prefixes.- Since:
- 1.4
-
endsWithOneOf
public static boolean endsWithOneOf(String string, String... suffixes)
Returnstrueif the given string ends with one of the given suffixes.- Parameters:
string- The object to be checked if it ends with one of the given suffixes.suffixes- The argument list of suffixes to be checked- Returns:
trueif the given string ends with one of the given suffixes.- Since:
- 3.1
-
isOneInstanceOf
public static boolean isOneInstanceOf(Class<?> cls, Class<?>... classes)
Returnstrueif an instance of the given class could also be an instance of one of the given classes.- Parameters:
cls- The class to be checked if it could also be an instance of one of the given classes.classes- The argument list of classes to be tested.- Returns:
trueif the given class could also be an instance of one of the given classes.- Since:
- 2.0
-
isOneAnnotationPresent
@SafeVarargs public static boolean isOneAnnotationPresent(Class<?> cls, Class<? extends Annotation>... annotations)
Returnstrueif the given class has at least one of the given annotations.- Parameters:
cls- The class to be checked if it has at least one of the given annotations.annotations- The argument list of annotations to be tested on the given class.- Returns:
trueif the given clazz would be an instance of one of the given clazzes.- Since:
- 2.0
-
getDefaultValue
public static Object getDefaultValue(Class<?> cls)
Returns the default value of the given class, covering primitives. E.g. if given class isint.class, then it will return0. Autoboxing will do the rest. Non-primitives andvoid.classwill returnnull.- Parameters:
cls- The class to obtain the default value for.- Returns:
- The default value of the given class, covering primitives.
- Since:
- 2.4
-
getPrimitiveType
public static Class<?> getPrimitiveType(Class<?> cls)
Returns the primitive type of the given class, if any. E.g. if given class isInteger.class, then it will returnint.class. Non-primitives andvoid.classwill returnnull.- Parameters:
cls- The class to obtain the primitive type for.- Returns:
- The primitive type of the given class, if any.
- Since:
- 2.7.2
-
stream
public static long stream(InputStream input, OutputStream output) throws IOException
Stream the given input to the given output via NIOChannelsand a directly allocated NIOByteBuffer. Both the input and output streams will implicitly be closed after streaming, regardless of whether an exception is been thrown or not.- Parameters:
input- The input stream.output- The output stream.- Returns:
- The length of the written bytes.
- Throws:
IOException- When an I/O error occurs.
-
stream
public static long stream(File file, OutputStream output, long start, long length) throws IOException
Stream a specified range of the given file to the given output via NIOChannelsand a directly allocated NIOByteBuffer. The output stream will only implicitly be closed after streaming when the specified range represents the whole file, regardless of whether an exception is been thrown or not.- Parameters:
file- The file.output- The output stream.start- The start position (offset).length- The (intented) length of written bytes.- Returns:
- The (actual) length of the written bytes. This may be smaller when the given length is too large.
- Throws:
IOException- When an I/O error occurs.- Since:
- 2.2
-
toByteArray
public static byte[] toByteArray(InputStream input) throws IOException
Read the given input stream into a byte array. The given input stream will implicitly be closed after streaming, regardless of whether an exception is been thrown or not.- Parameters:
input- The input stream.- Returns:
- The input stream as a byte array.
- Throws:
IOException- When an I/O error occurs.- Since:
- 2.0
-
close
public static IOException close(Closeable resource)
Check if the given resource is notnulland then close it, whereby any caughtIOExceptionis been returned instead of thrown, so that the caller can if necessary handle (log) or just ignore it without the need to put another try-catch.- Parameters:
resource- The closeable resource to be closed.- Returns:
- The caught
IOException, ornullif none is been thrown.
-
isSerializable
public static boolean isSerializable(Object object)
Returnstrueif the given object is guaranteed to be serializable. This does that by checking whetherObjectOutputStream.writeObject(Object)on the given object doesn't throw an exception rather than checking if the given object is an instance ofSerializable.- Parameters:
object- The object to be tested.- Returns:
trueif the given object is guaranteed to be serializable.- Since:
- 2.4
-
unmodifiableSet
public static <E> Set<E> unmodifiableSet(Object... values)
Creates an unmodifiable set based on the given values. If one of the values is an instance of an array or a collection, then each of its values will also be merged into the set. Nested arrays or collections will result in aClassCastException.- Type Parameters:
E- The expected set element type.- Parameters:
values- The values to create an unmodifiable set for.- Returns:
- An unmodifiable set based on the given values.
- Throws:
ClassCastException- When one of the values or one of the arrays or collections is of wrong type.- Since:
- 1.1
-
iterableToList
public static <E> List<E> iterableToList(Iterable<E> iterable)
Converts an iterable into a list.This method makes NO guarantee to whether changes to the source iterable are reflected in the returned list or not. For instance if the given iterable already is a list, it's returned directly.
- Type Parameters:
E- The generic iterable element type.- Parameters:
iterable- The iterable to be converted.- Returns:
- The list representation of the given iterable, possibly the same instance as that iterable.
- Since:
- 1.5
-
csvToList
public static List<String> csvToList(String values)
Converts comma separated values in a string into a list with those values.E.g. a string with "foo, bar, kaz" will be converted into a
Listwith values:- "foo"
- "bar"
- "kaz"
",") as delimiter. SeecsvToList(String, String)for when a different delimiter is needed.- Parameters:
values- string with comma separated values- Returns:
- a list with all values encountered in the
valuesargument, can be the empty list. - Since:
- 1.4
-
csvToList
public static List<String> csvToList(String values, String delimiter)
Converts comma separated values in a string into a list with those values.E.g. a string with "foo, bar, kaz" will be converted into a
Listwith values:- "foo"
- "bar"
- "kaz"
- Parameters:
values- string with comma separated valuesdelimiter- the delimiter used to separate the actual values in thevaluesparameter.- Returns:
- a list with all values encountered in the
valuesargument, can be the empty list. - Since:
- 1.4
-
reverse
public static <T> Map<T,T> reverse(Map<T,T> source)
Returns a new map that contains the reverse of the given map.The reverse of a map means that every value X becomes a key X' with as corresponding value Y' the key Y that was originally associated with the value X.
- Type Parameters:
T- The generic map key/value type.- Parameters:
source- the map that is to be reversed- Returns:
- the reverse of the given map
-
containsByClassName
public static boolean containsByClassName(Collection<?> objects, String className)
Checks if the given collection contains an object with the given class name.- Parameters:
objects- collection of objects to checkclassName- name of the class to be checked for- Returns:
- true if the collection contains at least one object with the given class name, false otherwise
- Since:
- 1.6
-
stream
public static <T> Stream<T> stream(Object object)
Returns a stream of given object. Supported types are: Anything else is returned as a single-element stream. Null is returned as an empty stream.- Type Parameters:
T- The expected stream type.- Parameters:
object- Any object to get a stream for.- Returns:
- A stream of given object.
- Throws:
ClassCastException- WhenTis of wrong type.- Since:
- 3.0
-
stream
public static <E> Stream<E> stream(Iterable<E> iterable)
Returns a stream of given iterable.- Type Parameters:
E- The generic iterable element type.- Parameters:
iterable- Any iterable to get a stream for.- Returns:
- A stream of given iterable.
- Since:
- 3.0
-
stream
public static <K,V> Stream<Map.Entry<K,V>> stream(Map<K,V> map)
Returns a stream of given map.- Type Parameters:
K- The generic map key type.V- The generic map value type.- Parameters:
map- Any map to get a stream for.- Returns:
- A stream of given map.
- Since:
- 3.0
-
stream
public static <T> Stream<T> stream(T[] array)
Returns a stream of given array.- Type Parameters:
T- The generic array item type.- Parameters:
array- Any array to get a stream for.- Returns:
- A stream of given array.
- Since:
- 3.0
-
forEach
public static void forEach(Object object, Consumer<? super Object> action)
Performs an action for each element of given object which is streamed usingstream(Object).- Parameters:
object- Any streamable object.action- A non-interfering action to perform on each element.- Since:
- 3.0
-
formatRFC1123
public static String formatRFC1123(Date date)
Formats the givenDateto a string in RFC 1123 format. This format is used in HTTP headers and in JavaScriptDateconstructor.- Parameters:
date- TheDateto be formatted to a string in RFC 1123 format.- Returns:
- The formatted string.
- Since:
- 1.2
-
parseRFC1123
public static Date parseRFC1123(String string) throws ParseException
- Parameters:
string- The string in RFC 1123 format to be parsed to aDateobject.- Returns:
- The parsed
Date. - Throws:
ParseException- When the given string is not in RFC 1123 format.- Since:
- 1.2
-
getZoneId
public static <D> ZoneId getZoneId(D date)
ObtainZoneIdfromD. WhenDisnullorDate, then returnZoneId.systemDefault(). WhenDisCalendar, then returnTimeZone.toZoneId()ofCalendar.getTimeZone()WhenDisTemporaland supportsChronoField.OFFSET_SECONDS, then returnZoneId.from(java.time.temporal.TemporalAccessor). WhenDisTemporaland supportsChronoField.CLOCK_HOUR_OF_DAY, then returnZoneId.systemDefault(). WhenDisTemporaland supports neither, then returnZoneOffset.UTC.
-
toZoneId
public static <Z> ZoneId toZoneId(Z timezone)
ConvertZtoZoneId. WhenZisnull, then returnZoneId.systemDefault(). WhenZisZoneId, then return it. WhenZisTimeZone, then returnTimeZone.toZoneId(). WhenZisString, then returnZoneId.of(String).
-
toZonedDateTime
public static <D> ZonedDateTime toZonedDateTime(D date)
ConvertDtoZonedDateTime. This method is guaranteed repeatable when combined withfromZonedDateTime(ZonedDateTime, Class).- Type Parameters:
D- The date type, can beDate,CalendarorTemporal.- Parameters:
date- TheDto convert toZonedDateTime.- Returns:
ZonedDateTimeconverted fromD.- Throws:
IllegalArgumentException- When date is notDate,CalendarorTemporal.- Since:
- 3.6
-
fromZonedDateTime
public static <D> D fromZonedDateTime(ZonedDateTime zonedDateTime, Class<?> type)
ConvertZonedDateTimetoD. This method is guaranteed repeatable when combined withtoZonedDateTime(Object).- Type Parameters:
D- The date type, can beDate,CalendarorTemporalor any of its subclasses.- Parameters:
zonedDateTime- TheZonedDateTimeto convert toD.type- The type ofD.- Returns:
Dconverted fromZonedDateTime.- Throws:
NullPointerException- When type isnull.IllegalArgumentException- When type is notDate,CalendarorTemporalor any of its subclasses.- Since:
- 3.6
-
parseLocale
public static Locale parseLocale(Object locale)
Parses the given object representing the locale to aLocaleobject. If it isnull, then returnnull. Else if it is already an instance ofLocale, then just return it. Else if it is in pattern ISO 639 alpha-2/3, optionally followed by "_" and ISO 3166-1 alpha-2 country code, then split the language/country and construct a newLocalewith it. Else parse it viaLocale.forLanguageTag(String)and return it.- Parameters:
locale- The object representing the locale.- Returns:
- The parsed
Locale. - Since:
- 2.3
-
serializeURLSafe
public static String serializeURLSafe(String string)
Serialize the given string to the short possible unique URL-safe representation. The current implementation will decode the given string with UTF-8 and then compress it with ZLIB using "best compression" algorithm and then Base64-encode the resulting bytes without the=padding, whereafter the Base64 characters+and/are been replaced by respectively-and_to make it URL-safe (so that no platform-sensitive URL-encoding needs to be done when used in URLs).- Parameters:
string- The string to be serialized.- Returns:
- The serialized URL-safe string, or
nullwhen the given string is itselfnull. - Since:
- 1.2
-
unserializeURLSafe
public static String unserializeURLSafe(String string)
Unserialize the given serialized URL-safe string. This does the inverse ofserializeURLSafe(String).- Parameters:
string- The serialized URL-safe string to be unserialized.- Returns:
- The unserialized string, or
nullwhen the given string is by itselfnull. - Throws:
IllegalArgumentException- When the given serialized URL-safe string is not in valid format as returned byserializeURLSafe(String).- Since:
- 1.2
-
encodeURL
public static String encodeURL(String string)
URL-encode the given string using UTF-8.- Parameters:
string- The string to be URL-encoded using UTF-8.- Returns:
- The given string, URL-encoded using UTF-8, or
nullifnullwas given. - Throws:
UnsupportedOperationException- When this platform does not support UTF-8.- Since:
- 1.4
-
decodeURL
public static String decodeURL(String string)
URL-decode the given string using UTF-8.- Parameters:
string- The string to be URL-decode using UTF-8.- Returns:
- The given string, URL-decode using UTF-8, or
nullifnullwas given. - Throws:
UnsupportedOperationException- When this platform does not support UTF-8.- Since:
- 1.4
-
encodeURI
public static String encodeURI(String string)
URI-encode the given string using UTF-8. URIs (paths and filenames) have different encoding rules as compared to URL query string parameters.URLEncoderis actually only for www (HTML) form based query string parameter values (as used when a webbrowser submits a HTML form). URI encoding has a lot in common with URL encoding, but the space has to be %20 and some chars doesn't necessarily need to be encoded.Since version 4.2 this method is using RFC 3986 rules. Previously it was using RFC 2396 rules. The result is therefore not per definition exactly the same, but this is supposed to be backwards compatible in modern clients.
- Parameters:
string- The string to be URI-encoded using UTF-8.- Returns:
- The given string, URI-encoded using UTF-8, or
nullifnullwas given. - Throws:
UnsupportedOperationException- When this platform does not support UTF-8.- Since:
- 2.4
-
formatURLWithQueryString
public static String formatURLWithQueryString(String url, String queryString)
Format given URL with given query string. If given URL is empty, assume/as URL. If given query string is empty, return URL right away. If given URL contains a?, prepend query string with&, else with?. Finally append query string to URL and return it.- Parameters:
url- URL to be formatted with given query string.queryString- Query string to be appended to given URL.- Returns:
- Formatted URL with query string.
- Since:
- 3.0
-
escapeJS
public static String escapeJS(String string, boolean escapeSingleQuote)
Escapes the given string according the JavaScript code rules. This escapes among others the special characters, the whitespace, the quotes and the unicode characters. Useful whenever you want to use a Java string variable as a JavaScript string variable.- Parameters:
string- The string to be escaped according the JavaScript code rules.escapeSingleQuote- Whether to escape single quotes as well or not. Set tofalseif you want to escape it for usage in JSON.- Returns:
- The escaped string according the JavaScript code rules.
-
openConnection
public static URLConnection openConnection(FacesContext context, Resource resource)
Returns connection to given resource, taking into account possibly buggy component libraries.- Parameters:
context- The involved faces context.resource- The resource to obtain connection from.- Returns:
- Connection to given resource.
- Since:
- 3.6
-
-