Class 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 Detail

      • isEmpty

        public static boolean isEmpty​(String string)
        Returns true if the given string is null or is empty.
        Parameters:
        string - The string to be checked on emptiness.
        Returns:
        true if the given string is null or is empty.
      • isEmpty

        public static boolean isEmpty​(Collection<?> collection)
        Returns true if the given collection is null or is empty.
        Parameters:
        collection - The collection to be checked on emptiness.
        Returns:
        true if the given collection is null or is empty.
      • isEmpty

        public static boolean isEmpty​(Map<?,​?> map)
        Returns true if the given map is null or is empty.
        Parameters:
        map - The map to be checked on emptiness.
        Returns:
        true if the given map is null or is empty.
      • isEmpty

        public static boolean isEmpty​(Part part)
        Returns true if the given part is null or is empty.
        Parameters:
        part - The part to be checked on emptiness.
        Returns:
        true if the given part is null or is empty.
        Since:
        2.6
      • isEmpty

        public static boolean isEmpty​(Object value)
        Returns true if 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:
        true if the given object is null or an empty array or has an empty toString() result.
      • isAnyEmpty

        public static boolean isAnyEmpty​(Object... values)
        Returns true if at least one value is empty.
        Parameters:
        values - the values to be checked on emptiness
        Returns:
        true if any value is empty and false if no values are empty
        Since:
        1.8
      • isBlank

        public static boolean isBlank​(String string)
        Returns true if the given string is null or is empty or contains whitespace only. In addition to isEmpty(String), this thus also returns true when string.trim().isEmpty() returns true.
        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)
        Returns true if 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 a NumberFormatException when parsing as Long.
        Parameters:
        string - The string to be checked as number.
        Returns:
        true if the given string is parseable as a number.
        Since:
        1.5.
      • isDecimal

        public static boolean isDecimal​(String string)
        Returns true if 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 a NumberFormatException when parsing as Double.
        Parameters:
        string - The string to be checked as decimal.
        Returns:
        true if the given string is parseable as a decimal.
        Since:
        1.5.
      • coalesce

        @SafeVarargs
        public static <T> T coalesce​(T... objects)
        Returns the first non-null object of the argument list, or null if 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-null object of the argument list, or null if there is no such element.
      • isOneOf

        @SafeVarargs
        public static <T> boolean isOneOf​(T object,
                                          T... objects)
        Returns true if 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:
        true if the given object equals one of the given objects.
      • startsWithOneOf

        public static boolean startsWithOneOf​(String string,
                                              String... prefixes)
        Returns true if 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:
        true if the given string starts with one of the given prefixes.
        Since:
        1.4
      • endsWithOneOf

        public static boolean endsWithOneOf​(String string,
                                            String... suffixes)
        Returns true if 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:
        true if the given string ends with one of the given suffixes.
        Since:
        3.1
      • isOneInstanceOf

        public static boolean isOneInstanceOf​(Class<?> cls,
                                              Class<?>... classes)
        Returns true if 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:
        true if 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)
        Returns true if 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:
        true if 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 is int.class, then it will return 0. Autoboxing will do the rest. Non-primitives and void.class will return null.
        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 is Integer.class, then it will return int.class. Non-primitives and void.class will return null.
        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 NIO Channels and a directly allocated NIO ByteBuffer. 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 NIO Channels and a directly allocated NIO ByteBuffer. 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 not null and then close it, whereby any caught IOException is 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, or null if none is been thrown.
      • isSerializable

        public static boolean isSerializable​(Object object)
        Returns true if the given object is guaranteed to be serializable. This does that by checking whether ObjectOutputStream.writeObject(Object) on the given object doesn't throw an exception rather than checking if the given object is an instance of Serializable.
        Parameters:
        object - The object to be tested.
        Returns:
        true if 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 a ClassCastException.
        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 List with values:

        • "foo"
        • "bar"
        • "kaz"
        Note that whitespace will be stripped. Empty entries are not supported. This method defaults to using a comma (",") as delimiter. See csvToList(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 values argument, 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 List with values:

        • "foo"
        • "bar"
        • "kaz"
        Note that whitespace will be stripped. Empty entries are not supported.
        Parameters:
        values - string with comma separated values
        delimiter - the delimiter used to separate the actual values in the values parameter.
        Returns:
        a list with all values encountered in the values argument, 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 check
        className - 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 - When T is 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 using stream(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 given Date to a string in RFC 1123 format. This format is used in HTTP headers and in JavaScript Date constructor.
        Parameters:
        date - The Date to 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
        Parses the given string in RFC 1123 format to a Date object.
        Parameters:
        string - The string in RFC 1123 format to be parsed to a Date object.
        Returns:
        The parsed Date.
        Throws:
        ParseException - When the given string is not in RFC 1123 format.
        Since:
        1.2
      • parseLocale

        public static Locale parseLocale​(Object locale)
        Parses the given object representing the locale to a Locale object. If it is null, then return null. Else if it is already an instance of Locale, 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 new Locale with it. Else parse it via Locale.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 null when the given string is itself null.
        Since:
        1.2
      • unserializeURLSafe

        public static String unserializeURLSafe​(String string)
        Unserialize the given serialized URL-safe string. This does the inverse of serializeURLSafe(String).
        Parameters:
        string - The serialized URL-safe string to be unserialized.
        Returns:
        The unserialized string, or null when the given string is by itself null.
        Throws:
        IllegalArgumentException - When the given serialized URL-safe string is not in valid format as returned by serializeURLSafe(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 null if null was 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 null if null was 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. URLEncoder is 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 null if null was 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
      • containsQueryStringParameter

        public static boolean containsQueryStringParameter​(String url,
                                                           String parameterName)
        Returns true when given URL contains a query string parameter with given name.
        Parameters:
        url - URL to be checked.
        parameterName - Parameter name to be checked.
        Returns:
        true when given URL contains a query string parameter with given name.
        Since:
        3.14.5
      • 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 to false if 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