Class CommonUtils


  • public abstract class CommonUtils
    extends Object
    Collection of utility methods used in 'ignite-commons' and throughout the system.
    • Constructor Detail

      • CommonUtils

        public CommonUtils()
    • Method Detail

      • forceNewInstance

        @Nullable
        public static <T> T forceNewInstance​(Class<?> cls)
                                      throws IgniteCheckedException
        Creates new instance of a class even if it does not have public constructor.
        Parameters:
        cls - Class to instantiate.
        Returns:
        New instance of the class or null if empty constructor could not be assigned.
        Throws:
        IgniteCheckedException - If failed.
      • forceEmptyConstructor

        @Nullable
        public static @Nullable Constructor<?> forceEmptyConstructor​(Class<?> cls)
                                                              throws IgniteCheckedException
        Gets empty constructor for class even if the class does not have empty constructor declared. This method is guaranteed to work with SUN JDK and other JDKs still need to be tested.
        Parameters:
        cls - Class to get empty constructor for.
        Returns:
        Empty constructor if one could be found or null otherwise.
        Throws:
        IgniteCheckedException - If failed.
      • sunReflectionFactory

        @Nullable
        public static @Nullable Object sunReflectionFactory()
        SUN JDK specific reflection factory for objects without public constructor.
        Returns:
        Reflection factory for objects without public constructor.
      • capacity

        public static int capacity​(int expSize)
        Returns a capacity that is sufficient to keep the map from being resized as long as it grows no larger than expSize and the load factor is >= its default (0.75). Copy pasted from guava. See com.google.common.collect.Maps#capacity(int)
        Parameters:
        expSize - Expected size of created map.
        Returns:
        Capacity.
      • nl

        public static String nl()
        Returns:
        line.separator system property.
      • jdkVersion

        public static String jdkVersion()
        Gets JDK version.
        Returns:
        JDK version.
      • majorJavaVersion

        public static int majorJavaVersion​(String verStr)
        Get major Java version from string.
        Parameters:
        verStr - Version string.
        Returns:
        Major version or zero if failed to resolve.
      • nearestPow2

        public static int nearestPow2​(int x,
                                      boolean less)
        Parameters:
        x - X.
        less - Less.
      • loadService

        public static <S> Iterable<S> loadService​(Class<S> svcCls)
        Type Parameters:
        S - Type of loaded interfaces.
        Parameters:
        svcCls - Service class to load.
        Returns:
        Lazy iterable structure over loaded class implementations.
      • millisToNanos

        public static long millisToNanos​(long millis)
        Convert milliseconds time interval to nanoseconds.
        Parameters:
        millis - Original time interval.
        Returns:
        Calculated time interval.
      • nanosToMillis

        public static long nanosToMillis​(long nanos)
        Convert nanoseconds time interval to milliseconds.
        Parameters:
        nanos - Original time interval.
        Returns:
        Calculated time interval.
      • millisSinceNanos

        public static long millisSinceNanos​(long nanos)
        Returns number of milliseconds passed after the given nanos timestamp.
        Parameters:
        nanos - Nanos timestamp.
        Returns:
        Number of milliseconds passed after the given nanos timestamp.
        See Also:
        System.nanoTime()
      • ceilPow2

        public static int ceilPow2​(int v)
        Gets nearest power of 2 larger or equal than v.
        Parameters:
        v - Value.
        Returns:
        Nearest power of 2.
      • isPow2

        public static boolean isPow2​(int i)
        Parameters:
        i - Value.
        Returns:
        true If the given value is power of 2 (0 is not power of 2).
      • nextPowerOf2

        public static int nextPowerOf2​(int v)
        Round up the argument to the next highest power of 2;
        Parameters:
        v - Value to round up.
        Returns:
        Next closest power of 2.
      • currentTimeMillis

        public static long currentTimeMillis()
        Returns:
        System time approximated by 10 ms.
      • onGridStart

        public static void onGridStart()
        Starts clock timer if grid is first.
      • writeUuid

        public static void writeUuid​(DataOutput out,
                                     UUID uid)
                              throws IOException
        Writes UUID to output stream. This method is meant to be used by implementations of Externalizable interface.
        Parameters:
        out - Output stream.
        uid - UUID to write.
        Throws:
        IOException - If write failed.
      • readUuid

        @Nullable
        public static @Nullable UUID readUuid​(DataInput in)
                                       throws IOException
        Reads UUID from input stream. This method is meant to be used by implementations of Externalizable interface.
        Parameters:
        in - Input stream.
        Returns:
        Read UUID.
        Throws:
        IOException - If read failed.
      • getCurrentIgniteName

        @Nullable
        public static @Nullable String getCurrentIgniteName()
        Get current Ignite name.
        Returns:
        Current Ignite name.
      • isCurrentIgniteNameSet

        public static boolean isCurrentIgniteNameSet​(@Nullable
                                                     @Nullable String name)
        Check if current Ignite name is set.
        Parameters:
        name - Name to check.
        Returns:
        True if set.
      • setCurrentIgniteName

        @Nullable
        public static @Nullable String setCurrentIgniteName​(@Nullable
                                                            @Nullable String newName)
        Set current Ignite name.
        Parameters:
        newName - New name.
        Returns:
        Old name.
      • restoreOldIgniteName

        public static void restoreOldIgniteName​(@Nullable
                                                @Nullable String oldName,
                                                @Nullable
                                                @Nullable String curName)
        Restore old Ignite name.
        Parameters:
        oldName - Old name.
        curName - Current name.
      • gridClassLoader

        public static ClassLoader gridClassLoader()
        Returns:
        Class loader used to load Ignite itself.
      • resolveClassLoader

        public static ClassLoader resolveClassLoader​(@Nullable
                                                     @Nullable ClassLoader ldr,
                                                     @Nullable
                                                     @Nullable ClassLoader cfgLdr)
        Parameters:
        ldr - Custom class loader.
        cfgLdr - Class loader from config.
        Returns:
        ClassLoader passed as param in case it is not null or cfgLdr in case it is not null or ClassLoader used to start Ignite.
      • isLoadableBy

        public static boolean isLoadableBy​(String clsName,
                                           @Nullable
                                           @Nullable ClassLoader ldr)
        Tests whether given class is loadable with provided class loader.
        Parameters:
        clsName - Class name to test.
        ldr - Class loader to test with. If null - we'll use system class loader instead. If System class loader is not set - this method will return false.
        Returns:
        True if class is loadable, false otherwise.
      • classForName

        @Nullable
        public static @Nullable Class<?> classForName​(@Nullable
                                                      @Nullable String cls,
                                                      @Nullable
                                                      @Nullable Class<?> dflt)
        Gets class for the given name if it can be loaded or default given class.
        Parameters:
        cls - Class.
        dflt - Default class to return.
        Returns:
        Class or default given class if it can't be found.
      • classForName

        @Nullable
        public static @Nullable Class<?> classForName​(@Nullable
                                                      @Nullable String cls,
                                                      @Nullable
                                                      @Nullable Class<?> dflt,
                                                      boolean includePrimitiveTypes)
        Gets class for the given name if it can be loaded or default given class.
        Parameters:
        cls - Class.
        dflt - Default class to return.
        includePrimitiveTypes - Whether class resolution should include primitive types (i.e. "int" will resolve to int.class if flag is set)
        Returns:
        Class or default given class if it can't be found.
      • forName

        public static Class<?> forName​(String clsName,
                                       @Nullable
                                       @Nullable ClassLoader ldr,
                                       @Nullable
                                       @Nullable IgnitePredicate<String> clsFilter,
                                       boolean useCache)
                                throws ClassNotFoundException
        Gets class for provided name. Accepts primitive types names.
        Parameters:
        clsName - Class name.
        ldr - Class loader.
        useCache - If true class loader and result should be cached internally, false otherwise.
        Returns:
        Class.
        Throws:
        ClassNotFoundException - If class not found.
      • clearClassFromClassCache

        public static void clearClassFromClassCache​(ClassLoader ldr,
                                                    String clsName)
        Clears class associated with provided class loader from class cache.
        Parameters:
        ldr - Class loader.
        clsName - Class name of clearing class.
      • clearClassCache

        public static void clearClassCache​(ClassLoader ldr)
        Clears class cache for provided loader.
        Parameters:
        ldr - Class loader.
      • clearClassCache

        public static void clearClassCache()
        Completely clears class cache.
      • lambdaEnclosingClassName

        @Nullable
        public static @Nullable String lambdaEnclosingClassName​(String clsName)
        Extracts full name of enclosing class from JDK8 lambda class name.
        Parameters:
        clsName - JDK8 lambda class name.
        Returns:
        Full name of enclosing class for JDK8 lambda class name or null if passed in name is not related to lambda.
      • isLambda

        public static boolean isLambda​(Class<?> objectClass)
        Returns true if class is a lambda.
        Parameters:
        objectClass - Class.
        Returns:
        true if class is a lambda, false otherwise.
      • classCannotBeLoadedByName

        public static boolean classCannotBeLoadedByName​(Class<?> objectClass)
        Returns true if class can not be loaded by name.
        Parameters:
        objectClass - Class.
        Returns:
        true if class can not be loaded by name, false otherwise.
      • newHashMap

        public static <K,​V> HashMap<K,​V> newHashMap​(int expSize)
        Creates new HashMap with expected size.
        Type Parameters:
        K - Type of map keys.
        V - Type of map values.
        Parameters:
        expSize - Expected size of created map.
        Returns:
        New map.
      • newLinkedHashMap

        public static <K,​V> LinkedHashMap<K,​V> newLinkedHashMap​(int expSize)
        Creates new LinkedHashMap with expected size.
        Type Parameters:
        K - Type of map keys.
        V - Type of map values.
        Parameters:
        expSize - Expected size of created map.
        Returns:
        New map.
      • newHashSet

        public static <T> HashSet<T> newHashSet​(int expSize)
        Creates new HashSet with expected size.
        Type Parameters:
        T - Type of elements.
        Parameters:
        expSize - Expected size of created map.
        Returns:
        New set.
      • newLinkedHashSet

        public static <T> LinkedHashSet<T> newLinkedHashSet​(int expSize)
        Creates new LinkedHashSet with expected size.
        Type Parameters:
        T - Type of elements.
        Parameters:
        expSize - Expected size of created map.
        Returns:
        New set.
      • limitedMap

        public static <K,​V> Map<K,​V> limitedMap​(int limit)
        Creates new map that limited by size.
        Parameters:
        limit - Limit for size.
      • convertToSingletonList

        public static <T> Collection<T> convertToSingletonList​(Collection<T> col)
        Parameters:
        col - non-null collection with one element
        Returns:
        a SingletonList containing the element in the original collection
      • close

        public static void close​(@Nullable
                                 @Nullable AutoCloseable rsrc,
                                 @Nullable
                                 @Nullable IgniteLogger log)
        Closes given resource logging possible checked exception.
        Parameters:
        rsrc - Resource to close. If it's null - it's no-op.
        log - Logger to log possible checked exception with (optional).
      • close

        public static void close​(@Nullable
                                 @Nullable Socket sock,
                                 @Nullable
                                 @Nullable IgniteLogger log)
        Closes given socket logging possible checked exception.
        Parameters:
        sock - Socket to close. If it's null - it's no-op.
        log - Logger to log possible checked exception with (optional).
      • close

        public static void close​(@Nullable
                                 @Nullable SelectionKey rsrc,
                                 @Nullable
                                 @Nullable IgniteLogger log)
        Closes given resource logging possible checked exceptions.
        Parameters:
        rsrc - Resource to close. If it's null - it's no-op.
        log - Logger to log possible checked exception with (optional).
      • close

        public static void close​(@Nullable
                                 @Nullable DatagramSocket rsrc)
        Closes given resource.
        Parameters:
        rsrc - Resource to close. If it's null - it's no-op.
      • close

        public static void close​(@Nullable
                                 @Nullable Selector rsrc,
                                 @Nullable
                                 @Nullable IgniteLogger log)
        Closes given resource logging possible checked exception.
        Parameters:
        rsrc - Resource to close. If it's null - it's no-op.
        log - Logger to log possible checked exception with (optional).
      • close

        public static void close​(@Nullable
                                 @Nullable URLClassLoader clsLdr,
                                 @Nullable
                                 @Nullable IgniteLogger log)
        Closes class loader logging possible checked exception.
        Parameters:
        clsLdr - Class loader. If it's null - it's no-op.
        log - Logger to log possible checked exception with (optional).
      • warn

        public static void warn​(@Nullable
                                @Nullable IgniteLogger log,
                                Object msg)
        Depending on whether log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message. If log is null or in QUIET mode it will add (wrn) prefix to the message.
        Parameters:
        log - Optional logger to use when QUIET mode is not enabled.
        msg - Message to log.
      • warn

        public static void warn​(@Nullable
                                @Nullable IgniteLogger log,
                                Object msg,
                                @Nullable
                                @Nullable Throwable e)
        Depending on whether log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message. If log is null or in QUIET mode it will add (wrn) prefix to the message.
        Parameters:
        log - Optional logger to use when QUIET mode is not enabled.
        msg - Message to log using normal logger.
        e - Optional exception.
      • quietAndWarn

        public static void quietAndWarn​(IgniteLogger log,
                                        Object msg)
        Logs warning message in both verbose and quiet modes.
        Parameters:
        log - Logger to use.
        msg - Message to log.
      • quietAndWarn

        public static void quietAndWarn​(IgniteLogger log,
                                        Object msg,
                                        Object shortMsg)
        Logs warning message in both verbose and quiet modes.
        Parameters:
        log - Logger to use.
        shortMsg - Short message.
        msg - Message to log.
      • quietAndWarn

        public static void quietAndWarn​(IgniteLogger log,
                                        Object msg,
                                        @Nullable
                                        @Nullable Throwable e)
        Logs warning message in both verbose and quiet modes.
        Parameters:
        log - Logger to use.
        msg - Message to log.
        e - Optional exception.
      • error

        public static void error​(@Nullable
                                 @Nullable IgniteLogger log,
                                 Object msg)
        Depending on whether log is provided and quiet mode is enabled logs given messages as quiet message or normal log ERROR message. If log is null or in QUIET mode it will add (err) prefix to the message.
        Parameters:
        log - Optional logger to use when QUIET mode is not enabled.
        msg - Message to log.
      • warnDevOnly

        public static void warnDevOnly​(@Nullable
                                       @Nullable IgniteLogger log,
                                       Object msg)
        Depending on whether log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message with DEV_ONLY marker. If log is null or in QUIET mode it will add (wrn) prefix to the message. If property IGNITE_DEV_ONLY_LOGGING_DISABLED is set to true, the message will not be logged.
        Parameters:
        log - Optional logger to use when QUIET mode is not enabled.
        msg - Message to log.
      • log

        public static void log​(@Nullable
                               @Nullable IgniteLogger log,
                               Object longMsg,
                               Object shortMsg)
        Depending on whether log is provided and quiet mode is enabled logs given messages as quiet message or normal log INFO message.

        NOTE: unlike the normal logging when INFO level may not be enabled and therefore no logging will happen - using this method the log will be written always either via INFO log or quiet mode.

        USE IT APPROPRIATELY.

        Parameters:
        log - Optional logger to use when QUIET mode is not enabled.
        longMsg - Message to log using normal logger.
        shortMsg - Message to log using quiet logger.
      • log

        public static void log​(@Nullable
                               @Nullable IgniteLogger log,
                               Object msg)
        Depending on whether log is provided and quiet mode is enabled logs given messages as quiet message or normal log INF0 message.

        NOTE: unlike the normal logging when INFO level may not be enabled and therefore no logging will happen - using this method the log will be written always either via INFO log or quiet mode.

        USE IT APPROPRIATELY.

        Parameters:
        log - Optional logger to use when QUIET mode is not enabled.
        msg - Message to log.
      • error

        public static void error​(@Nullable
                                 @Nullable IgniteLogger log,
                                 Object longMsg,
                                 Object shortMsg,
                                 @Nullable
                                 @Nullable Throwable e)
        Depending on whether log is provided and quiet mode is enabled logs given messages as quiet message or normal log ERROR message. If log is null or in QUIET mode it will add (err) prefix to the message.
        Parameters:
        log - Optional logger to use when QUIET mode is not enabled.
        longMsg - Message to log using normal logger.
        shortMsg - Message to log using quiet logger.
        e - Optional exception.
      • quiet

        public static void quiet​(boolean err,
                                 Object... objs)
        Parameters:
        err - Whether to print to System.err.
        objs - Objects to log in quiet mode.
      • quietMultipleLines

        public static void quietMultipleLines​(boolean err,
                                              String multiline)
        Parameters:
        err - Whether to print to System.err.
        multiline - Multiple lines string to print.
      • quietAndInfo

        public static void quietAndInfo​(IgniteLogger log,
                                        String msg)
        Prints out the message in quiet and info modes.
        Parameters:
        log - Logger.
        msg - Message to print.
      • compact

        public static String compact​(String s)
        Replaces all occurrences of org.apache.ignite. with o.a.i., org.apache.ignite.internal. with o.a.i.i., org.apache.ignite.internal.visor. with o.a.i.i.v. and
        Parameters:
        s - String to replace in.
        Returns:
        Replaces string.
      • isEnum

        public static boolean isEnum​(Class cls)
        Check if given class represents a Enum.
        Parameters:
        cls - Class to check.
        Returns:
        True if this is a Enum class.
      • firstNotNull

        @Nullable
        public static <T> T firstNotNull​(@Nullable
                                         @Nullable T... vals)
        Returns a first non-null value in a given array, if such is present.
        Parameters:
        vals - Input array.
        Returns:
        First non-null value, or null, if array is empty or contains only nulls.
      • isFinal

        public static boolean isFinal​(Class<?> cls)
        Parameters:
        cls - Class to check.
        Returns:
        True if class is final.
      • isIgnite

        public static boolean isIgnite​(Class<?> cls)
        Checks if given class is of Ignite type.
        Parameters:
        cls - Class to check.
        Returns:
        True if given class is of Ignite type.
      • isGrid

        public static boolean isGrid​(Class<?> cls)
        Checks if given class is of Grid type.
        Parameters:
        cls - Class to check.
        Returns:
        True if given class is of Grid type.
      • isJdk

        public static boolean isJdk​(Class<?> cls)
        Check if given class is of JDK type.
        Parameters:
        cls - Class to check.
        Returns:
        True if object is JDK type.
      • findInheritableMethod

        @Nullable
        public static @Nullable Method findInheritableMethod​(Class<?> cls,
                                                             String name,
                                                             Class<?>... paramTypes)
        Finds a non-static and non-abstract method from the class it parents. Method.getMethod() does not return non-public method.
        Parameters:
        cls - Target class.
        name - Name of the method.
        paramTypes - Method parameters.
        Returns:
        Method or null.
      • packageName

        public static String packageName​(Class<?> cls)
        Parameters:
        cls - Class.
        Returns:
        Package name.
      • writeLongString

        public static void writeLongString​(DataOutput out,
                                           @Nullable
                                           @Nullable String s)
                                    throws IOException
        Writes string to output stream accounting for null values.
        This method can write string of any length, limit of 65535 is not applied.
        Parameters:
        out - Output stream to write to.
        s - String to write, possibly null.
        Throws:
        IOException - If write failed.
      • readLongString

        @Nullable
        public static @Nullable String readLongString​(DataInput in)
                                               throws IOException
        Reads string from input stream accounting for null values.
        This method can read string of any length, limit of 65535 is not applied.
        Parameters:
        in - Stream to read from.
        Returns:
        Read string, possibly null.
        Throws:
        IOException - If read failed.
      • utfBytes

        public static int utfBytes​(char c)
        Get number of bytes for DataOutput.writeUTF(java.lang.String), depending on character:
        One byte - If a character c is in the range \u0001 through \u007f.
        Two bytes - If a character c is \u0000 or is in the range \u0080 through \u07ff.
        Three bytes - If a character c is in the range \u0800 through uffff.
        Parameters:
        c - Character.
        Returns:
        Number of bytes.
      • getIgniteHome

        @Nullable
        public static @Nullable String getIgniteHome()
        Retrieves IGNITE_HOME property. The property is retrieved from system properties or from environment in that order.
        Returns:
        IGNITE_HOME property.
      • setIgniteHome

        public static void setIgniteHome​(@Nullable
                                         @Nullable String path)
        Parameters:
        path - Ignite home. May be null.
      • nullifyHomeDirectory

        public static void nullifyHomeDirectory()
        Nullifies Ignite home directory. For test purposes only.
      • isLinux

        public static boolean isLinux()
        Indicates whether current OS is Linux flavor.
        Returns:
        true if current OS is Linux - false otherwise.
      • isMacOs

        public static boolean isMacOs()
        Indicates whether current OS is Mac OS.
        Returns:
        true if current OS is Mac OS - false otherwise.
      • isUnix

        public static boolean isUnix()
        Indicates whether current OS is UNIX flavor.
        Returns:
        true if current OS is UNIX - false otherwise.
      • isWindows

        public static boolean isWindows()
        Indicates whether current OS is Windows.
        Returns:
        true if current OS is Windows (any versions) - false otherwise.
      • classLoaderUrls

        public static URL[] classLoaderUrls​(ClassLoader clsLdr)
        Returns URLs of class loader
        Parameters:
        clsLdr - Class loader.
      • hashCode

        public static int hashCode​(Object obj)
        Calculate a hashCode for an array.
        Parameters:
        obj - Object.
      • isGeometryClass

        public static boolean isGeometryClass​(Class<?> cls)
        Checks if the given class is GEOMETRY.
        Parameters:
        cls - Class.
        Returns:
        true If this is geometry.