Class IgniteUtils
- java.lang.Object
-
- org.apache.ignite.internal.util.IgniteUtils
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceIgniteUtils.InterfaceSupplierExplicit class forSupplier<Enumeration<NetworkInterface>>.
-
Field Summary
Fields Modifier and Type Field Description static DateTimeFormatterDEBUG_DATE_FMTDebug date format.static StringDELIMstatic LongDFLT_MAX_CHECKPOINTING_PAGE_BUFFER_SIZEDefault minimum checkpointing page buffer size (may be adjusted by Ignite).static booleanDFLT_MBEAN_APPEND_CLASS_LOADER_IDstatic LongDFLT_MIN_CHECKPOINTING_PAGE_BUFFER_SIZEMinimum checkpointing page buffer size (may be adjusted by Ignite).static StringDFLT_USER_VERSIONDefault user version.static Field[]EMPTY_FIELDSEmpty fields array.static int[]EMPTY_INTSEmpty integers array.static long[]EMPTY_LONGSEmpty longs array.static String[]EMPTY_STRSEmpty strings array.static UUID[]EMPTY_UUIDSstatic longGBstatic byte[]IGNITE_HEADERNetwork packet header.static StringIGNITE_JMX_REMOTE_PROPERTYJMX remote system property.static StringIGNITE_LOG_DIRIgnite Logging Directory.static booleanIGNITE_MBEANS_DISABLEDIgnite MBeans disabled flag.static StringIGNITE_PKGIgnite package.static StringIGNITE_SUCCESS_FILE_PROPERTYSuccess file name property.static booleanIGNITE_TEST_FEATURES_ENABLEDIgnite test features enabled flag.static StringIGNITE_WORK_DIRIgnite Work Directory.static IgniteUtils.InterfaceSupplierINTERFACE_SUPPLIERSupplier of network interfaces.static StringJMX_DOMAINJMX domain as 'xxx.apache.ignite'.static longKBstatic StringLOC_IGNITE_NAME_EMPTYEmpty local Ignite name.static DateTimeFormatterLONG_DATE_FMTLong date format pattern for log messages.static StringMAC_INVALID_ARG_MSGMAC OS invalid argument socket error message.static longMBstatic intNUMBER_FILE_NAME_LENGTHLength of numbered file name.static DateTimeFormatterSHORT_DATE_FMTShort date format pattern for log messages in "quiet" mode.static StringTHREAD_DUMP_MSGThread dump message.static intUTF_BYTE_LIMITString limit in bytes forDataOutput.writeUTF(java.lang.String)andDataInput.readUTF(), that use "Modified UTF-8".
-
Constructor Summary
Constructors Constructor Description IgniteUtils()
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static SocketacceptServerSocket(ServerSocket srvrSock)InvokesServerSocket.accept()method on the passed server socked, working around the https://bugs.openjdk.java.net/browse/JDK-8247750 in the process.static voidacquire(Semaphore sem)Acquires a permit from provided semaphore.static int[]addAll(int[] arr1, int[] arr2)static <V,C extends Collection<? super V>>
CaddAll(C c, V... vals)Adds values to collection and returns the same collection to allow chaining.static <K,V,M extends Map<K,V>>
MaddAll(M m, Map.Entry<K,V>... entries)Adds values to collection and returns the same collection to allow chaining.static <K,V,M extends Map<K,V>>
MaddAll(M m, IgniteBiTuple<K,V>... entries)Adds values to collection and returns the same collection to allow chaining.static Collection<Handler>addJavaNoOpLogger()Adds no-op console handler for root java logger.static booleanaddLastCause(@Nullable Throwable e, @Nullable Throwable cause, IgniteLogger log)Adds cause to the end of cause chain.static StringaddressesAsString(Collection<String> addrs, Collection<String> hostNames)Returns string representation of addresses.static StringaddressesAsString(ClusterNode node)Returns string representation of node addresses.static <T extends Throwable>
TaddSuppressed(T root, T err)Utility method to add the given throwable error to the given throwable root error.static longadjustedWalHistorySize(DataStorageConfiguration dsCfg, @Nullable IgniteLogger log)Calculates maximum WAL archive size based on maximum checkpoint buffer size, if the default value ofDataStorageConfiguration.getMaxWalArchiveSize()is not overridden.static Collection<Class<?>>allInterfaces(Class<?> cls)Provides all interfaces ofclsincluding inherited ones.static Collection<String>allLocalIps()Gets a list of all local non-loopback IPs known to this JVM.static Collection<String>allLocalMACs()Gets a list of all local enabled MACs known to this JVM.static List<PluginProvider>allPluginProviders()Gets all plugin providers.static List<PluginProvider>allPluginProviders(IgniteConfiguration cfg, boolean includeClsPath)Gets all plugin providers.static booleanalphanumericUnderscore(String s)static intarrayCopy(byte[] src, int off, byte[] resBuf, int resOff, int len)static <T extends R,R>
List<R>arrayList(Collection<T> c)static <T extends R,R>
List<R>arrayList(Collection<T> c, @Nullable IgnitePredicate<? super T>... p)static <T extends R,R>
List<R>arrayList(Iterator<T> c, int cap, @Nullable IgnitePredicate<? super T>... p)static <T> Iterable<T>asIterable(Enumeration<T> e)Converts enumeration to iterable so it can be used inforeachconstruct.static booleanassertionsEnabled()static voidassertParameter(boolean cond, String condDesc)Throws exception with uniform error message if given parameter's assertion condition isfalse.static voidasyncLogError(IgniteInternalFuture<?> f, IgniteLogger log)Adds listener to asynchronously log errors.static intavailableThreadCount(GridKernalContext ctx, byte plc, int reserved)static voidawait(CountDownLatch latch)Awaits for the latch.static booleanawait(CountDownLatch latch, long timeout, TimeUnit unit)Awaits for the latch.static voidawait(Condition cond)Awaits for condition.static booleanawait(Condition cond, long time, TimeUnit unit)Awaits for condition.static voidawaitForWorkersStop(Collection<GridWorker> workers, boolean cancel, @Nullable IgniteLogger log)Stops workers from given collection and waits for their completion.static voidawaitQuiet(CountDownLatch latch)Awaits for the latch until it is counted down, ignoring interruptions.static voidawaitQuiet(CyclicBarrier barrier)Awaits for the barrier ignoring interruptions.static voidawaitQuiet(Condition cond)Awaits for condition ignoring interrupts.static @Nullable Class<?>box(@Nullable Class<?> cls)Gets wrapper class for a primitive type.static IgniteFuture<Void>broadcastToNodesWithFilterAsync(GridKernalContext kctx, IgniteRunnable job, boolean srvrsOnly, IgnitePredicate<ClusterNode> nodeFilter)Broadcasts given job to nodes that match filter.static StringbyteArray2HexString(byte[] arr)Converts byte array to hex string.static StringbyteArray2HexString(byte[] arr, boolean toUpper)Converts byte array to hex string.static StringbyteArray2String(byte[] arr, String hdrFmt, String bodyFmt)Converts byte array to formatted string.static booleanbytesEqual(byte[] a, int aOff, byte[] b, int bOff, int len)Compares fragments of byte arrays.static doublebytesToDouble(byte[] bytes, int off)Constructs double from byte array.static floatbytesToFloat(byte[] bytes, int off)Constructs float from byte array.static IgniteUuidbytesToIgniteUuid(byte[] in, int off)Converts bytes toIgniteUuid.static intbytesToInt(byte[] bytes, int off)Constructsintfrom byte array.static longbytesToLong(byte[] bytes, int off)Constructslongfrom byte array.static shortbytesToShort(byte[] bytes, int off)Constructsshortfrom byte array.static UUIDbytesToUuid(byte[] bytes, int off)Reads anUUIDform byte array.static GridCacheAttributes[]cacheAttributes(ClusterNode n)Gets cache attributes for the node.static StringcalculateMD5(InputStream in)Calculate MD5 string.static byte[]calculateMD5Digest(@NotNull InputStream in)Calculate MD5 digits.static int[]calculateOptimalBatchSizes(int parallelismLvl, int size)Split number of tasks into optimized batches.static voidcancel(@Nullable GridWorker w)Cancels given runnable.static voidcancel(Iterable<? extends GridWorker> ws)Cancels collection of runnables.static intcapacity(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).static IgniteCheckedExceptioncast(Throwable t)Casts the passedThrowable ttoIgniteCheckedException.
Iftis aGridClosureException, it is unwrapped and then cast toIgniteCheckedException.static intceilPow2(int v)Gets nearest power of 2 larger or equal than v.static longcheckpointBufferSize(DataRegionConfiguration regCfg)Get checkpoint buffer size for the given configuration.static booleanclassCannotBeLoadedByName(Class<?> objectClass)Returnstrueif class can not be loaded by name.static @Nullable Class<?>classForName(@Nullable String cls, @Nullable Class<?> dflt)Gets class for the given name if it can be loaded or default given class.static @Nullable Class<?>classForName(@Nullable String cls, @Nullable Class<?> dflt, boolean includePrimitiveTypes)Gets class for the given name if it can be loaded or default given class.static URL[]classLoaderUrls(ClassLoader clsLdr)Returns URLs of class loaderstatic StringclassNameToResourceName(String clsName)Gets resource path for the class.static voidclearClassCache()Completely clears class cache.static voidclearClassCache(ClassLoader ldr)Clears class cache for provided loader.static voidclearClassFromClassCache(ClassLoader ldr, String clsName)Clears class associated with provided class loader from class cache.static voidclose(@Nullable AutoCloseable rsrc, @Nullable IgniteLogger log)Closes given resource logging possible checked exception.static voidclose(@Nullable DatagramSocket rsrc)Closes given resource.static voidclose(@Nullable Socket sock, @Nullable IgniteLogger log)Closes given socket logging possible checked exception.static voidclose(@Nullable URLClassLoader clsLdr, @Nullable IgniteLogger log)Closes class loader logging possible checked exception.static voidclose(@Nullable SelectionKey rsrc, @Nullable IgniteLogger log)Closes given resource logging possible checked exceptions.static voidclose(@Nullable Selector rsrc, @Nullable IgniteLogger log)Closes given resource logging possible checked exception.static voidclose(@Nullable Context rsrc, @Nullable IgniteLogger log)Closes given resource logging possible checked exception.static voidcloseQuiet(@Nullable AutoCloseable rsrc)Quietly closes given resource ignoring possible checked exception.static voidcloseQuiet(@Nullable Socket sock)Quietly closes givenSocketignoring possible checked exception.static voidcloseQuiet(@Nullable SelectionKey rsrc)Quietly closes given resource ignoring possible checked exceptions.static voidcloseQuiet(@Nullable Selector rsrc)Quietly closes given resource ignoring possible checked exception.static voidcloseQuiet(@Nullable Context rsrc)Quietly closes given resource ignoring possible checked exception.static voidcloseWithSuppressingException(@Nullable AutoCloseable rsrc, @NotNull Exception e)Closes given resource suppressing possible checked exception.static Stringcompact(String s)Replaces all occurrences oforg.apache.ignite.witho.a.i.,org.apache.ignite.internal.witho.a.i.i.,org.apache.ignite.internal.visor.witho.a.i.i.v.andstatic intcompareVersionNumbers(@Nullable String v1, @Nullable String v2)Compare java implementation versionstatic intconcurrentMapSegment(int hash, int concurLvl)static StringconsistentId(Collection<String> addrs)static StringconsistentId(Collection<String> addrs, int port)static booleancontainsAll(Map<?,?> base, Map<?,?> map)Checks if the map passed in is contained in base map.static booleancontainsIntArray(int[] arr, int val)Checks for containment of the value in the array.static booleancontainsObjectArray(@Nullable Object[] arr, Object val, @Nullable Object... vals)Checks for containment of the value in the array.static booleancontainsStringArray(String[] arr, @Nullable String val, boolean ignoreCase)Checks for containment of given string value in the specified array.static booleancontainsStringCollection(Iterable<String> c, @Nullable String val, boolean ignoreCase)Checks for containment of given string value in the specified collection.static IgniteUuidcontextDeploymentClassLoaderId(GridKernalContext ctx)Returns Deployment class loader id if method was invoked in the job context (it may be the context of a cache's operation which was triggered by the distributed job) ornullif no context was found or Deployment is switched off.static IgniteExceptionconvertException(IgniteCheckedException e)static ExceptionconvertExceptionNoWrap(IgniteCheckedException e)Converts exception, but unlikeconvertException(IgniteCheckedException)does not wrap passed in exception if none suitable converter found.static <T> Collection<T>convertToSingletonList(Collection<T> col)static voidcopy(File src, File dest, boolean overwrite)Copy source file (or folder) to destination file (or folder).static intcopy(InputStream in, OutputStream out)Copies input byte stream to output byte stream.static intcopy(Reader in, Writer out)Copies input character stream to output character stream.static int[]copyIfExceeded(int[] arr, int len)Copies array only if array length greater than needed length.static <K,V>
Map<K,V>copyMap(Map<K,V> m)static byte[]copyMemory(long ptr, int size)static voidcourtesy(@Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message inorg.apache.ignite.CourtesyConfigNoticecategory.static voidcourtesy(@Nullable IgniteLogger log, Object longMsg, Object shortMsg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message inorg.apache.ignite.CourtesyConfigNoticecategory.static CiphercreateCipher(Key key, int encMode)static @Nullable MethodctorFactory()Return SUN specific constructor factory.static longcurrentTimeMillis()static StringcustomDirectoryLogFileName(@Nullable String dir, String fileName)Substitutes log directory with a custom one.static Stringdash(int len)Makes a'+---+'dash line.static booleandeadlockPresent()static voiddebug(Object msg)Deprecated.Calls to this method should never be committed to master.static voiddebug(IgniteLogger log, String msg)Deprecated.Calls to this method should never be committed to master.static voiddebugHeapUsage()Prints heap usage.static voiddebugStack(IgniteLogger log, String msg)Deprecated.Calls to this method should never be committed to master.static voiddebugx(String msg)Deprecated.Calls to this method should never be committed to master.static byte[]decodeHex(char[] data)Converts an array of characters representing hexidecimal values into an array of bytes of those same values.static StringdefaultWorkDirectory()Get default work directory.static booleandelete(@Nullable File file)Deletes file or directory with all sub-directories and files.static booleandelete(Path path)Deletes file or directory with all sub-directories and files.static ClassLoaderdeploymentClassLoader(GridKernalContext ctx, IgniteUuid ldrId)Gets that deployment class loader matching by the specific id, ornullif the class loader was not found.static Class<?>detectClass(Object obj)Tries to detect user class from passed in object inspecting collections, arrays or maps.static ClassLoaderdetectClassLoader(Class<?> cls)Detects class loader for given class.static @Nullable ClassLoaderdetectObjectClassLoader(@Nullable Object obj)Detects class loader for given object's class.static GridPeerDeployAwaredetectPeerDeployAware(GridPeerDeployAware obj)Unwraps top level user class for wrapped objects.static int[]difference(int[] a, int aLen, int[] b, int bLen)Returns array which is the difference between two arrays (array of elements contained in first array but not contained in second).static longdirSize(Path path)Will calculate the size of a directory.static booleandiscoOrdered(DiscoverySpi discoSpi)static <T,R>
Collection<R>doInParallel(int parallelismLvl, ExecutorService executorSvc, Collection<T> srcDatas, IgniteThrowableFunction<T,R> operation)Execute operation on data in parallel.static <T,R>
Collection<R>doInParallel(ExecutorService executorSvc, Collection<T> srcDatas, IgniteThrowableFunction<T,R> operation)Execute operation on data in parallel.static <T,R>
Collection<R>doInParallelUninterruptibly(int parallelismLvl, ExecutorService executorSvc, Collection<T> srcDatas, IgniteThrowableFunction<T,R> operation)Execute operation on data in parallel uninterruptibly.static byte[]doubleToBytes(double d)Converts primitive double to byte array.static intdoubleToBytes(double d, byte[] bytes, int off)Converts primitivedoubletype to byte array and stores it in the specified byte array.static FiledownloadUrl(URL url, File file)Downloads resource by URL.static voiddumpStack()Deprecated.Calls to this method should never be committed to master.static voiddumpStack(@Nullable IgniteLogger log, String msg)static voiddumpStack(String msg)Deprecated.Calls to this method should never be committed to master.static voiddumpStack(String msg, PrintStream out)Deprecated.Calls to this method should never be committed to master.static voiddumpStack(Thread t)Deprecated.Calls to this method should never be committed to master.static voiddumpStack(Thread t, PrintStream s)Deprecated.Calls to this method should never be committed to master.static voiddumpThreads(@Nullable IgniteLogger log)Performs thread dump and prints all available info to the given log with WARN logging level.static voiddumpThreads(@Nullable IgniteLogger log, boolean isErrorLevel)Performs thread dump and prints all available info to the given log with WARN or ERROR logging level depending onisErrorLevelparameter.static ClusterGroupEmptyCheckedExceptionemptyTopologyException()Creates appropriate empty projection exception.static voidenhanceThreadName(@Nullable Thread thread, String text)Puts additional text to thread name.static voidenhanceThreadName(String text)Puts additional text to thread name.static voidensureDirectory(File dir, String msg, IgniteLogger log)Checks if the given directory exists and attempts to create one if not.static voidensureDirectory(Path dir, String msg, IgniteLogger log)Checks if the given directory exists and attempts to create one if not.static longensurePositive(long i, long dflt)Whenlongvalue given is positive returns that value, otherwise returns provided default value.static voiderror(@Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log ERROR message.static voiderror(@Nullable IgniteLogger log, Object shortMsg, @Nullable Throwable e)static voiderror(@Nullable IgniteLogger log, Object longMsg, Object shortMsg, @Nullable Throwable e)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log ERROR message.static IgniteCheckedExceptionexceptionWithSuppressed(String msg, @Nullable Collection<Throwable> suppressed)CreatesIgniteCheckedExceptionwith the collection of suppressed exceptions.static StringextendToLen(String s, int targetLen)Appends spaces to end of input string for extending to needed length.static <T> Tfield(Class<?> cls, String fieldName)Gets field value.static <T> Tfield(Object obj, String fieldName)Gets field value.static longfieldOffset(Class<?> cls, String fieldName)Gets object field offset.static intfileCount(Path dir)Return count of regular file in the directory (including in sub-directories)static Stringfiller(int len, char ch)static List<InetAddress>filterReachable(Collection<InetAddress> addrs)static @Nullable FieldfindField(Class<?> cls, String name)static @Nullable MethodfindInheritableMethod(Class<?> cls, String name, Class<?>... paramTypes)Finds a non-static and non-abstract method from the class it parents.static @Nullable MethodfindNonPublicMethod(Class<?> cls, String name, Class<?>... paramTypes)Finds a method in the class and it parents.static <T> TfirstNotNull(@Nullable T... vals)Returns a first non-null value in a given array, if such is present.static longfixedLengthFileNumber(String fileName)static StringfixedLengthNumberName(long num, @Nullable String ext)Generates file name from index.static PatternfixedLengthNumberNamePattern(@Nullable String ext)static Stringfl(String msg, Object... args)Creates string for log output.static byte[]floatToBytes(float f)Converts primitive float to byte array.static intfloatToBytes(float f, byte[] bytes, int off)Converts primitive float to byte array.static @Nullable Constructor<?>forceEmptyConstructor(Class<?> cls)Gets empty constructor for class even if the class does not have empty constructor declared.static <T> TforceNewInstance(Class<?> cls)Creates new instance of a class even if it does not have public constructor.static Stringformat(long sysTime)Formats system time in milliseconds for printing in logs.static StringformatMins(long mins)Pretty-formatting for minutes.static Class<?>forName(String clsName, @Nullable ClassLoader ldr)Gets class for provided name.static Class<?>forName(String clsName, @Nullable ClassLoader ldr, IgnitePredicate<String> clsFilter)Gets class for provided name.static Class<?>forName(String clsName, @Nullable ClassLoader ldr, IgnitePredicate<String> clsFilter, boolean useCache)Gets class for provided name.static GridIntIteratorforRange(int start, int cnt)ReturnsGridIntIteratorfor range of primitive integers.static <T> TfromBytes(byte[] data)Deserialize object from byte array.static <T> Tget(Future<T> fut)Gets result from the given future with right exception handling.static <T extends Annotation>
TgetAnnotation(Class<?> cls, Class<T> annCls)Gets annotation for a class.static BaselineTopologygetBaselineTopology(@NotNull GridKernalContext ctx)static BaselineTopologygetBaselineTopology(@NotNull GridCacheContext cctx)static BaselineTopologygetBaselineTopology(@NotNull GridCacheSharedContext cctx)static <T> TgetByIndex(Collection<T> vals, int idx)Gets collection value by index.static CompilationMXBeangetCompilerMx()Gets compilation MBean.static @Nullable StringgetCurrentIgniteName()Get current Ignite name.static <T extends Annotation>
TgetDeclaredAnnotation(Class<?> cls, Class<T> annCls)Gets declared annotation for a class.static C1<IgniteCheckedException,IgniteException>getExceptionConverter(Class<? extends IgniteCheckedException> clazz)Gets IgniteClosure for an IgniteCheckedException class.static @Nullable StringgetIgniteHome()RetrievesIGNITE_HOMEproperty.static InetAddressgetLocalHost()Gets local host.static MemoryMXBeangetMemoryMx()Gets memory MBean.static @Nullable StringgetNetworkInterfaceName(String addr)Gets display name of the network interface this IP address belongs to.static @Nullable MethodgetNonPublicMethod(Class<?> cls, String name, Class<?>... paramTypes)Gets a method from the class.static OperatingSystemMXBeangetOsMx()Gets OS MBean.static StringgetResourceName(Class rscCls)Gets resource name.static RuntimeMXBeangetRuntimeMx()Gets runtime MBean.static StringgetSimpleName(Class<?> cls)Gets simple class name taking care of empty names.static StringgetTaskName(Class<? extends ComputeTask<?,?>> taskCls)Gets task name for the given task class.static ThreadMXBeangetThreadMx()Gets threading MBean.static longgetTotalMemoryAvailable()Gets amount of RAM memory available on this machine.static ClassLoadergridClassLoader()static StringgridEventName(int type)Gets name for given grid event type.static int[]gridEvents(int... excl)Gets all event types.static Collection<UUID>gridIds(@Nullable Collection<? extends Ignite> grids)Converts collection of Grid instances to collection of node IDs.static Collection<String>grids2names(@Nullable Collection<? extends Ignite> grids)Converts collection of Grid instances to collection of grid names.static <T extends Annotation>
booleanhasAnnotation(Class<?> cls, Class<T> annCls)Indicates if class has given annotation.static <T extends Annotation>
booleanhasAnnotation(Object o, Class<T> annCls)Indicates if class has given annotation.static <T extends Annotation>
booleanhasDeclaredAnnotation(Class<?> cls, Class<T> annCls)Indicates if class has given declared annotation.static <T extends Annotation>
booleanhasDeclaredAnnotation(Object o, Class<T> annCls)Indicates if class has given annotation.static booleanhasField(Object obj, String fieldName)Check that field exist.static inthash(int h)Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions.static inthash(long key)A primitive override ofhash(Object)to avoid unnecessary boxing.static inthash(Object key)Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions.static inthashCode(Object obj)Calculate a hashCode for an array.static inthashCode(ByteBuffer... bufs)Calculates hash code for the given byte buffers contents.static inthashToIndex(int hash, int size)Maps object hash to some index between 0 and specified size via modulo operation.static booleanhasNearCache(ClusterNode n, String cacheName)Checks if given node has near cache enabled for the specified partitioned cache.static booleanhasParent(@Nullable ClassLoader parent, ClassLoader ldr)static doubleheapSize(int precision)Returns current JVM maxMemory in the same format asheapSize(ClusterNode, int).static doubleheapSize(Iterable<ClusterNode> nodes, int precision)Gets total heap size in GB rounded to specified precision.static doubleheapSize(ClusterNode node, int precision)Gets heap size in GB rounded to specified precision.static StringhexInt(int val)Gets a hex string representation of the given long value.static StringhexLong(long val)Gets a hex string representation of the given long value.static byte[]hexString2ByteArray(String hex)Convert string with hex values to byte array.static @Nullable StringhidePassword(@Nullable String uri)Replace password in URI string with a single '*' character.static StringhumanReadableByteCount(long bytes)Converts count of bytes to a human-readable format.static StringhumanReadableDuration(long millis)Converts duration to a human-readable format.static IgniteClosure<UUID,ClusterNode>id2Node(GridKernalContext ctx)static Stringid8(UUID id)Gets 8-character substring of UUID (for terse logging).static Stringid8(IgniteUuid id)Gets 8-character substring ofIgniteUuid(for terse logging).static byte[]igniteUuidToBytes(IgniteUuid uuid)ConvertsIgniteUuidto bytes.static voidigniteUuidToBytes(IgniteUuid uuid, byte[] out, int off)ConvertsIgniteUuidto bytes.static booleaninClassPath(String clsName)Check whether class is in classpath.static Comparator<InetSocketAddress>inetAddressesComparator(boolean sameHost)Returns comparator that sorts remote node addresses.static IgniteLoggerinitLogger(@Nullable IgniteLogger cfgLog, @Nullable String app, @Nullable UUID nodeId, String workDir)static IgniteLoggerinitLogger(IgniteConfiguration cfg, String app)static voidinitWorkDir(IgniteConfiguration cfg)Resolves work directory.static voidinterrupt(@Nullable Thread t)Convenience method that interrupts a given thread if it's notnull.static voidinterrupt(Iterable<? extends Thread> workers)Convenience method that interrupts a given thread if it's notnull.static byte[]intToBytes(int i)Converts primitiveinttype to byte array.static intintToBytes(int i, byte[] bytes, int off)Converts primitiveinttype to byte array and stores it in specified byte array.static <T> Tinvoke(@Nullable Class<?> cls, @Nullable Object obj, String mtdName, Class[] paramTypes, Object... params)Invokes method.static <T> Tinvoke(@Nullable Class<?> cls, @Nullable Object obj, String mtdName, Object... params)Invokes method.static booleanisCurrentIgniteNameSet(@Nullable String name)Check if current Ignite name is set.static booleanisEnum(Class cls)Check if given class represents a Enum.static booleanisEqualsMethod(Method mtd)static booleanisFinal(Class<?> cls)static booleanisFlagSet(int flags, int flag)Check if flag set.static booleanisGrid(Class<?> cls)Checks if given class is ofGridtype.static booleanisHashCodeMethod(Method mtd)static booleanisHotSpot()Indicates whether HotSpot VM is used.static booleanisIgnite(Class<?> cls)Checks if given class is ofIgnitetype.static booleanisIncreasingArray(int[] arr, int len)Checks if array prefix increases.static booleanisJavaVersionAtLeast(String v)Compare running Java Runtime version withvstatic booleanisJdk(Class<?> cls)Check if given class is of JDK type.static booleanisJmxRemoteEnabled()static booleanisLambda(Class<?> objectClass)Returnstrueif class is a lambda.static booleanisLinux()Indicates whether current OS is Linux flavor.static booleanisLoadableBy(String clsName, @Nullable ClassLoader ldr)Tests whether or not given class is loadable provided class loader.static booleanisLocalAddress(InetAddress addr)Checks if the address is local.static booleanisLocalHostChanged()Determines whether current local host is different from previously cached.static booleanisLocalNodeCoordinator(GridDiscoveryManager discoMgr)static booleanisMacInvalidArgumentError(Exception e)Checks if error is MAC invalid argument error which ususally requires special handling.static booleanisMacOs()Indicates whether current OS is Mac OS.static booleanisNetWare()Indicates whether current OS is Netware.static booleanisNonDecreasingArray(int[] arr, int len)Checks if array prefix do not decreases.static booleanisOldestNodeVersionAtLeast(IgniteProductVersion ver, Iterable<ClusterNode> nodes)Check that node Ignite product version is not less then specified.static booleanisPow2(int i)static booleanisPrimitiveArray(Object obj)Checks if object is a primitive array.static booleanisPrimitiveOrWrapper(Class<?> cls)static booleanisRedHat()static booleanisRestartEnabled()static booleanisRestEnabled(IgniteConfiguration cfg)static booleanisSolaris()Indicates whether current OS is Solaris.static booleanisSolarisSparc()Indicates whether current OS is Solaris on Spark box.static booleanisSolarisX86()Indicates whether current OS is Solaris on x86 box.static booleanisToStringMethod(Method mtd)static booleanisTxAwareQueriesEnabled(GridKernalContext kctx)static booleanisUnix()Indicates whether current OS is UNIX flavor.static booleanisVisorNodeStartProperty(String name)Checks whether property is one added by Visor when node is started via remote SSH session.static booleanisVisorRequiredProperty(String name)Checks whether property is one required by Visor to work correctly.static booleanisWindows()Indicates whether current OS is Windows.static booleanisWindows2003()Indicates whether current OS is Windows Server 2003.static booleanisWindows2008()Indicates whether current OS is Windows Server 2008.static booleanisWindows2k()Indicates whether current OS is Windows 2000.static booleanisWindows7()Indicates whether current OS is Windows 7.static booleanisWindows8()Indicates whether current OS is Windows 8.static booleanisWindows81()Indicates whether current OS is Windows 8.1.static booleanisWindows95()Indicates whether current OS is Windows 95.static booleanisWindows98()Indicates whether current OS is Windows 98.static booleanisWindowsNt()Indicates whether current OS is Windows NT.static booleanisWindowsVista()Indicates whether current OS is Windows Vista.static booleanisWindowsXp()Indicates whether current OS is Windows XP.static StringjdkName()Gets JDK name.static StringjdkString()Gets JDK string.static StringjdkVendor()Gets JDK vendor.static StringjdkVersion()Gets JDK version.static JMExceptionjmException(Throwable e)Utility method creatingJMExceptionwith given cause.static byte[]join(byte[]... bufs)Join byte arrays into single one.static voidjoin(@Nullable Thread t)Joins thread.static booleanjoin(@Nullable Thread t, @Nullable IgniteLogger log)Waits for completion of a given thread.static booleanjoin(@Nullable Thread t, @Nullable IgniteLogger log, long timeout)Waits for completion of a given thread.static booleanjoin(@Nullable GridWorker w, @Nullable IgniteLogger log)Joins runnable.static booleanjoin(Iterable<? extends GridWorker> ws, IgniteLogger log)Joins given collection of runnables.static voidjoin(GridWorker w)Joins worker.static booleanjoinThreads(Iterable<? extends Thread> workers, @Nullable IgniteLogger log)Waits for completion of a given threads.static StringjreName()Gets Java Runtime name.static StringjreVersion()Gets Java Runtime version.static booleanjvm32Bit()Does a best effort to detect if we a running on a 32-bit JVM.static List<String>jvmArgs()static StringjvmName()Gets JVM implementation name.static intjvmPid()static StringjvmSpec()Gets JVM specification name.static StringjvmVendor()Gets JVM implementation vendor.static StringjvmVersion()Gets JVM implementation version.static @Nullable StringlambdaEnclosingClassName(String clsName)Extracts full name of enclosing class from JDK8 lambda class name.static Stringlanguage(ClassLoader ldr)static <K,V>
Map<K,V>limitedMap(int limit)Creates new map that limited by size.static <S> Iterable<S>loadService(Class<S> svcCls)static voidlog(@Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log INF0 message.static voidlog(@Nullable IgniteLogger log, Object longMsg, Object shortMsg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log INFO message.static IgniteLoggerlogger(GridKernalContext ctx, AtomicReference<IgniteLogger> logRef, Class<?> cls)Initializes logger into/from log reference passed in.static IgniteLoggerlogger(GridKernalContext ctx, AtomicReference<IgniteLogger> logRef, Object obj)Initializes logger into/from log reference passed in.static byte[]longToBytes(long l)Converts primitivelongtype to byte array.static intlongToBytes(long l, byte[] bytes, int off)Converts primitivelongtype to byte array and stores it in specified byte array.static intmajorJavaVersion(String verStr)Get major Java version from string.static ObjectNamemakeMBeanName(@Nullable String igniteInstanceName, @Nullable String grp, String name)Constructs JMX object name with given properties.static ObjectNamemakeMBeanName(@Nullable String igniteInstanceName, @Nullable String grp, List<String> grps, String name)Constructs JMX object name with given properties.static <K,V>
Map<K,V>map(K k, V v)Create a map with single key-value pair.static <K,V>
Map<K,V>map(K k1, V v1, K k2, V v2)Create a map with two key-value pairs.static <K,V>
Map<K,V>map(K k1, V v1, K k2, V v2, K k3, V v3)Create a map with three key-value pairs.static byte[]marshal(GridKernalContext ctx, Object obj)Marshals object to byte array.static byte[]marshal(GridCacheSharedContext ctx, Object obj)Marshals object to byte array.static voidmarshal(Marshaller marsh, @Nullable Object obj, OutputStream out)Marshals object to byte array.static byte[]marshal(Marshaller marsh, Object obj)Marshals object to byte array.static StringmaskForFileName(CharSequence name)Masks name for a valid directory path.static StringmaskName(@Nullable String name)Mask component name to make sure that it is notnull.static <T extends Comparable<? super T>>
Tmax(T t0, T t1)static longmillisSinceNanos(long nanos)Returns number of milliseconds passed after the given nanos timestamp.static longmillisToNanos(long millis)Convert milliseconds time interval to nanoseconds.static booleanmkdirs(File dir)static longnanosToMillis(long nanos)Convert nanoseconds time interval to milliseconds.static intnearestPow2(int x)static intnearestPow2(int x, boolean less)static Map<String,Collection<ClusterNode>>neighborhood(Iterable<ClusterNode> nodes)Groups given nodes by the node's physical computer (host).static <K,V>
HashMap<K,V>newHashMap(int expSize)Creates newHashMapwith expected size.static <T> HashSet<T>newHashSet(int expSize)Creates newHashSetwith expected size.static <X> Set<X>newIdentityHashSet()static <T> TnewInstance(Class<T> cls)Creates new instance of a class only if it has an empty constructor (can be non-public).static <T> TnewInstance(String cls)Creates new instance of a class only if it has an empty constructor (can be non-public).static <K,V>
LinkedHashMap<K,V>newLinkedHashMap(int expSize)Creates newLinkedHashMapwith expected size.static <T> LinkedHashSet<T>newLinkedHashSet(int expSize)Creates newLinkedHashSetwith expected size.static intnextPowerOf2(int v)Round up the argument to the next highest power of 2;static Stringnl()static StringnodeIdLogFileName(UUID nodeId, String fileName)Attaches node ID to log file name.static Collection<UUID>nodeIds(@Nullable Collection<? extends ClusterNode> nodes)Converts collection of nodes to collection of node IDs.static Collection<String>nodes2names(@Nullable Collection<? extends ClusterNode> nodes)Converts collection of grid nodes to collection of grid names.static <T> voidnotifyListeners(T t, Collection<Consumer<T>> lsnrs, IgniteLogger log)Notifies providedlsnrswith the valuet.static voidnullifyHomeDirectory()Nullifies Ignite home directory.static ConstructorobjectConstructor()static doubleoffheapSize(Iterable<ClusterNode> nodes, int precision)Gets total offheap size in GB rounded to specified precision.static ClusterNodeoldest(Collection<ClusterNode> c, @Nullable IgnitePredicate<ClusterNode> p)Gets oldest node out of collection of nodes.static voidonGridStart()Starts clock timer if grid is first.static voidonGridStop()Stops clock timer if all nodes into JVM were stopped.static StringosArchitecture()Gets OS CPU-architecture.static StringosJdkString()Gets OS JDK string.static StringosName()Gets underlying OS name.static StringosString()Gets OS string.static StringosVersion()Gets underlying OS version.static booleanoverridesEqualsAndHashCode(Class<?> cls)static booleanoverridesEqualsAndHashCode(Object obj)static booleanp2pLoader(ClassLoader ldr)Checks if class loader is an internal P2P class loader.static booleanp2pLoader(Object o)Checks if class loader is an internal P2P class loader.static StringpackageName(Class<?> cls)static Stringpad(int len)Creates space filled string of given length.static GridPeerDeployAwarepeerDeployAware(Object obj)Creates an instance ofGridPeerDeployAwarefor object.static GridPeerDeployAwarepeerDeployAware0(@Nullable Iterable<?> c)Gets the peer deploy aware instance for the object with the widest class loader.static GridPeerDeployAwarepeerDeployAware0(@Nullable Object... c)Gets the peer deploy aware instance for the object with the widest class loader.static GridPeerDeployAwarepeerDeployAware0(Object obj)Creates an instance ofGridPeerDeployAwarefor object.static <K,V>
voidprintConcurrentHashMapInfo(ConcurrentHashMap<K,V> map)static voidprintStackTrace(long threadId, GridStringBuilder sb)static IgniteProductVersionproductVersion(ClusterNode node)Gets node product version based on node attributes.static <T> Tproperty(Object obj, String propName)Gets property value.static voidquiet(boolean err, Object... objs)static voidquietAndInfo(IgniteLogger log, String msg)Prints out the message in quiet and info modes.static voidquietAndWarn(IgniteLogger log, Object msg)Logs warning message in both verbose and quiet modes.static voidquietAndWarn(IgniteLogger log, Object msg, @Nullable Throwable e)Logs warning message in both verbose and quiet modes.static voidquietAndWarn(IgniteLogger log, Object msg, Object shortMsg)Logs warning message in both verbose and quiet modes.static voidquietMultipleLines(boolean err, String multiline)static ClusterNoderandomServerNode(GridKernalContext ctx)static booleanreachable(InetAddress addr, int reachTimeout)Checks if address can be reached using one argument InetAddress.isReachable() version.static booleanreachable(NetworkInterface itf, InetAddress addr, int reachTimeout)Checks if address can be reached using three argument InetAddress.isReachable() version.static StringreadableSize(long bytes, boolean si)static @Nullable Object[]readArray(ObjectInput in)Reads array from input stream.static <T> @Nullable T[]readArray(ObjectInput in, Class<T> cls)Reads typed array from input stream.static @org.jetbrains.annotations.Nullable boolean[]readBooleanArray(DataInput in)Reads boolean array from input stream accounting for null values.static @org.jetbrains.annotations.Nullable byte[]readByteArray(DataInput in)Reads byte array from input stream accounting for null values.static byte[]readByteArray(ByteBuffer... bufs)Reads byte array from given buffers (changing buffer positions).static @Nullable List<Byte>readByteList(DataInput in)// FIXME: added for DR dataCenterIds, review if it is needed after GG-6879.static List<byte[]>readBytesList(DataInput in)Reads collection of byte arrays from data input.static @Nullable Class<?>[]readClassArray(ObjectInput in)Reads array from input stream.static <E> @Nullable Collection<E>readCollection(ObjectInput in)static <E extends Enum<E>>
EreadEnum(DataInput in, Class<E> enumCls)static StringreadFileToString(String fileName, String charset)Reads file to string using specified charset.static <K,V>
@Nullable HashMap<K,V>readHashMap(ObjectInput in)Read hash map.static @Nullable IgniteUuidreadIgniteUuid(DataInput in)ReadsIgniteUuidfrom input stream.static @Nullable List<IgniteUuid>readIgniteUuids(DataInput in)Reads Ignite UUIDs from input stream.static @org.jetbrains.annotations.Nullable int[]readIntArray(DataInput in)Reads int array from input stream accounting for null values.static @Nullable Collection<Integer>readIntCollection(DataInput in)static @Nullable Map<Integer,Integer>readIntKeyIntValueMap(DataInput in)static <V> @Nullable Map<Integer,V>readIntKeyMap(ObjectInput in)static @Nullable List<Integer>readIntList(DataInput in)static @Nullable Set<Integer>readIntSet(DataInput in)static <K,V>
@Nullable LinkedHashMap<K,V>readLinkedMap(ObjectInput in)static <E> @Nullable List<E>readList(ObjectInput in)static @org.jetbrains.annotations.Nullable long[]readLongArray(DataInput in)Reads long array from input stream.static @Nullable StringreadLongString(DataInput in)Reads string from input stream accounting fornullvalues.static <K,V>
@Nullable Map<K,V>readMap(ObjectInput in)static <E> @Nullable Set<E>readSet(ObjectInput in)static @Nullable StringreadString(DataInput in)Reads string from input stream accounting fornullvalues.static Map<String,String>readStringMap(DataInput in)Reads string-to-string map written bywriteStringMap(DataOutput, Map).static <K,V>
@Nullable TreeMap<K,V>readTreeMap(ObjectInput in)static StringreadUTF(DataInput in)Read UTF string which can benull.static @Nullable UUIDreadUuid(DataInput in)Reads UUID from input stream.static @Nullable UUIDreadUuid(BinaryRawReader in)Reads UUID from binary reader.static @Nullable List<UUID>readUuids(DataInput in)Reads UUIDs from input stream.static <T> ObjectNameregisterMBean(MBeanServer mbeanSrv, @Nullable String igniteInstanceName, @Nullable String grp, String name, T impl, @Nullable Class<T> itf)Registers MBean with the server.static <T> ObjectNameregisterMBean(MBeanServer mbeanSrv, ObjectName name, T impl, Class<T> itf)Registers MBean with the server.static booleanrelaxDiscoveryOrdered()static voidreleaseQuiet(@Nullable FileLock lock)Quietly releases file lock ignoring all possible exceptions.static voidremoveJavaNoOpLogger(Collection<Handler> rmvHnds)Removes previously added no-op handler for root java logger.static Collection<InetSocketAddress>resolveAddresses(AddressResolver addrRslvr, Iterable<String> addrs, int port)Resolves all not loopback addresses and collect results.static Collection<InetSocketAddress>resolveAddresses(AddressResolver addrRslvr, Collection<InetSocketAddress> sockAddr)static ClassLoaderresolveClassLoader(ClassLoader ldr, IgniteConfiguration cfg)static ClassLoaderresolveClassLoader(IgniteConfiguration cfg)static @Nullable FileresolveIgnitePath(String path)Gets file associated with path.static @Nullable URLresolveIgniteUrl(String path)Gets URL representing the path passed in.static @Nullable URLresolveIgniteUrl(String path, boolean metaInf)Gets URL representing the path passed in.static IgniteBiTuple<Collection<String>,Collection<String>>resolveLocalAddresses(InetAddress locAddr)Returns host names consistent withresolveLocalHost(String).static IgniteBiTuple<Collection<String>,Collection<String>>resolveLocalAddresses(InetAddress locAddr, boolean allHostNames)Returns host names consistent withresolveLocalHost(String).static InetAddressresolveLocalHost(@Nullable String hostName)Tries to resolve host by name, returning local host if input is empty.static URLresolveSpringUrl(String springCfgPath)Resolve Spring configuration URL.static FileresolveWorkDirectory(String workDir, String path, boolean delIfExist)Resolves work directory.static FileresolveWorkDirectory(String workDir, String path, boolean delIfExist, boolean create)Resolves work directory.static voidrestoreDeploymentContext(GridKernalContext ctx, IgniteUuid ldrId)Restores a deployment context for cache deployment.static voidrestoreOldIgniteName(@Nullable String oldName, @Nullable String curName)Restore old Ignite name.static voidrollbackConnection(@Nullable Connection rsrc, @Nullable IgniteLogger log)Rollbacks JDBC connection logging possible checked exception.static voidrollbackConnectionQuiet(@Nullable Connection rsrc)Quietly rollbacks JDBC connection ignoring possible checked exception.static intsafeAbs(int i)Gets absolute value for integer.static longsafeAbs(long i)Gets absolute value for long.static booleansameMacs(ClusterNode loc, ClusterNode rmt)static <E> List<E>sealList(E... a)Convert array to seal list.static <E> List<E>sealList(Collection<E> c)Seal collection.static <K,V>
Map<K,V>sealMap(Map<K,V> m)static PathsearchFileRecursively(Path path, @NotNull String name)static @Nullable StringsetCurrentIgniteName(@Nullable String newName)Set current Ignite name.static voidsetIgniteHome(@Nullable String path)static byte[]shortToBytes(short s)Converts primitiveshorttype to byte array.static intshortToBytes(short s, byte[] bytes, int off)Converts primitiveshorttype to byte array and stores it in specified byte array.static voidshutdownNow(Class<?> owner, @Nullable ExecutorService exec, @Nullable IgniteLogger log)Shutdowns givenExecutorServiceand wait for executor service to stop.static intsizeInMegabytes(long sizeInBytes)Converts size in bytes to human-readable size in megabytes.static voidsleep(long ms)Sleeps for given number of milliseconds.static StringspiAttribute(IgniteSpi spi, String attrName)Creates SPI attribute name by adding prefix to the attribute name.static StringstackTrace()static voidstartLifecycleAware(Iterable<?> objs)For each object provided by the givenIterablechecks if it implementsLifecycleAwareinterface and executesLifecycleAware.start()method.static voidstartThreads(Iterable<? extends Thread> threads)Starts given threads.static <T> TstaticField(Class<?> cls, String fieldName)Gets static field value.static voidstopLifecycleAware(IgniteLogger log, Iterable<?> objs)For each object provided by the givenIterablechecks if it implementsLifecycleAwareinterface and executesLifecycleAware.stop()method.static intstripeIdx(int stripes, int grpId, int partId)static @Nullable ObjectsunReflectionFactory()SUN JDK specific reflection factory for objects without public constructor.static voidswap(Object[] arr, int a, int b)Swaps two objects in array.static StringthreadName(long threadId)static <T> T[]toArray(Collection<? extends T> c, T[] arr)Copies all elements from collection to array and asserts that array is big enough to hold the collection.static byte[]toBytes(Serializable obj)Serialize object to byte array.static inttoDigit(char ch, int idx)Converts a hexadecimal character to an integer.static StringtoHexString(long addr, int len)static StringtoHexString(ByteBuffer buf)static int[]toIntArray(@Nullable Collection<Integer> c)Converts collection of integers into array.static List<Integer>toIntList(@org.jetbrains.annotations.Nullable int[] arr, IgnitePredicate<Integer>... p)Converts array of integers into list.static longtoLong(int high, int low)Concats two integers to long.static long[]toLongArray(@Nullable Collection<Long> c)Converts collection of integers into array.static List<Long>toLongList(@org.jetbrains.annotations.Nullable long[] arr)Converts array of longs into list.static StringtoShortString(Collection<? extends ClusterNode> ns)Short node representation.static StringtoShortString(ClusterNode n)Short node representation.static Collection<InetSocketAddress>toSocketAddresses(Collection<String> addrs, Collection<String> hostNames, int port)Returns the list of resolved socket addresses.static Collection<InetSocketAddress>toSocketAddresses(ClusterNode node, int port)Returns the list of resolved socket addresses.static @Nullable StringtoStringSafe(@Nullable Object obj)Get string representation of an object properly catching all exceptions.static booleantryAcquire(Semaphore sem, long timeout, TimeUnit unit)Tries to acquire a permit from provided semaphore duringtimeout.static longuncompressedSize(File zip)Getting the total size of uncompressed data in zip.static int[]unique(int[] a, int aLen, int[] b, int bLen)Returns array which is the union of two arrays (array of elements contained in any of provided arrays).static <T> Tunmarshal(GridKernalContext ctx, byte[] arr, @Nullable ClassLoader clsLdr)Unmarshals object from the input stream using given class loader.static <T> Tunmarshal(GridCacheSharedContext ctx, byte[] arr, @Nullable ClassLoader clsLdr)Unmarshals object from the input stream using given class loader.static <T> Tunmarshal(Marshaller marsh, byte[] arr, @Nullable ClassLoader clsLdr)Unmarshals object from the input stream using given class loader.static <T> Tunmarshal(Marshaller marsh, InputStream in, @Nullable ClassLoader clsLdr)Unmarshals object from the input stream using given class loader.static <T> TunmarshalZip(Marshaller marsh, byte[] zipBytes, @Nullable ClassLoader clsLdr)static Stringunquote(String s)Unquote the given string.static Exceptionunwrap(Throwable t)Unwraps closure exceptions.static byte[]unzip(byte[] zipBytes)static voidunzip(File zipFile, File toDir, @Nullable IgniteLogger log)Unzip file to folder.static intutfBytes(char c)Get number of bytes forDataOutput.writeUTF(java.lang.String), depending on character:
One byte - If a charactercis in the range\u0001through\u007f.
Two bytes - If a charactercis\u0000or is in the range\u0080through\u07ff.static byte[]uuidToBytes(@Nullable UUID uuid)Converts an UUID to byte array.static intuuidToBytes(@Nullable UUID uuid, byte[] arr, int off)EncodesUUIDinto a sequence of bytes using theByteBuffer, storing the result into a new byte array.static voidwait(Object mux)ConvertsInterruptedExceptiontoIgniteCheckedException.static voidwarn(@Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message.static voidwarn(@Nullable IgniteLogger log, Object msg, @Nullable Throwable e)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message.static voidwarnDevOnly(@Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message withDEV_ONLYmarker.static <E extends Throwable>
EwithCause(E e, @Nullable Throwable cause)Utility method that sets cause into exception and returns it.static StringworkDirectory(@Nullable String userWorkDir, @Nullable String userIgniteHome)Get work directory for the given user-provided work directory and Ignite home.static RunnablewrapIgniteFuture(Runnable r, GridFutureAdapter<?> fut)static voidwrapThreadLoader(ClassLoader ldr, Runnable c)Sets thread context class loader to the given loader, executes the closure, and then resets thread context class loader to its initial value.static <R> RwrapThreadLoader(ClassLoader ldr, Callable<R> c)Sets thread context class loader to the given loader, executes the closure, and then resets thread context class loader to its initial value.static <R> RwrapThreadLoader(ClassLoader ldr, IgniteOutClosure<R> c)Sets thread context class loader to the given loader, executes the closure, and then resets thread context class loader to its initial value.static <T> voidwriteArray(ObjectOutput out, T[] arr)Writes array to output stream.static voidwriteBooleanArray(DataOutput out, @org.jetbrains.annotations.Nullable boolean[] arr)Writes boolean array to output stream accounting for null values.static voidwriteByteArray(DataOutput out, @org.jetbrains.annotations.Nullable byte[] arr)Writes byte array to output stream accounting for null values.static voidwriteByteArray(DataOutput out, @org.jetbrains.annotations.Nullable byte[] arr, int maxLen)Writes byte array to output stream accounting for null values.static voidwriteByteCollection(DataOutput out, Collection<Byte> col)// FIXME: added for DR dataCenterIds, review if it is needed after GG-6879.static voidwriteBytesCollection(DataOutput out, Collection<byte[]> bytes)Writes collection of byte arrays to data output.static voidwriteCollection(ObjectOutput out, Collection<?> col)static voidwriteCutString(DataOutput out, @Nullable String s)Writes string to output stream accounting fornullvalues.static <E extends Enum<E>>
voidwriteEnum(DataOutput out, E e)Writes enum to output stream accounting fornullvalues.static voidwriteFully(SocketChannel sockCh, ByteBuffer buf)Safely write buffer fully to blocking socket channel.static voidwriteIgniteUuid(DataOutput out, IgniteUuid uid)WritesIgniteUuidto output stream.static voidwriteIgniteUuids(DataOutput out, @Nullable Collection<IgniteUuid> col)Writes Ignite UUIDs to output stream.static voidwriteIntArray(DataOutput out, @org.jetbrains.annotations.Nullable int[] arr)Writes int array to output stream accounting for null values.static voidwriteIntCollection(DataOutput out, Collection<Integer> col)static voidwriteIntKeyIntValueMap(DataOutput out, Map<Integer,Integer> map)static voidwriteIntKeyMap(ObjectOutput out, Map<Integer,?> map)static voidwriteLock(ReadWriteLock lock)static voidwriteLongArray(DataOutput out, @org.jetbrains.annotations.Nullable long[] arr)Writes long array to output stream.static voidwriteLongString(DataOutput out, @Nullable String s)Writes string to output stream accounting fornullvalues.static voidwriteMap(ObjectOutput out, Map<?,?> map)static intwriteMessageFully(Message msg, OutputStream out, ByteBuffer buf, MessageWriter writer)Fully writes communication message to provided stream.static voidwriteString(DataOutput out, String s)Writes string to output stream accounting fornullvalues.static voidwriteStringMap(DataOutput out, @Nullable Map<String,String> map)Writes string-to-string map to given data output.static voidwriteStringToFile(File file, String s)Writes string to file.static voidwriteStringToFile(File file, String s, String charset)Writes string to file.static voidwriteStringToFile(File file, String s, String charset, boolean append)Writes string to file.static voidwriteUTF(DataOutput out, @Nullable String val)Write UTF string which can benull.static voidwriteUuid(DataOutput out, UUID uid)Writes UUID to output stream.static voidwriteUuid(BinaryRawWriter out, UUID uid)Writes UUID to binary writer.static voidwriteUuids(DataOutput out, @Nullable Collection<UUID> col)Writes UUIDs to output stream.static ClusterNodeyoungest(Collection<ClusterNode> c, @Nullable IgnitePredicate<ClusterNode> p)Gets youngest node out of collection of nodes.static byte[]zip(@org.jetbrains.annotations.Nullable byte[] bytes)Zip binary payload using default compression.static byte[]zip(@org.jetbrains.annotations.Nullable byte[] bytes, int compressionLevel)
-
-
-
Field Detail
-
KB
public static final long KB
- See Also:
- Constant Field Values
-
MB
public static final long MB
- See Also:
- Constant Field Values
-
GB
public static final long GB
- See Also:
- Constant Field Values
-
UTF_BYTE_LIMIT
public static final int UTF_BYTE_LIMIT
String limit in bytes forDataOutput.writeUTF(java.lang.String)andDataInput.readUTF(), that use "Modified UTF-8".- See Also:
- Constant Field Values
-
DFLT_MIN_CHECKPOINTING_PAGE_BUFFER_SIZE
public static final Long DFLT_MIN_CHECKPOINTING_PAGE_BUFFER_SIZE
Minimum checkpointing page buffer size (may be adjusted by Ignite).
-
DFLT_MAX_CHECKPOINTING_PAGE_BUFFER_SIZE
public static final Long DFLT_MAX_CHECKPOINTING_PAGE_BUFFER_SIZE
Default minimum checkpointing page buffer size (may be adjusted by Ignite).
-
DFLT_MBEAN_APPEND_CLASS_LOADER_ID
public static final boolean DFLT_MBEAN_APPEND_CLASS_LOADER_ID
-
EMPTY_INTS
public static final int[] EMPTY_INTS
Empty integers array.
-
EMPTY_LONGS
public static final long[] EMPTY_LONGS
Empty longs array.
-
EMPTY_STRS
public static final String[] EMPTY_STRS
Empty strings array.
-
EMPTY_FIELDS
public static final Field[] EMPTY_FIELDS
Empty fields array.
-
EMPTY_UUIDS
public static final UUID[] EMPTY_UUIDS
-
DFLT_USER_VERSION
public static final String DFLT_USER_VERSION
Default user version.- See Also:
- Constant Field Values
-
THREAD_DUMP_MSG
public static final String THREAD_DUMP_MSG
Thread dump message.- See Also:
- Constant Field Values
-
NUMBER_FILE_NAME_LENGTH
public static final int NUMBER_FILE_NAME_LENGTH
Length of numbered file name.- See Also:
- Constant Field Values
-
IGNITE_PKG
public static final String IGNITE_PKG
Ignite package.- See Also:
- Constant Field Values
-
JMX_DOMAIN
public static final String JMX_DOMAIN
JMX domain as 'xxx.apache.ignite'.
-
IGNITE_HEADER
public static final byte[] IGNITE_HEADER
Network packet header.
-
LONG_DATE_FMT
public static final DateTimeFormatter LONG_DATE_FMT
Long date format pattern for log messages.
-
SHORT_DATE_FMT
public static final DateTimeFormatter SHORT_DATE_FMT
Short date format pattern for log messages in "quiet" mode. Only time is included since we don't expect "quiet" mode to be used for longer runs.
-
DEBUG_DATE_FMT
public static final DateTimeFormatter DEBUG_DATE_FMT
Debug date format.
-
INTERFACE_SUPPLIER
public static IgniteUtils.InterfaceSupplier INTERFACE_SUPPLIER
Supplier of network interfaces. Could be used for tests purposes, must not be changed in production code.
-
MAC_INVALID_ARG_MSG
public static final String MAC_INVALID_ARG_MSG
MAC OS invalid argument socket error message.- See Also:
- Constant Field Values
-
DELIM
public static final String DELIM
- See Also:
- Constant Field Values
-
IGNITE_LOG_DIR
public static final String IGNITE_LOG_DIR
Ignite Logging Directory.
-
IGNITE_WORK_DIR
public static final String IGNITE_WORK_DIR
Ignite Work Directory.
-
LOC_IGNITE_NAME_EMPTY
public static final String LOC_IGNITE_NAME_EMPTY
Empty local Ignite name.
-
IGNITE_MBEANS_DISABLED
public static boolean IGNITE_MBEANS_DISABLED
Ignite MBeans disabled flag.
-
IGNITE_TEST_FEATURES_ENABLED
public static boolean IGNITE_TEST_FEATURES_ENABLED
Ignite test features enabled flag.
-
IGNITE_SUCCESS_FILE_PROPERTY
public static final String IGNITE_SUCCESS_FILE_PROPERTY
Success file name property. This file is used with auto-restarting functionality when Ignite is started by supplied ignite.{bat|sh} scripts.
-
IGNITE_JMX_REMOTE_PROPERTY
public static final String IGNITE_JMX_REMOTE_PROPERTY
JMX remote system property. Setting this property registered the Java VM platform's MBeans and published the Remote Method Invocation (RMI) connector via a private interface to allow JMX client applications to monitor a local Java platform, that is, a Java VM running on the same machine as the JMX client.
-
-
Method Detail
-
getExceptionConverter
public static C1<IgniteCheckedException,IgniteException> getExceptionConverter(Class<? extends IgniteCheckedException> clazz)
Gets IgniteClosure for an IgniteCheckedException class.- Parameters:
clazz- Class.- Returns:
- The IgniteClosure mapped to this exception class, or null if none.
-
allPluginProviders
public static List<PluginProvider> allPluginProviders()
Gets all plugin providers.- Returns:
- Plugins.
-
allPluginProviders
public static List<PluginProvider> allPluginProviders(IgniteConfiguration cfg, boolean includeClsPath)
Gets all plugin providers.- Parameters:
cfg- Configuration.includeClsPath- Include classpath plugins on empty config.- Returns:
- Plugins.
-
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.
-
convertExceptionNoWrap
public static Exception convertExceptionNoWrap(IgniteCheckedException e)
Converts exception, but unlikeconvertException(IgniteCheckedException)does not wrap passed in exception if none suitable converter found.- Parameters:
e- Ignite checked exception.- Returns:
- Ignite runtime exception.
-
convertException
public static IgniteException convertException(IgniteCheckedException e)
- Parameters:
e- Ignite checked exception.- Returns:
- Ignite runtime exception.
-
currentTimeMillis
public static long currentTimeMillis()
- Returns:
- System time approximated by 10 ms.
-
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:
trueIf the given value is power of 2 (0 is not power of 2).
-
ctorFactory
@Nullable public static @Nullable Method ctorFactory()
Return SUN specific constructor factory.- Returns:
- SUN specific constructor factory.
-
objectConstructor
public static Constructor objectConstructor()
- Returns:
- Empty constructor for object class.
-
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.
-
gridEventName
public static String gridEventName(int type)
Gets name for given grid event type.- Parameters:
type- Event type.- Returns:
- Event name.
-
gridEvents
public static int[] gridEvents(int... excl)
Gets all event types.- Parameters:
excl- Optional exclude events.- Returns:
- All events minus excluded ones.
-
discoOrdered
public static boolean discoOrdered(DiscoverySpi discoSpi)
- Parameters:
discoSpi- Discovery SPI.- Returns:
Trueif ordering is supported.
-
relaxDiscoveryOrdered
public static boolean relaxDiscoveryOrdered()
- Returns:
- Checks if disco ordering should be enforced.
-
debug
@Deprecated public static void debug(Object msg)
Deprecated.Calls to this method should never be committed to master.This method should be used for adding quick debug statements in code while debugging. Calls to this method should never be committed to master.- Parameters:
msg- Message to debug.
-
debugx
@Deprecated public static void debugx(String msg)
Deprecated.Calls to this method should never be committed to master.This method should be used for adding quick debug statements in code while debugging. Calls to this method should never be committed to master.- Parameters:
msg- Message to debug.
-
debug
@Deprecated public static void debug(IgniteLogger log, String msg)
Deprecated.Calls to this method should never be committed to master.This method should be used for adding quick debug statements in code while debugging. Calls to this method should never be committed to master.- Parameters:
log- Logger.msg- Message to debug.
-
dumpStack
@Deprecated public static void dumpStack()
Deprecated.Calls to this method should never be committed to master.Prints stack trace of the current thread toSystem.out.
-
dumpStack
@Deprecated public static void dumpStack(String msg)
Deprecated.Calls to this method should never be committed to master.Prints stack trace of the current thread toSystem.out.- Parameters:
msg- Message to print with the stack.
-
dumpStack
public static void dumpStack(@Nullable @Nullable IgniteLogger log, String msg)- Parameters:
log- Logger.msg- Message.
-
dumpStack
@Deprecated public static void dumpStack(String msg, PrintStream out)
Deprecated.Calls to this method should never be committed to master.Prints stack trace of the current thread to provided output stream.- Parameters:
msg- Message to print with the stack.out- Output to dump stack to.
-
debugStack
@Deprecated public static void debugStack(IgniteLogger log, String msg)
Deprecated.Calls to this method should never be committed to master.Prints stack trace of the current thread to provided logger.- Parameters:
log- Logger.msg- Message to print with the stack.
-
debugHeapUsage
public static void debugHeapUsage()
Prints heap usage.
-
heapSize
public static double heapSize(ClusterNode node, int precision)
Gets heap size in GB rounded to specified precision.- Parameters:
node- Node.precision- Precision.- Returns:
- Heap size in GB.
-
heapSize
public static double heapSize(Iterable<ClusterNode> nodes, int precision)
Gets total heap size in GB rounded to specified precision.- Parameters:
nodes- Nodes.precision- Precision.- Returns:
- Total heap size in GB.
-
offheapSize
public static double offheapSize(Iterable<ClusterNode> nodes, int precision)
Gets total offheap size in GB rounded to specified precision.- Parameters:
nodes- Nodes.precision- Precision.- Returns:
- Total offheap size in GB.
-
heapSize
public static double heapSize(int precision)
Returns current JVM maxMemory in the same format asheapSize(ClusterNode, int).- Parameters:
precision- Precision.- Returns:
- Maximum memory size in GB.
-
dumpThreads
public static void dumpThreads(@Nullable @Nullable IgniteLogger log)Performs thread dump and prints all available info to the given log with WARN logging level.- Parameters:
log- Logger.
-
dumpThreads
public static void dumpThreads(@Nullable @Nullable IgniteLogger log, boolean isErrorLevel)Performs thread dump and prints all available info to the given log with WARN or ERROR logging level depending onisErrorLevelparameter.- Parameters:
log- Logger.isErrorLevel-trueif thread dump must be printed with ERROR logging level,falseif thread dump must be printed with WARN logging level.
-
printStackTrace
public static void printStackTrace(long threadId, GridStringBuilder sb)- Parameters:
threadId- Thread ID.sb- Builder.
-
deadlockPresent
public static boolean deadlockPresent()
- Returns:
trueif there is java level deadlock.
-
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
nullotherwise. - Throws:
IgniteCheckedException- If failed.
-
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.
-
newInstance
@Nullable public static <T> T newInstance(String cls) throws IgniteCheckedException
Creates new instance of a class only if it has an empty constructor (can be non-public).- Parameters:
cls- Class name.- Returns:
- Instance.
- Throws:
IgniteCheckedException- If failed.
-
newInstance
@Nullable public static <T> T newInstance(Class<T> cls) throws IgniteCheckedException
Creates new instance of a class only if it has an empty constructor (can be non-public).- Parameters:
cls- Class to instantiate.- Returns:
- New instance of the class or
nullif empty constructor could not be assigned. - Throws:
IgniteCheckedException- If failed.
-
inClassPath
public static boolean inClassPath(String clsName)
Check whether class is in classpath.- Returns:
Trueif in classpath.
-
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
nullif empty constructor could not be assigned. - Throws:
IgniteCheckedException- If failed.
-
formatMins
public static String formatMins(long mins)
Pretty-formatting for minutes.- Parameters:
mins- Minutes to format.- Returns:
- Formatted presentation of minutes.
-
id8
public static String id8(UUID id)
Gets 8-character substring of UUID (for terse logging).- Parameters:
id- Input ID.- Returns:
- 8-character ID substring.
-
id8
public static String id8(IgniteUuid id)
Gets 8-character substring ofIgniteUuid(for terse logging). The ID8 will be constructed as follows:- Take first 4 digits for global ID, i.e.
IgniteUuid.globalId(). - Take last 4 digits for local ID, i.e.
IgniteUuid.localId().
- Parameters:
id- Input ID.- Returns:
- 8-character representation of
IgniteUuid.
- Take first 4 digits for global ID, i.e.
-
filler
public static String filler(int len, char ch)
- Parameters:
len- Number of characters to fill in.ch- Character to fill with.- Returns:
- String.
-
writeArray
public static <T> void writeArray(ObjectOutput out, T[] arr) throws IOException
Writes array to output stream.- Type Parameters:
T- Array type.- Parameters:
out- Output stream.arr- Array to write.- Throws:
IOException- If failed.
-
readArray
@Nullable public static @Nullable Object[] readArray(ObjectInput in) throws IOException, ClassNotFoundException
Reads array from input stream.- Parameters:
in- Input stream.- Returns:
- Deserialized array.
- Throws:
IOException- If failed.ClassNotFoundException- If class not found.
-
readArray
@Nullable public static <T> @Nullable T[] readArray(ObjectInput in, Class<T> cls) throws IOException, ClassNotFoundException
Reads typed array from input stream.- Parameters:
in- Input stream.- Returns:
- Deserialized array.
- Throws:
IOException- If failed.ClassNotFoundException- If class not found.
-
readClassArray
@Nullable public static @Nullable Class<?>[] readClassArray(ObjectInput in) throws IOException, ClassNotFoundException
Reads array from input stream.- Parameters:
in- Input stream.- Returns:
- Deserialized array.
- Throws:
IOException- If failed.ClassNotFoundException- If class not found.
-
writeCollection
public static void writeCollection(ObjectOutput out, Collection<?> col) throws IOException
- Parameters:
out- Output.col- Set to write.- Throws:
IOException- If write failed.
-
writeIntCollection
public static void writeIntCollection(DataOutput out, Collection<Integer> col) throws IOException
- Parameters:
out- Output.col- Set to write.- Throws:
IOException- If write failed.
-
readCollection
@Nullable public static <E> @Nullable Collection<E> readCollection(ObjectInput in) throws IOException, ClassNotFoundException
- Parameters:
in- Input.- Returns:
- Deserialized set.
- Throws:
IOException- If deserialization failed.ClassNotFoundException- If deserialized class could not be found.
-
readIntCollection
@Nullable public static @Nullable Collection<Integer> readIntCollection(DataInput in) throws IOException
- Parameters:
in- Input.- Returns:
- Deserialized set.
- Throws:
IOException- If deserialization failed.
-
copyMap
public static <K,V> Map<K,V> copyMap(Map<K,V> m)
- Type Parameters:
K- Key type.V- Value type- Parameters:
m- Map to copy.- Returns:
- Copied map.
-
sealMap
public static <K,V> Map<K,V> sealMap(Map<K,V> m)
- Type Parameters:
K- Key type.V- Value type- Parameters:
m- Map to seal.- Returns:
- Sealed map.
-
sealList
public static <E> List<E> sealList(Collection<E> c)
Seal collection.- Type Parameters:
E- Entry type- Parameters:
c- Collection to seal.- Returns:
- Sealed collection.
-
sealList
public static <E> List<E> sealList(E... a)
Convert array to seal list.- Type Parameters:
E- Entry type- Parameters:
a- Array for convert to seal list.- Returns:
- Sealed collection.
-
getNetworkInterfaceName
@Nullable public static @Nullable String getNetworkInterfaceName(String addr)
Gets display name of the network interface this IP address belongs to.- Parameters:
addr- IP address for which to find network interface name.- Returns:
- Network interface name or
nullif can't be found.
-
resolveLocalHost
public static InetAddress resolveLocalHost(@Nullable @Nullable String hostName) throws IOException
Tries to resolve host by name, returning local host if input is empty. This method reflects howIgniteConfiguration.getLocalHost()should be handled in most places.- Parameters:
hostName- Hostname ornullif local host should be returned.- Returns:
- Address of given host or of localhost.
- Throws:
IOException- If attempt to get local host failed.
-
isLocalHostChanged
public static boolean isLocalHostChanged() throws IOExceptionDetermines whether current local host is different from previously cached.- Returns:
trueorfalsedepending on whether or not local host has changed from the cached value.- Throws:
IOException- If attempt to get local host failed.
-
filterReachable
public static List<InetAddress> filterReachable(Collection<InetAddress> addrs)
- Parameters:
addrs- Addresses.- Returns:
- List of reachable addresses.
-
resolveLocalAddresses
public static IgniteBiTuple<Collection<String>,Collection<String>> resolveLocalAddresses(InetAddress locAddr) throws IOException
Returns host names consistent withresolveLocalHost(String). So when it returns a common address this method returns single host name, and when a wildcard address passed this method tries to collect addresses of all available interfaces.- Parameters:
locAddr- Local address to resolve.- Returns:
- Resolved available addresses of given local address.
- Throws:
IOException- If failed.
-
resolveLocalAddresses
public static IgniteBiTuple<Collection<String>,Collection<String>> resolveLocalAddresses(InetAddress locAddr, boolean allHostNames) throws IOException
Returns host names consistent withresolveLocalHost(String). So when it returns a common address this method returns single host name, and when a wildcard address passed this method tries to collect addresses of all available interfaces.- Parameters:
locAddr- Local address to resolve.allHostNames- Iftruethen include host names for all addresses.- Returns:
- Resolved available addresses and host names of given local address.
- Throws:
IOException- If failed.
-
getLocalHost
public static InetAddress getLocalHost() throws IOException
Gets local host. Implementation will first attempt to get a non-loopback address. If that fails, then loopback address will be returned.Note that this method is synchronized to make sure that local host initialization happens only once.
- Returns:
- Address representing local host.
- Throws:
IOException- If attempt to get local host failed.
-
reachable
public static boolean reachable(NetworkInterface itf, InetAddress addr, int reachTimeout)
Checks if address can be reached using three argument InetAddress.isReachable() version.- Parameters:
itf- Network interface to use for test.addr- Address to check.reachTimeout- Timeout for the check.- Returns:
Trueif address is reachable.
-
reachable
public static boolean reachable(InetAddress addr, int reachTimeout)
Checks if address can be reached using one argument InetAddress.isReachable() version.- Parameters:
addr- Address to check.reachTimeout- Timeout for the check.- Returns:
Trueif address is reachable.
-
sameMacs
public static boolean sameMacs(ClusterNode loc, ClusterNode rmt)
- Parameters:
loc- Local node.rmt- Remote node.- Returns:
- Whether given nodes have the same macs.
-
allLocalIps
public static Collection<String> allLocalIps()
Gets a list of all local non-loopback IPs known to this JVM. Note that this will include both IPv4 and IPv6 addresses (even if one "resolves" into another). Loopbacks will be skipped.- Returns:
- List of all known local IPs (empty list if no addresses available).
-
isLocalAddress
public static boolean isLocalAddress(InetAddress addr)
Checks if the address is local.- Parameters:
addr- Address for check.- Returns:
- true if address is local, otherwise false
-
allLocalMACs
public static Collection<String> allLocalMACs()
Gets a list of all local enabled MACs known to this JVM. It is using hardware address of the network interface that is not guaranteed to be MAC addresses (but in most cases it is).Note that if network interface is disabled - its MAC won't be included. All local network interfaces are probed including loopbacks. Virtual interfaces (sub-interfaces) are skipped.
Note that on linux getHardwareAddress() can return null from time to time if NetworkInterface.getHardwareAddress() method is called from many threads.
- Returns:
- List of all known enabled local MACs or empty list if no MACs could be found.
-
downloadUrl
public static File downloadUrl(URL url, File file) throws IOException
Downloads resource by URL.- Parameters:
url- URL to download.file- File where downloaded resource should be stored.- Returns:
- File where downloaded resource should be stored.
- Throws:
IOException- If error occurred.
-
hidePassword
@Nullable public static @Nullable String hidePassword(@Nullable @Nullable String uri)
Replace password in URI string with a single '*' character.Parses given URI by applying ".*://(.*:.*)@.*" regular expression pattern and than if URI matches it replaces password strings between '/' and '@' with '*'.
- Parameters:
uri- URI which password should be replaced.- Returns:
- Converted URI string
-
gridClassLoader
public static ClassLoader gridClassLoader()
- Returns:
- Class loader used to load Ignite itself.
-
resolveClassLoader
public static ClassLoader resolveClassLoader(IgniteConfiguration cfg)
- Returns:
- ClassLoader at IgniteConfiguration in case it is not null or ClassLoader used to start Ignite.
-
resolveClassLoader
public static ClassLoader resolveClassLoader(ClassLoader ldr, IgniteConfiguration cfg)
- Returns:
- ClassLoader passed as param in case it is not null or ClassLoader at IgniteConfiguration in case it is not null or ClassLoader used to start Ignite.
-
hasParent
public static boolean hasParent(@Nullable @Nullable ClassLoader parent, ClassLoader ldr)- Parameters:
parent- Parent to find.ldr- Loader to check.- Returns:
Trueif parent found.
-
writeBytesCollection
public static void writeBytesCollection(DataOutput out, Collection<byte[]> bytes) throws IOException
Writes collection of byte arrays to data output.- Parameters:
out- Output to write to.bytes- Collection with byte arrays.- Throws:
IOException- If write failed.
-
readBytesList
public static List<byte[]> readBytesList(DataInput in) throws IOException
Reads collection of byte arrays from data input.- Parameters:
in- Data input to read from.- Returns:
- List of byte arrays.
- Throws:
IOException- If read failed.
-
writeByteArray
public static void writeByteArray(DataOutput out, @Nullable @org.jetbrains.annotations.Nullable byte[] arr) throws IOException
Writes byte array to output stream accounting for null values.- Parameters:
out- Output stream to write to.arr- Array to write, possibly null.- Throws:
IOException- If write failed.
-
writeByteArray
public static void writeByteArray(DataOutput out, @Nullable @org.jetbrains.annotations.Nullable byte[] arr, int maxLen) throws IOException
Writes byte array to output stream accounting for null values.- Parameters:
out- Output stream to write to.arr- Array to write, possibly null.- Throws:
IOException- If write failed.
-
readByteArray
@Nullable public static @org.jetbrains.annotations.Nullable byte[] readByteArray(DataInput in) throws IOException
Reads byte array from input stream accounting for null values.- Parameters:
in- Stream to read from.- Returns:
- Read byte array, possibly null.
- Throws:
IOException- If read failed.
-
readByteArray
public static byte[] readByteArray(ByteBuffer... bufs)
Reads byte array from given buffers (changing buffer positions).- Parameters:
bufs- Byte buffers.- Returns:
- Byte array.
-
writeByteCollection
public static void writeByteCollection(DataOutput out, Collection<Byte> col) throws IOException
// FIXME: added for DR dataCenterIds, review if it is needed after GG-6879.- Parameters:
out- Output.col- Set to write.- Throws:
IOException- If write failed.
-
readByteList
@Nullable public static @Nullable List<Byte> readByteList(DataInput in) throws IOException
// FIXME: added for DR dataCenterIds, review if it is needed after GG-6879.- Parameters:
in- Input.- Returns:
- Deserialized list.
- Throws:
IOException- If deserialization failed.
-
join
public static byte[] join(byte[]... bufs)
Join byte arrays into single one.- Parameters:
bufs- list of byte arrays to concatenate.- Returns:
- Concatenated byte's array.
-
byteArray2String
public static String byteArray2String(byte[] arr, String hdrFmt, String bodyFmt)
Converts byte array to formatted string. If calling:... byte[] data = {10, 20, 30, 40, 50, 60, 70, 80, 90}; U.byteArray2String(data, "0x%02X", ",0x%02X") ...the result will be:... 0x0A, 0x14, 0x1E, 0x28, 0x32, 0x3C, 0x46, 0x50, 0x5A ...
- Parameters:
arr- Array of byte.hdrFmt- C-style string format for the first element.bodyFmt- C-style string format for second and following elements, if any.- Returns:
- String with converted bytes.
-
hexString2ByteArray
public static byte[] hexString2ByteArray(String hex) throws IllegalArgumentException
Convert string with hex values to byte array.- Parameters:
hex- Hexadecimal string to convert.- Returns:
- array of bytes defined as hex in string.
- Throws:
IllegalArgumentException- If input character differs from certain hex characters.
-
hexLong
public static String hexLong(long val)
Gets a hex string representation of the given long value.- Parameters:
val- Value to convert to string.- Returns:
- Hex string.
-
hexInt
public static String hexInt(int val)
Gets a hex string representation of the given long value.- Parameters:
val- Value to convert to string.- Returns:
- Hex string.
-
doubleToBytes
public static byte[] doubleToBytes(double d)
Converts primitive double to byte array.- Parameters:
d- Double to convert.- Returns:
- Byte array.
-
doubleToBytes
public static int doubleToBytes(double d, byte[] bytes, int off)Converts primitivedoubletype to byte array and stores it in the specified byte array.- Parameters:
d- Double to convert.bytes- Array of bytes.off- Offset.- Returns:
- New offset.
-
floatToBytes
public static byte[] floatToBytes(float f)
Converts primitive float to byte array.- Parameters:
f- Float to convert.- Returns:
- Array of bytes.
-
floatToBytes
public static int floatToBytes(float f, byte[] bytes, int off)Converts primitive float to byte array.- Parameters:
f- Float to convert.bytes- Array of bytes.off- Offset.- Returns:
- New offset.
-
longToBytes
public static byte[] longToBytes(long l)
Converts primitivelongtype to byte array.- Parameters:
l- Long value.- Returns:
- Array of bytes.
-
longToBytes
public static int longToBytes(long l, byte[] bytes, int off)Converts primitivelongtype to byte array and stores it in specified byte array.- Parameters:
l- Long value.bytes- Array of bytes.off- Offset inbytesarray.- Returns:
- Number of bytes overwritten in
bytesarray.
-
intToBytes
public static byte[] intToBytes(int i)
Converts primitiveinttype to byte array.- Parameters:
i- Integer value.- Returns:
- Array of bytes.
-
intToBytes
public static int intToBytes(int i, byte[] bytes, int off)Converts primitiveinttype to byte array and stores it in specified byte array.- Parameters:
i- Integer value.bytes- Array of bytes.off- Offset inbytesarray.- Returns:
- Number of bytes overwritten in
bytesarray.
-
shortToBytes
public static byte[] shortToBytes(short s)
Converts primitiveshorttype to byte array.- Parameters:
s- Short value.- Returns:
- Array of bytes.
-
shortToBytes
public static int shortToBytes(short s, byte[] bytes, int off)Converts primitiveshorttype to byte array and stores it in specified byte array.- Parameters:
s- Short value.bytes- Array of bytes.off- Offset inbytesarray.- Returns:
- Number of bytes overwritten in
bytesarray.
-
uuidToBytes
public static int uuidToBytes(@Nullable @Nullable UUID uuid, byte[] arr, int off)EncodesUUIDinto a sequence of bytes using theByteBuffer, storing the result into a new byte array.- Parameters:
uuid- Unique identifier.arr- Byte array to fill with result.off- Offset inarr.- Returns:
- Number of bytes overwritten in
bytesarray.
-
uuidToBytes
public static byte[] uuidToBytes(@Nullable @Nullable UUID uuid)Converts an UUID to byte array.- Parameters:
uuid- UUID value.- Returns:
- Encoded into byte array
UUID.
-
bytesToShort
public static short bytesToShort(byte[] bytes, int off)Constructsshortfrom byte array.- Parameters:
bytes- Array of bytes.off- Offset inbytesarray.- Returns:
- Short value.
-
bytesToInt
public static int bytesToInt(byte[] bytes, int off)Constructsintfrom byte array.- Parameters:
bytes- Array of bytes.off- Offset inbytesarray.- Returns:
- Integer value.
-
bytesToLong
public static long bytesToLong(byte[] bytes, int off)Constructslongfrom byte array.- Parameters:
bytes- Array of bytes.off- Offset inbytesarray.- Returns:
- Long value.
-
bytesToUuid
public static UUID bytesToUuid(byte[] bytes, int off)
Reads anUUIDform byte array. If given array contains all 0s thennullwill be returned.- Parameters:
bytes- array of bytes.off- Offset inbytesarray.- Returns:
- UUID value or
null.
-
bytesToDouble
public static double bytesToDouble(byte[] bytes, int off)Constructs double from byte array.- Parameters:
bytes- Byte array.off- Offset inbytesarray.- Returns:
- Double value.
-
bytesToFloat
public static float bytesToFloat(byte[] bytes, int off)Constructs float from byte array.- Parameters:
bytes- Byte array.off- Offset inbytesarray.- Returns:
- Float value.
-
bytesEqual
public static boolean bytesEqual(byte[] a, int aOff, byte[] b, int bOff, int len)Compares fragments of byte arrays.- Parameters:
a- First array.aOff- First array offset.b- Second array.bOff- Second array offset.len- Length of fragments.- Returns:
trueif fragments are equal,falseotherwise.
-
decodeHex
public static byte[] decodeHex(char[] data) throws IgniteCheckedExceptionConverts an array of characters representing hexidecimal values into an array of bytes of those same values. The returned array will be half the length of the passed array, as it takes two characters to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.- Parameters:
data- An array of characters containing hexidecimal digits- Returns:
- A byte array containing binary data decoded from the supplied char array.
- Throws:
IgniteCheckedException- Thrown if an odd number or illegal of characters is supplied.
-
readableSize
public static String readableSize(long bytes, boolean si)
- Parameters:
bytes- Number of bytes to display.si- Iftrue, then unit base is 1000, otherwise unit base is 1024.- Returns:
- Formatted size.
-
fixedLengthNumberName
public static String fixedLengthNumberName(long num, @Nullable @Nullable String ext)
Generates file name from index.- Parameters:
num- Number to generate file name.ext- Optional extension- Returns:
- File name.
-
fixedLengthFileNumber
public static long fixedLengthFileNumber(String fileName)
- Parameters:
fileName- File name.- Returns:
- Number of this file.
-
fixedLengthNumberNamePattern
public static Pattern fixedLengthNumberNamePattern(@Nullable @Nullable String ext)
- Parameters:
ext- Optional extension.- Returns:
- Pattern to match numbered file name with the specific extension.
-
dash
public static String dash(int len)
Makes a'+---+'dash line.- Parameters:
len- Length of the dash line to make.- Returns:
- Dash line.
-
pad
public static String pad(int len)
Creates space filled string of given length.- Parameters:
len- Number of spaces.- Returns:
- Space filled string of given length.
-
format
public static String format(long sysTime)
Formats system time in milliseconds for printing in logs.- Parameters:
sysTime- System time.- Returns:
- Formatted time string.
-
asIterable
public static <T> Iterable<T> asIterable(Enumeration<T> e)
Converts enumeration to iterable so it can be used inforeachconstruct.- Type Parameters:
T- Types of instances for iteration.- Parameters:
e- Enumeration to convert.- Returns:
- Iterable over the given enumeration.
-
copy
public static void copy(File src, File dest, boolean overwrite) throws IOException
Copy source file (or folder) to destination file (or folder). Supported source & destination:- File to File
- File to Folder
- Folder to Folder (Copy the content of the directory and not the directory itself)
- Parameters:
src- Source file or folder.dest- Destination file or folder.overwrite- Whether or not overwrite existing files and folders.- Throws:
IOException- Thrown if an I/O error occurs.
-
onGridStart
public static void onGridStart()
Starts clock timer if grid is first.
-
onGridStop
public static void onGridStop() throws InterruptedExceptionStops clock timer if all nodes into JVM were stopped.- Throws:
InterruptedException- If interrupted.
-
copy
public static int copy(InputStream in, OutputStream out) throws IOException
Copies input byte stream to output byte stream.- Parameters:
in- Input byte stream.out- Output byte stream.- Returns:
- Number of the copied bytes.
- Throws:
IOException- Thrown if an I/O error occurs.
-
copy
public static int copy(Reader in, Writer out) throws IOException
Copies input character stream to output character stream.- Parameters:
in- Input character stream.out- Output character stream.- Returns:
- Number of the copied characters.
- Throws:
IOException- Thrown if an I/O error occurs.
-
writeStringToFile
public static void writeStringToFile(File file, String s) throws IOException
Writes string to file.- Parameters:
file- File.s- String to write.- Throws:
IOException- Thrown if an I/O error occurs.
-
writeStringToFile
public static void writeStringToFile(File file, String s, String charset) throws IOException
Writes string to file.- Parameters:
file- File.s- String to write.charset- Encoding.- Throws:
IOException- Thrown if an I/O error occurs.
-
readFileToString
public static String readFileToString(String fileName, String charset) throws IOException
Reads file to string using specified charset.- Parameters:
fileName- File name.charset- File charset.- Returns:
- File content.
- Throws:
IOException- If error occurred.
-
writeStringToFile
public static void writeStringToFile(File file, String s, String charset, boolean append) throws IOException
Writes string to file.- Parameters:
file- File.s- String to write.charset- Encoding.append- Iftrue, then specified string will be added to the end of the file.- Throws:
IOException- Thrown if an I/O error occurs.
-
withCause
public static <E extends Throwable> E withCause(E e, @Nullable @Nullable Throwable cause)
Utility method that sets cause into exception and returns it.- Type Parameters:
E- Type of the exception.- Parameters:
e- Exception to set cause to and return.cause- Optional cause to set (if notnull).- Returns:
- Passed in exception with optionally set cause.
-
delete
public static boolean delete(@Nullable @Nullable File file)Deletes file or directory with all sub-directories and files. Not thread-safe.- Parameters:
file- File or directory to delete.- Returns:
trueif and only if the file or directory is successfully deleted,falseotherwise
-
sizeInMegabytes
public static int sizeInMegabytes(long sizeInBytes)
Converts size in bytes to human-readable size in megabytes.- Parameters:
sizeInBytes- Size of any object (file, memory region etc) in bytes.- Returns:
- Size converted to megabytes.
-
delete
public static boolean delete(Path path)
Deletes file or directory with all sub-directories and files. Not thread-safe.- Parameters:
path- File or directory to delete.- Returns:
trueif and only if the file or directory is successfully deleted,falseotherwise
-
mkdirs
public static boolean mkdirs(File dir)
- Parameters:
dir- Directory to create along with all non-existent parent directories.- Returns:
Trueif directory exists (has been created or already existed),falseif has not been created and does not exist.
-
getIgniteHome
@Nullable public static @Nullable String getIgniteHome()
RetrievesIGNITE_HOMEproperty. The property is retrieved from system properties or from environment in that order.- Returns:
IGNITE_HOMEproperty.
-
setIgniteHome
public static void setIgniteHome(@Nullable @Nullable String path)- Parameters:
path- Ignite home. May benull.
-
resolveIgnitePath
@Nullable public static @Nullable File resolveIgnitePath(String path)
Gets file associated with path.First check if path is relative to
IGNITE_HOME. If not, check if path is absolute. If all checks fail, thennullis returned.See
getIgniteHome()for information on howIGNITE_HOMEis retrieved.- Parameters:
path- Path to resolve.- Returns:
- Resolved path as file, or
nullif path cannot be resolved.
-
resolveIgniteUrl
@Nullable public static @Nullable URL resolveIgniteUrl(String path)
Gets URL representing the path passed in. First the check is made if path is absolute. If not, then the check is made if path is relative toMETA-INFfolder in classpath. If not, then the check is made if path is relative to ${IGNITE_HOME}. If all checks fail, thennullis returned, otherwise URL representing path is returned.See
getIgniteHome()for information on howIGNITE_HOMEis retrieved.- Parameters:
path- Path to resolve.- Returns:
- Resolved path as URL, or
nullif path cannot be resolved. - See Also:
getIgniteHome()
-
resolveSpringUrl
public static URL resolveSpringUrl(String springCfgPath) throws IgniteCheckedException
Resolve Spring configuration URL.- Parameters:
springCfgPath- Spring XML configuration file path or URL. This cannot benull.- Returns:
- URL.
- Throws:
IgniteCheckedException- If failed.
-
resolveIgniteUrl
@Nullable public static @Nullable URL resolveIgniteUrl(String path, boolean metaInf)
Gets URL representing the path passed in. First the check is made if path is absolute. If not, then the check is made if path is relative toMETA-INFfolder in classpath. If not, then the check is made if path is relative to ${IGNITE_HOME}. If all checks fail, thennullis returned, otherwise URL representing path is returned.See
getIgniteHome()for information on howIGNITE_HOMEis retrieved.- Parameters:
path- Path to resolve.metaInf- Flag to indicate whether META-INF folder should be checked or class path root.- Returns:
- Resolved path as URL, or
nullif path cannot be resolved. - See Also:
getIgniteHome()
-
byteArray2HexString
public static String byteArray2HexString(byte[] arr)
Converts byte array to hex string.- Parameters:
arr- Array of bytes.- Returns:
- Hex string.
-
byteArray2HexString
public static String byteArray2HexString(byte[] arr, boolean toUpper)
Converts byte array to hex string.- Parameters:
arr- Array of bytes.toUpper- Iftruereturns upper cased result.- Returns:
- Hex string.
-
containsObjectArray
public static boolean containsObjectArray(@Nullable @Nullable Object[] arr, Object val, @Nullable @Nullable Object... vals)Checks for containment of the value in the array. Both array cells and value may benull. Twonulls are considered equal.- Parameters:
arr- Array of objects.val- Value to check for containment inside of array.vals- Additional values.- Returns:
trueif contains object,falseotherwise.
-
containsIntArray
public static boolean containsIntArray(int[] arr, int val)Checks for containment of the value in the array.- Parameters:
arr- Array of objects.val- Value to check for containment inside of array.- Returns:
trueif contains object,falseotherwise.
-
containsStringArray
public static boolean containsStringArray(String[] arr, @Nullable @Nullable String val, boolean ignoreCase)
Checks for containment of given string value in the specified array. Array's cells and string value can benull. Townulls are considered equal.- Parameters:
arr- Array of strings.val- Value to check for containment inside of array.ignoreCase- Ignoring case iftrue.- Returns:
trueif contains string,falseotherwise.
-
containsStringCollection
public static boolean containsStringCollection(Iterable<String> c, @Nullable @Nullable String val, boolean ignoreCase)
Checks for containment of given string value in the specified collection. Collection elements and string value can benull. Townulls are considered equal.- Parameters:
c- Array of strings.val- Value to check for containment inside of array.ignoreCase- Ignoring case iftrue.- Returns:
trueif contains string,falseotherwise.
-
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'snull- 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'snull- it's no-op.log- Logger to log possible checked exception with (optional).
-
closeWithSuppressingException
public static void closeWithSuppressingException(@Nullable @Nullable AutoCloseable rsrc, @NotNull @NotNull Exception e)Closes given resource suppressing possible checked exception.- Parameters:
rsrc- Resource to close. If it'snull- it's no-op.e- Suppressor exception
-
closeQuiet
public static void closeQuiet(@Nullable @Nullable AutoCloseable rsrc)Quietly closes given resource ignoring possible checked exception.- Parameters:
rsrc- Resource to close. If it'snull- it's no-op.
-
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'snull- it's no-op.log- Logger to log possible checked exception with (optional).
-
closeQuiet
public static void closeQuiet(@Nullable @Nullable SelectionKey rsrc)Quietly closes given resource ignoring possible checked exceptions.- Parameters:
rsrc- Resource to close. If it'snull- it's no-op.
-
close
public static void close(@Nullable @Nullable DatagramSocket rsrc)Closes given resource.- Parameters:
rsrc- Resource to close. If it'snull- 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'snull- it's no-op.log- Logger to log possible checked exception with (optional).
-
closeQuiet
public static void closeQuiet(@Nullable @Nullable Selector rsrc)Quietly closes given resource ignoring possible checked exception.- Parameters:
rsrc- Resource to close. If it'snull- it's no-op.
-
close
public static void close(@Nullable @Nullable Context rsrc, @Nullable @Nullable IgniteLogger log)Closes given resource logging possible checked exception.- Parameters:
rsrc- Resource to close. If it'snull- it's no-op.log- Logger to log possible checked exception with (optional).
-
closeQuiet
public static void closeQuiet(@Nullable @Nullable Context rsrc)Quietly closes given resource ignoring possible checked exception.- Parameters:
rsrc- Resource to close. If it'snull- it's no-op.
-
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'snull- it's no-op.log- Logger to log possible checked exception with (optional).
-
closeQuiet
public static void closeQuiet(@Nullable @Nullable Socket sock)Quietly closes givenSocketignoring possible checked exception.- Parameters:
sock- Socket to close. If it'snull- it's no-op.
-
releaseQuiet
public static void releaseQuiet(@Nullable @Nullable FileLock lock)Quietly releases file lock ignoring all possible exceptions.- Parameters:
lock- File lock. If it'snull- it's no-op.
-
rollbackConnection
public static void rollbackConnection(@Nullable @Nullable Connection rsrc, @Nullable @Nullable IgniteLogger log)Rollbacks JDBC connection logging possible checked exception.- Parameters:
rsrc- JDBC connection to rollback. If connection isnull, it's no-op.log- Logger to log possible checked exception with (optional).
-
courtesy
public static void courtesy(@Nullable @Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message inorg.apache.ignite.CourtesyConfigNoticecategory. Iflogisnullor in QUIET mode it will add(courtesy)prefix to the message.- Parameters:
log- Optional logger to use when QUIET mode is not enabled.msg- Message to log.
-
courtesy
public static void courtesy(@Nullable @Nullable IgniteLogger log, Object longMsg, Object shortMsg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message inorg.apache.ignite.CourtesyConfigNoticecategory. Iflogisnullor in QUIET mode it will add(courtesy)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.
-
warn
public static void warn(@Nullable @Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message. Iflogisnullor 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.
-
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 or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log ERROR message. Iflogisnullor 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.
-
warn
public static void warn(@Nullable @Nullable IgniteLogger log, Object msg, @Nullable @Nullable Throwable e)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message. Iflogisnullor 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.
-
warnDevOnly
public static void warnDevOnly(@Nullable @Nullable IgniteLogger log, Object msg)Depending on whether or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log WARN message withDEV_ONLYmarker. Iflogisnullor in QUIET mode it will add(wrn)prefix to the message. If propertyIGNITE_DEV_ONLY_LOGGING_DISABLEDis 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 or not 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.
-
initWorkDir
public static void initWorkDir(IgniteConfiguration cfg) throws IgniteCheckedException
Resolves work directory.- Parameters:
cfg- Ignite configuration.- Throws:
IgniteCheckedException
-
initLogger
public static IgniteLogger initLogger(IgniteConfiguration cfg, String app) throws IgniteCheckedException
- Parameters:
cfg- Ignite configuration.app- Application name.- Returns:
- Initialized logger.
- Throws:
IgniteCheckedException- If failed.
-
initLogger
public static IgniteLogger initLogger(@Nullable @Nullable IgniteLogger cfgLog, @Nullable @Nullable String app, @Nullable @Nullable UUID nodeId, String workDir) throws IgniteCheckedException
- Parameters:
cfgLog- Configured logger.app- Application name.workDir- Work directory.- Returns:
- Initialized logger.
- Throws:
IgniteCheckedException- If failed.
-
log
public static void log(@Nullable @Nullable IgniteLogger log, Object msg)Depending on whether or not 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 or not log is provided and quiet mode is enabled logs given messages as quiet message or normal log ERROR message. Iflogisnullor 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.
-
error
public static void error(@Nullable @Nullable IgniteLogger log, Object shortMsg, @Nullable @Nullable Throwable e)- Parameters:
log- Optional 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 toSystem.err.objs- Objects to log in quiet mode.
-
quietMultipleLines
public static void quietMultipleLines(boolean err, String multiline)- Parameters:
err- Whether to print toSystem.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.
-
rollbackConnectionQuiet
public static void rollbackConnectionQuiet(@Nullable @Nullable Connection rsrc)Quietly rollbacks JDBC connection ignoring possible checked exception.- Parameters:
rsrc- JDBC connection to rollback. If connection isnull, it's no-op.
-
makeMBeanName
public static ObjectName makeMBeanName(@Nullable @Nullable String igniteInstanceName, @Nullable @Nullable String grp, String name) throws MalformedObjectNameException
Constructs JMX object name with given properties. Map with orderedgroupsused for proper object name construction.- Parameters:
igniteInstanceName- Ignite instance name.grp- Name of the group.name- Name of mbean.- Returns:
- JMX object name.
- Throws:
MalformedObjectNameException- Thrown in case of any errors.
-
makeMBeanName
public static ObjectName makeMBeanName(@Nullable @Nullable String igniteInstanceName, @Nullable @Nullable String grp, List<String> grps, String name) throws MalformedObjectNameException
Constructs JMX object name with given properties. Map with orderedgroupsused for proper object name construction.- Parameters:
igniteInstanceName- Ignite instance name.grp- Name of the group.grps- Names of extended groups.name- Name of mbean.- Returns:
- JMX object name.
- Throws:
MalformedObjectNameException- Thrown in case of any errors.
-
maskName
public static String maskName(@Nullable @Nullable String name)
Mask component name to make sure that it is notnull.- Parameters:
name- Component name to mask, possiblynull.- Returns:
- Component name.
-
alphanumericUnderscore
public static boolean alphanumericUnderscore(String s)
- Parameters:
s- String to check.- Returns:
trueif given string contains only alphanumeric and underscore symbols.
-
registerMBean
public static <T> ObjectName registerMBean(MBeanServer mbeanSrv, @Nullable @Nullable String igniteInstanceName, @Nullable @Nullable String grp, String name, T impl, @Nullable @Nullable Class<T> itf) throws JMException
Registers MBean with the server.- Type Parameters:
T- Type of mbean.- Parameters:
mbeanSrv- MBean server.igniteInstanceName- Ignite instance name.grp- Name of the group.name- Name of mbean.impl- MBean implementation.itf- MBean interface.- Returns:
- JMX object name.
- Throws:
MBeanRegistrationException- if MBeans are disabled.JMException- If MBean creation failed.
-
registerMBean
public static <T> ObjectName registerMBean(MBeanServer mbeanSrv, ObjectName name, T impl, Class<T> itf) throws JMException
Registers MBean with the server.- Type Parameters:
T- Type of mbean.- Parameters:
mbeanSrv- MBean server.name- MBean object name.impl- MBean implementation.itf- MBean interface.- Returns:
- JMX object name.
- Throws:
MBeanRegistrationException- if MBeans are disabled.JMException- If MBean creation failed.IgniteException- If MBean creation are not allowed.
-
interrupt
public static void interrupt(@Nullable @Nullable Thread t)Convenience method that interrupts a given thread if it's notnull.- Parameters:
t- Thread to interrupt.
-
interrupt
public static void interrupt(Iterable<? extends Thread> workers)
Convenience method that interrupts a given thread if it's notnull.- Parameters:
workers- Threads to interrupt.
-
join
public static boolean join(@Nullable @Nullable Thread t, @Nullable @Nullable IgniteLogger log)Waits for completion of a given thread. If thread isnullthen this method returns immediately returningtrue- Parameters:
t- Thread to join.log- Logger for logging errors.- Returns:
trueif thread has finished,falseotherwise.
-
join
public static boolean join(@Nullable @Nullable Thread t, @Nullable @Nullable IgniteLogger log, long timeout)Waits for completion of a given thread. If thread isnullthen this method returns immediately returningtrue- Parameters:
t- Thread to join.log- Logger for logging errors.timeout- Join timeout.- Returns:
trueif thread has finished,falseotherwise.
-
joinThreads
public static boolean joinThreads(Iterable<? extends Thread> workers, @Nullable @Nullable IgniteLogger log)
Waits for completion of a given threads. If thread isnullthen this method returns immediately returningtrue- Parameters:
workers- Thread to join.log- Logger for logging errors.- Returns:
trueif thread has finished,falseotherwise.
-
startThreads
public static void startThreads(Iterable<? extends Thread> threads)
Starts given threads.- Parameters:
threads- Threads to start.
-
cancel
public static void cancel(@Nullable @Nullable GridWorker w)Cancels given runnable.- Parameters:
w- Worker to cancel - it's no-op if runnable isnull.
-
cancel
public static void cancel(Iterable<? extends GridWorker> ws)
Cancels collection of runnables.- Parameters:
ws- Collection of workers - it's no-op if collection isnull.
-
join
public static boolean join(@Nullable @Nullable GridWorker w, @Nullable @Nullable IgniteLogger log)Joins runnable.- Parameters:
w- Worker to join.log- The logger to possible exception.- Returns:
trueif worker has not been interrupted,falseif it was interrupted.
-
join
public static boolean join(Iterable<? extends GridWorker> ws, IgniteLogger log)
Joins given collection of runnables.- Parameters:
ws- Collection of workers to join.log- The logger to possible exceptions.- Returns:
trueif none of the worker have been interrupted,falseif at least one was interrupted.
-
shutdownNow
public static void shutdownNow(Class<?> owner, @Nullable @Nullable ExecutorService exec, @Nullable @Nullable IgniteLogger log)
Shutdowns givenExecutorServiceand wait for executor service to stop.- Parameters:
owner- The ExecutorService owner.exec- ExecutorService to shutdown.log- The logger to possible exceptions and warnings.
-
emptyTopologyException
public static ClusterGroupEmptyCheckedException emptyTopologyException()
Creates appropriate empty projection exception.- Returns:
- Empty projection exception.
-
writeUuids
public static void writeUuids(DataOutput out, @Nullable @Nullable Collection<UUID> col) throws IOException
Writes UUIDs to output stream. This method is meant to be used by implementations ofExternalizableinterface.- Parameters:
out- Output stream.col- UUIDs to write.- Throws:
IOException- If write failed.
-
readUuids
@Nullable public static @Nullable List<UUID> readUuids(DataInput in) throws IOException
Reads UUIDs from input stream. This method is meant to be used by implementations ofExternalizableinterface.- Parameters:
in- Input stream.- Returns:
- Read UUIDs.
- Throws:
IOException- If read failed.
-
writeIgniteUuids
public static void writeIgniteUuids(DataOutput out, @Nullable @Nullable Collection<IgniteUuid> col) throws IOException
Writes Ignite UUIDs to output stream. This method is meant to be used by implementations ofExternalizableinterface.- Parameters:
out- Output stream.col- Ignite UUIDs to write.- Throws:
IOException- If write failed.
-
readIgniteUuids
@Nullable public static @Nullable List<IgniteUuid> readIgniteUuids(DataInput in) throws IOException
Reads Ignite UUIDs from input stream. This method is meant to be used by implementations ofExternalizableinterface.- Parameters:
in- Input stream.- Returns:
- Read Ignite UUIDs.
- Throws:
IOException- If read failed.
-
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 ofExternalizableinterface.- 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 ofExternalizableinterface.- Parameters:
in- Input stream.- Returns:
- Read UUID.
- Throws:
IOException- If read failed.
-
writeUuid
public static void writeUuid(BinaryRawWriter out, UUID uid)
Writes UUID to binary writer.- Parameters:
out- Output Binary writer.uid- UUID to write.- Throws:
IOException- If write failed.
-
readUuid
@Nullable public static @Nullable UUID readUuid(BinaryRawReader in)
Reads UUID from binary reader.- Parameters:
in- Binary reader.- Returns:
- Read UUID.
- Throws:
IOException- If read failed.
-
writeIgniteUuid
public static void writeIgniteUuid(DataOutput out, IgniteUuid uid) throws IOException
WritesIgniteUuidto output stream. This method is meant to be used by implementations ofExternalizableinterface.- Parameters:
out- Output stream.uid- UUID to write.- Throws:
IOException- If write failed.
-
readIgniteUuid
@Nullable public static @Nullable IgniteUuid readIgniteUuid(DataInput in) throws IOException
ReadsIgniteUuidfrom input stream. This method is meant to be used by implementations ofExternalizableinterface.- Parameters:
in- Input stream.- Returns:
- Read UUID.
- Throws:
IOException- If read failed.
-
igniteUuidToBytes
public static byte[] igniteUuidToBytes(IgniteUuid uuid)
ConvertsIgniteUuidto bytes.- Parameters:
uuid-IgniteUuidto convert.- Returns:
- Bytes.
-
igniteUuidToBytes
public static void igniteUuidToBytes(IgniteUuid uuid, byte[] out, int off)
ConvertsIgniteUuidto bytes.- Parameters:
uuid-IgniteUuidto convert.out- Output array to write to.off- Offset from which to write.
-
bytesToIgniteUuid
public static IgniteUuid bytesToIgniteUuid(byte[] in, int off)
Converts bytes toIgniteUuid.- Parameters:
in- Input byte array.off- Offset from which start reading.- Returns:
IgniteUuidinstance.
-
writeBooleanArray
public static void writeBooleanArray(DataOutput out, @Nullable @org.jetbrains.annotations.Nullable boolean[] arr) throws IOException
Writes boolean array to output stream accounting for null values.- Parameters:
out- Output stream to write to.arr- Array to write, possibly null.- Throws:
IOException- If write failed.
-
writeIntArray
public static void writeIntArray(DataOutput out, @Nullable @org.jetbrains.annotations.Nullable int[] arr) throws IOException
Writes int array to output stream accounting for null values.- Parameters:
out- Output stream to write to.arr- Array to write, possibly null.- Throws:
IOException- If write failed.
-
writeLongArray
public static void writeLongArray(DataOutput out, @Nullable @org.jetbrains.annotations.Nullable long[] arr) throws IOException
Writes long array to output stream.- Parameters:
out- Output stream to write to.arr- Array to write.- Throws:
IOException- If write failed.
-
readBooleanArray
@Nullable public static @org.jetbrains.annotations.Nullable boolean[] readBooleanArray(DataInput in) throws IOException
Reads boolean array from input stream accounting for null values.- Parameters:
in- Stream to read from.- Returns:
- Read byte array, possibly null.
- Throws:
IOException- If read failed.
-
readIntArray
@Nullable public static @org.jetbrains.annotations.Nullable int[] readIntArray(DataInput in) throws IOException
Reads int array from input stream accounting for null values.- Parameters:
in- Stream to read from.- Returns:
- Read byte array, possibly null.
- Throws:
IOException- If read failed.
-
readLongArray
@Nullable public static @org.jetbrains.annotations.Nullable long[] readLongArray(DataInput in) throws IOException
Reads long array from input stream.- Parameters:
in- Stream to read from.- Returns:
- Read long array, possibly null.
- Throws:
IOException- If read failed.
-
hashCode
public static int hashCode(ByteBuffer... bufs)
Calculates hash code for the given byte buffers contents. Compatible withArrays.hashCode(byte[])with the same content. Does not change buffers positions.- Parameters:
bufs- Byte buffers.- Returns:
- Hash code.
-
writeMap
public static void writeMap(ObjectOutput out, Map<?,?> map) throws IOException
- Parameters:
out- Output.map- Map to write.- Throws:
IOException- If write failed.
-
readMap
@Nullable public static <K,V> @Nullable Map<K,V> readMap(ObjectInput in) throws IOException, ClassNotFoundException
- Parameters:
in- Input.- Returns:
- Read map.
- Throws:
IOException- If de-serialization failed.ClassNotFoundException- If deserialized class could not be found.
-
hashCode
public static int hashCode(Object obj)
Calculate a hashCode for an array.- Parameters:
obj- Object.
-
readTreeMap
@Nullable public static <K,V> @Nullable TreeMap<K,V> readTreeMap(ObjectInput in) throws IOException, ClassNotFoundException
- Parameters:
in- Input.- Returns:
- Read map.
- Throws:
IOException- If de-serialization failed.ClassNotFoundException- If deserialized class could not be found.
-
readHashMap
@Nullable public static <K,V> @Nullable HashMap<K,V> readHashMap(ObjectInput in) throws IOException, ClassNotFoundException
Read hash map.- Parameters:
in- Input.- Returns:
- Read map.
- Throws:
IOException- If de-serialization failed.ClassNotFoundException- If deserialized class could not be found.
-
readLinkedMap
@Nullable public static <K,V> @Nullable LinkedHashMap<K,V> readLinkedMap(ObjectInput in) throws IOException, ClassNotFoundException
- Parameters:
in- Input.- Returns:
- Read map.
- Throws:
IOException- If de-serialization failed.ClassNotFoundException- If deserialized class could not be found.
-
writeIntKeyMap
public static void writeIntKeyMap(ObjectOutput out, Map<Integer,?> map) throws IOException
- Parameters:
out- Output.map- Map to write.- Throws:
IOException- If write failed.
-
readIntKeyMap
@Nullable public static <V> @Nullable Map<Integer,V> readIntKeyMap(ObjectInput in) throws IOException, ClassNotFoundException
- Parameters:
in- Input.- Returns:
- Read map.
- Throws:
IOException- If de-serialization failed.ClassNotFoundException- If deserialized class could not be found.
-
writeIntKeyIntValueMap
public static void writeIntKeyIntValueMap(DataOutput out, Map<Integer,Integer> map) throws IOException
- Parameters:
out- Output.map- Map to write.- Throws:
IOException- If write failed.
-
readIntKeyIntValueMap
@Nullable public static @Nullable Map<Integer,Integer> readIntKeyIntValueMap(DataInput in) throws IOException
- Parameters:
in- Input.- Returns:
- Read map.
- Throws:
IOException- If de-serialization failed.
-
readList
@Nullable public static <E> @Nullable List<E> readList(ObjectInput in) throws IOException, ClassNotFoundException
- Parameters:
in- Input.- Returns:
- Deserialized list.
- Throws:
IOException- If deserialization failed.ClassNotFoundException- If deserialized class could not be found.
-
readIntList
@Nullable public static @Nullable List<Integer> readIntList(DataInput in) throws IOException
- Parameters:
in- Input.- Returns:
- Deserialized list.
- Throws:
IOException- If deserialization failed.
-
readSet
@Nullable public static <E> @Nullable Set<E> readSet(ObjectInput in) throws IOException, ClassNotFoundException
- Parameters:
in- Input.- Returns:
- Deserialized set.
- Throws:
IOException- If deserialization failed.ClassNotFoundException- If deserialized class could not be found.
-
readIntSet
@Nullable public static @Nullable Set<Integer> readIntSet(DataInput in) throws IOException
- Parameters:
in- Input.- Returns:
- Deserialized set.
- Throws:
IOException- If deserialization failed.
-
writeString
public static void writeString(DataOutput out, String s) throws IOException
Writes string to output stream accounting fornullvalues.Limitation for max string lenght of
UTF_BYTE_LIMITbytes is caused byObjectOutputStream.writeUTF(java.lang.String)used under the hood to perform an actual write.If longer string is passes a
UTFDataFormatExceptionexception will be thrown.To write longer strings use one of two options:
-
writeLongString(DataOutput, String)writes string as is converting it into binary array of UTF-8 encoded characters. To read the value backreadLongString(DataInput)should be used. -
writeCutString(DataOutput, String)cuts passed string toUTF_BYTE_LIMITbytes and then writes them without converting to byte array. No exceptions will be thrown for string of any length; written string can be read back with regularreadString(DataInput)method.
- Parameters:
out- Output stream to write to.s- String to write, possiblynull.- Throws:
IOException- If write failed.
-
-
readString
@Nullable public static @Nullable String readString(DataInput in) throws IOException
Reads string from input stream accounting fornullvalues. Method enables to read strings shorter thanUTF_BYTE_LIMITbytes in UTF-8 otherwise an exception will be thrown. Strings written bywriteString(DataOutput, String)orwriteCutString(DataOutput, String)can be read by this method.- Parameters:
in- Stream to read from.- Returns:
- Read string, possibly
null. - Throws:
IOException- If read failed.- See Also:
for more information about writing strings.
-
writeEnum
public static <E extends Enum<E>> void writeEnum(DataOutput out, E e) throws IOException
Writes enum to output stream accounting fornullvalues. Note: method writes only one byte for every enum. Therefore, this method only for Enums with maximum count of values equals to 128.- Parameters:
out- Output stream to write to.e- Enum value to write, possiblynull.- Throws:
IOException- If write failed.
-
readEnum
public static <E extends Enum<E>> E readEnum(DataInput in, Class<E> enumCls) throws IOException
- Throws:
IOException
-
getByIndex
public static <T> T getByIndex(Collection<T> vals, int idx)
Gets collection value by index.- Type Parameters:
T- Type of collection values.- Parameters:
vals- Collection of values.idx- Index of value in the collection.- Returns:
- Value at the given index.
-
getAnnotation
@Nullable public static <T extends Annotation> T getAnnotation(Class<?> cls, Class<T> annCls)
Gets annotation for a class.- Type Parameters:
T- Type of annotation to return.- Parameters:
cls- Class to get annotation from.annCls- Annotation to get.- Returns:
- Instance of annotation, or
nullif not found.
-
getDeclaredAnnotation
@Nullable public static <T extends Annotation> T getDeclaredAnnotation(Class<?> cls, Class<T> annCls)
Gets declared annotation for a class.- Type Parameters:
T- Type of annotation to return.- Parameters:
cls- Class to get annotation from.annCls- Annotation to get.- Returns:
- Instance of annotation, or
nullif not found.
-
hasDeclaredAnnotation
public static <T extends Annotation> boolean hasDeclaredAnnotation(Class<?> cls, Class<T> annCls)
Indicates if class has given declared annotation.- Type Parameters:
T- Annotation type.- Parameters:
cls- Class to get annotation from.annCls- Annotation to get.- Returns:
trueif class has annotation orfalseotherwise.
-
hasDeclaredAnnotation
public static <T extends Annotation> boolean hasDeclaredAnnotation(Object o, Class<T> annCls)
Indicates if class has given annotation.- Parameters:
o- Object to get annotation from.annCls- Annotation to get.- Returns:
trueif class has annotation orfalseotherwise.
-
hasAnnotation
public static <T extends Annotation> boolean hasAnnotation(Class<?> cls, Class<T> annCls)
Indicates if class has given annotation.- Type Parameters:
T- Annotation type.- Parameters:
cls- Class to get annotation from.annCls- Annotation to get.- Returns:
trueif class has annotation orfalseotherwise.
-
hasAnnotation
public static <T extends Annotation> boolean hasAnnotation(Object o, Class<T> annCls)
Indicates if class has given annotation.- Parameters:
o- Object to get annotation from.annCls- Annotation to get.- Returns:
trueif class has annotation orfalseotherwise.
-
allInterfaces
public static Collection<Class<?>> allInterfaces(Class<?> cls)
Provides all interfaces ofclsincluding inherited ones. Excludes duplicated ones in case of multiple inheritance.- Parameters:
cls- Class to search for interfaces.- Returns:
- Collection of interfaces of
cls.
-
getSimpleName
public static String getSimpleName(Class<?> cls)
Gets simple class name taking care of empty names.- Parameters:
cls- Class to get the name for.- Returns:
- Simple class name.
-
containsAll
public static boolean containsAll(Map<?,?> base, Map<?,?> map)
Checks if the map passed in is contained in base map.- Parameters:
base- Base map.map- Map to check.- Returns:
Trueif all entries within map are contained in base map,falseotherwise.
-
getTaskName
public static String getTaskName(Class<? extends ComputeTask<?,?>> taskCls)
Gets task name for the given task class.- Parameters:
taskCls- Task class.- Returns:
- Either task name from class annotation (see
ComputeTaskName}) or task class name if there is no annotation.
-
getResourceName
public static String getResourceName(Class rscCls)
Gets resource name. Returns a task name if it is a Compute task or a class name otherwise.- Parameters:
rscCls- Class of resource.- Returns:
- Name of resource.
-
spiAttribute
public static String spiAttribute(IgniteSpi spi, String attrName)
Creates SPI attribute name by adding prefix to the attribute name. Prefix is an SPI name + '.'.- Parameters:
spi- SPI.attrName- attribute name.- Returns:
- SPI attribute name.
-
classNameToResourceName
public static String classNameToResourceName(String clsName)
Gets resource path for the class.- Parameters:
clsName- Class name.- Returns:
- Resource name for the class.
-
getRuntimeMx
public static RuntimeMXBean getRuntimeMx()
Gets runtime MBean.- Returns:
- Runtime MBean.
-
getThreadMx
public static ThreadMXBean getThreadMx()
Gets threading MBean.- Returns:
- Threading MBean.
-
getOsMx
public static OperatingSystemMXBean getOsMx()
Gets OS MBean.- Returns:
- OS MBean.
-
getMemoryMx
public static MemoryMXBean getMemoryMx()
Gets memory MBean.- Returns:
- Memory MBean.
-
getTotalMemoryAvailable
public static long getTotalMemoryAvailable()
Gets amount of RAM memory available on this machine.- Returns:
- Total amount of memory in bytes or -1 if any exception happened.
-
getCompilerMx
public static CompilationMXBean getCompilerMx()
Gets compilation MBean.- Returns:
- Compilation MBean.
-
detectClass
public static Class<?> detectClass(Object obj)
Tries to detect user class from passed in object inspecting collections, arrays or maps.- Parameters:
obj- Object.- Returns:
- First non-JDK or deployment aware class or passed in object class.
-
detectClassLoader
public static ClassLoader detectClassLoader(Class<?> cls)
Detects class loader for given class.This method will first check if
Thread.getContextClassLoader()is appropriate. If yes, then context class loader will be returned, otherwise theClass.getClassLoader()will be returned.- Parameters:
cls- Class to find class loader for.- Returns:
- Class loader for given class (never
null).
-
detectObjectClassLoader
@Nullable public static @Nullable ClassLoader detectObjectClassLoader(@Nullable @Nullable Object obj)
Detects class loader for given object's class.- Parameters:
obj- Object to find class loader for class of.- Returns:
- Class loader for given object (possibly
null).
-
isLoadableBy
public static boolean isLoadableBy(String clsName, @Nullable @Nullable ClassLoader ldr)
Tests whether or not given class is loadable provided class loader.- Parameters:
clsName- Class name to test.ldr- Class loader to test with. Ifnull- we'll use system class loader instead. If System class loader is not set - this method will returnfalse.- Returns:
Trueif class is loadable,falseotherwise.
-
peerDeployAware0
public static GridPeerDeployAware peerDeployAware0(@Nullable @Nullable Iterable<?> c)
Gets the peer deploy aware instance for the object with the widest class loader. If collection isnull, empty or contains onlynulls - the peer deploy aware object based on system class loader will be returned.- Parameters:
c- Collection.- Returns:
- Peer deploy aware object from this collection with the widest class loader.
- Throws:
IllegalArgumentException- Thrown in case when common class loader for all elements in this collection cannot be found. In such case - peer deployment is not possible.
-
peerDeployAware0
public static GridPeerDeployAware peerDeployAware0(@Nullable @Nullable Object... c)
Gets the peer deploy aware instance for the object with the widest class loader. If array isnull, empty or contains onlynulls - the peer deploy aware object based on system class loader will be returned.- Parameters:
c- Objects.- Returns:
- Peer deploy aware object from this array with the widest class loader.
- Throws:
IllegalArgumentException- Thrown in case when common class loader for all elements in this array cannot be found. In such case - peer deployment is not possible.
-
peerDeployAware0
public static GridPeerDeployAware peerDeployAware0(Object obj)
Creates an instance ofGridPeerDeployAwarefor object. Checks, if the object is an instance of collection or object array.- Parameters:
obj- Object to deploy.- Returns:
GridPeerDeployAwareinstance for given object.
-
peerDeployAware
public static GridPeerDeployAware peerDeployAware(Object obj)
Creates an instance ofGridPeerDeployAwarefor object.- Parameters:
obj- Object to deploy.- Returns:
GridPeerDeployAwareinstance for given object.
-
detectPeerDeployAware
public static GridPeerDeployAware detectPeerDeployAware(GridPeerDeployAware obj)
Unwraps top level user class for wrapped objects.- Parameters:
obj- Object to check.- Returns:
- Top level user class.
-
isIgnite
public static boolean isIgnite(Class<?> cls)
Checks if given class is ofIgnitetype.- Parameters:
cls- Class to check.- Returns:
Trueif given class is ofIgnitetype.
-
isGrid
public static boolean isGrid(Class<?> cls)
Checks if given class is ofGridtype.- Parameters:
cls- Class to check.- Returns:
Trueif given class is ofGridtype.
-
compact
public static String compact(String s)
Replaces all occurrences oforg.apache.ignite.witho.a.i.,org.apache.ignite.internal.witho.a.i.i.,org.apache.ignite.internal.visor.witho.a.i.i.v.and- Parameters:
s- String to replace in.- Returns:
- Replaces string.
-
isJdk
public static boolean isJdk(Class<?> cls)
Check if given class is of JDK type.- Parameters:
cls- Class to check.- Returns:
Trueif object is JDK type.
-
isEnum
public static boolean isEnum(Class cls)
Check if given class represents a Enum.- Parameters:
cls- Class to check.- Returns:
Trueif this is a Enum class.
-
wait
public static void wait(Object mux) throws IgniteInterruptedCheckedException
ConvertsInterruptedExceptiontoIgniteCheckedException.- Parameters:
mux- Mux to wait on.- Throws:
IgniteInterruptedCheckedException- If interrupted.
-
unzip
public static void unzip(File zipFile, File toDir, @Nullable @Nullable IgniteLogger log) throws IOException
Unzip file to folder.- Parameters:
zipFile- ZIP file.toDir- Directory to unzip file content.log- Grid logger.- Throws:
IOException- In case of error.
-
assertionsEnabled
public static boolean assertionsEnabled()
- Returns:
Trueif assertions enabled.
-
osJdkString
public static String osJdkString()
Gets OS JDK string.- Returns:
- OS JDK string.
-
osString
public static String osString()
Gets OS string.- Returns:
- OS string.
-
jdkString
public static String jdkString()
Gets JDK string.- Returns:
- JDK string.
-
isLinux
public static boolean isLinux()
Indicates whether current OS is Linux flavor.- Returns:
trueif current OS is Linux -falseotherwise.
-
jdkName
public static String jdkName()
Gets JDK name.- Returns:
- JDK name.
-
jdkVendor
public static String jdkVendor()
Gets JDK vendor.- Returns:
- JDK vendor.
-
jdkVersion
public static String jdkVersion()
Gets JDK version.- Returns:
- JDK version.
-
osArchitecture
public static String osArchitecture()
Gets OS CPU-architecture.- Returns:
- OS CPU-architecture.
-
osName
public static String osName()
Gets underlying OS name.- Returns:
- Underlying OS name.
-
osVersion
public static String osVersion()
Gets underlying OS version.- Returns:
- Underlying OS version.
-
isMacOs
public static boolean isMacOs()
Indicates whether current OS is Mac OS.- Returns:
trueif current OS is Mac OS -falseotherwise.
-
isRedHat
public static boolean isRedHat()
- Returns:
Trueif current OS is RedHat.
-
isNetWare
public static boolean isNetWare()
Indicates whether current OS is Netware.- Returns:
trueif current OS is Netware -falseotherwise.
-
isSolaris
public static boolean isSolaris()
Indicates whether current OS is Solaris.- Returns:
trueif current OS is Solaris (SPARC or x86) -falseotherwise.
-
isSolarisSparc
public static boolean isSolarisSparc()
Indicates whether current OS is Solaris on Spark box.- Returns:
trueif current OS is Solaris SPARC -falseotherwise.
-
isSolarisX86
public static boolean isSolarisX86()
Indicates whether current OS is Solaris on x86 box.- Returns:
trueif current OS is Solaris x86 -falseotherwise.
-
isUnix
public static boolean isUnix()
Indicates whether current OS is UNIX flavor.- Returns:
trueif current OS is UNIX -falseotherwise.
-
isWindows
public static boolean isWindows()
Indicates whether current OS is Windows.- Returns:
trueif current OS is Windows (any versions) -falseotherwise.
-
isWindowsVista
public static boolean isWindowsVista()
Indicates whether current OS is Windows Vista.- Returns:
trueif current OS is Windows Vista -falseotherwise.
-
isWindows7
public static boolean isWindows7()
Indicates whether current OS is Windows 7.- Returns:
trueif current OS is Windows 7 -falseotherwise.
-
isWindows8
public static boolean isWindows8()
Indicates whether current OS is Windows 8.- Returns:
trueif current OS is Windows 8 -falseotherwise.
-
isWindows81
public static boolean isWindows81()
Indicates whether current OS is Windows 8.1.- Returns:
trueif current OS is Windows 8.1 -falseotherwise.
-
isWindows2k
public static boolean isWindows2k()
Indicates whether current OS is Windows 2000.- Returns:
trueif current OS is Windows 2000 -falseotherwise.
-
isWindows2003
public static boolean isWindows2003()
Indicates whether current OS is Windows Server 2003.- Returns:
trueif current OS is Windows Server 2003 -falseotherwise.
-
isWindows2008
public static boolean isWindows2008()
Indicates whether current OS is Windows Server 2008.- Returns:
trueif current OS is Windows Server 2008 -falseotherwise.
-
isWindows95
public static boolean isWindows95()
Indicates whether current OS is Windows 95.- Returns:
trueif current OS is Windows 95 -falseotherwise.
-
isWindows98
public static boolean isWindows98()
Indicates whether current OS is Windows 98.- Returns:
trueif current OS is Windows 98 -falseotherwise.
-
isWindowsNt
public static boolean isWindowsNt()
Indicates whether current OS is Windows NT.- Returns:
trueif current OS is Windows NT -falseotherwise.
-
isWindowsXp
public static boolean isWindowsXp()
Indicates whether current OS is Windows XP.- Returns:
trueif current OS is Windows XP-falseotherwise.
-
jvmSpec
public static String jvmSpec()
Gets JVM specification name.- Returns:
- JVM specification name.
-
jvmVersion
public static String jvmVersion()
Gets JVM implementation version.- Returns:
- JVM implementation version.
-
jvmVendor
public static String jvmVendor()
Gets JVM implementation vendor.- Returns:
- JVM implementation vendor.
-
jvmName
public static String jvmName()
Gets JVM implementation name.- Returns:
- JVM implementation name.
-
jvm32Bit
public static boolean jvm32Bit()
Does a best effort to detect if we a running on a 32-bit JVM.- Returns:
trueif detected that we are running on a 32-bit JVM.
-
compareVersionNumbers
public static int compareVersionNumbers(@Nullable @Nullable String v1, @Nullable @Nullable String v2)Compare java implementation version- Parameters:
v1- - java implementation versionv2- - java implementation version- Returns:
- the value
0ifv1 == v2; a value less than0ifv1 < v2; and a value greater than0ifv1 > v2
-
productVersion
public static IgniteProductVersion productVersion(ClusterNode node)
Gets node product version based on node attributes.- Parameters:
node- Node to get version from.- Returns:
- Version object.
-
isJavaVersionAtLeast
public static boolean isJavaVersionAtLeast(String v)
Compare running Java Runtime version withv- Parameters:
v- - java implementation version- Returns:
trueif running on Java Runtime version greater thanv
-
jreName
public static String jreName()
Gets Java Runtime name.- Returns:
- Java Runtime name.
-
jreVersion
public static String jreVersion()
Gets Java Runtime version.- Returns:
- Java Runtime 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.
-
isHotSpot
public static boolean isHotSpot()
Indicates whether HotSpot VM is used.- Returns:
trueif current JVM implementation is a Sun HotSpot VM,falseotherwise.
-
wrapThreadLoader
@Nullable public static <R> R wrapThreadLoader(ClassLoader ldr, Callable<R> c) throws IgniteCheckedException
Sets thread context class loader to the given loader, executes the closure, and then resets thread context class loader to its initial value.- Type Parameters:
R- Return type.- Parameters:
ldr- Class loader to run the closure under.c- Callable to run.- Returns:
- Return value.
- Throws:
IgniteCheckedException- If call failed.
-
wrapThreadLoader
@Nullable public static <R> R wrapThreadLoader(ClassLoader ldr, IgniteOutClosure<R> c)
Sets thread context class loader to the given loader, executes the closure, and then resets thread context class loader to its initial value.- Type Parameters:
R- Return type.- Parameters:
ldr- Class loader to run the closure under.c- Closure to run.- Returns:
- Return value.
-
wrapThreadLoader
public static void wrapThreadLoader(ClassLoader ldr, Runnable c)
Sets thread context class loader to the given loader, executes the closure, and then resets thread context class loader to its initial value.- Parameters:
ldr- Class loader to run the closure under.c- Closure to run.
-
toShortString
public static String toShortString(ClusterNode n)
Short node representation.- Parameters:
n- Grid node.- Returns:
- Short string representing the node.
-
toShortString
public static String toShortString(Collection<? extends ClusterNode> ns)
Short node representation.- Parameters:
ns- Grid nodes.- Returns:
- Short string representing the node.
-
toStringSafe
@Nullable public static @Nullable String toStringSafe(@Nullable @Nullable Object obj)
Get string representation of an object properly catching all exceptions.- Parameters:
obj- Object.- Returns:
- Result or
null.
-
toIntArray
public static int[] toIntArray(@Nullable @Nullable Collection<Integer> c)Converts collection of integers into array.- Parameters:
c- Collection of integers.- Returns:
- Integer array.
-
addAll
public static int[] addAll(int[] arr1, int[] arr2)- Parameters:
arr1- Array 1.arr2- Array 2.
-
toIntList
public static List<Integer> toIntList(@Nullable @org.jetbrains.annotations.Nullable int[] arr, IgnitePredicate<Integer>... p)
Converts array of integers into list.- Parameters:
arr- Array of integers.p- Optional predicate array.- Returns:
- List of integers.
-
toLongArray
public static long[] toLongArray(@Nullable @Nullable Collection<Long> c)Converts collection of integers into array.- Parameters:
c- Collection of integers.- Returns:
- Integer array.
-
toLongList
public static List<Long> toLongList(@Nullable @org.jetbrains.annotations.Nullable long[] arr)
Converts array of longs into list.- Parameters:
arr- Array of longs.- Returns:
- List of longs.
-
toLong
public static long toLong(int high, int low)Concats two integers to long.- Parameters:
high- Highest bits.low- Lowest bits.- Returns:
- Long.
-
toArray
public static <T> T[] toArray(Collection<? extends T> c, T[] arr)
Copies all elements from collection to array and asserts that array is big enough to hold the collection. This method should always be preferred toCollection.toArray(Object[])method.- Type Parameters:
T- Element type.- Parameters:
c- Collection to convert to array.arr- Array to populate.- Returns:
- Passed in array.
-
swap
public static void swap(Object[] arr, int a, int b)
Swaps two objects in array.- Parameters:
arr- Array.a- Index of the first object.b- Index of the second object.
-
unique
public static int[] unique(int[] a, int aLen, int[] b, int bLen)Returns array which is the union of two arrays (array of elements contained in any of provided arrays). Note: arrays must be increasing.- Parameters:
a- First array.aLen- Length of prefixa.b- Second array.bLen- Length of prefixb.- Returns:
- Increasing array which is union of
aandb.
-
difference
public static int[] difference(int[] a, int aLen, int[] b, int bLen)Returns array which is the difference between two arrays (array of elements contained in first array but not contained in second). Note: arrays must be increasing.- Parameters:
a- First array.aLen- Length of prefixa.b- Second array.bLen- Length of prefixb.- Returns:
- Increasing array which is difference between
aandb.
-
isIncreasingArray
public static boolean isIncreasingArray(int[] arr, int len)Checks if array prefix increases.- Parameters:
arr- Array.len- Prefix length.- Returns:
Trueifarrfrom 0 to (len- 1) increases.
-
isNonDecreasingArray
public static boolean isNonDecreasingArray(int[] arr, int len)Checks if array prefix do not decreases.- Parameters:
arr- Array.len- Prefix length.- Returns:
Trueifarrfrom 0 to (len- 1) do not decreases.
-
copyIfExceeded
public static int[] copyIfExceeded(int[] arr, int len)Copies array only if array length greater than needed length.- Parameters:
arr- Array.len- Prefix length.- Returns:
- Old array if length of
arris equals tolen, otherwise copy of array.
-
addAll
public static <V,C extends Collection<? super V>> C addAll(C c, V... vals)
Adds values to collection and returns the same collection to allow chaining.- Type Parameters:
V- Value type.- Parameters:
c- Collection to add values to.vals- Values.- Returns:
- Passed in collection.
-
addAll
public static <K,V,M extends Map<K,V>> M addAll(M m, Map.Entry<K,V>... entries)
Adds values to collection and returns the same collection to allow chaining.- Type Parameters:
K- Key type.V- Value type.M- Map type.- Parameters:
m- Map to add entries to.entries- Entries.- Returns:
- Passed in collection.
-
addAll
public static <K,V,M extends Map<K,V>> M addAll(M m, IgniteBiTuple<K,V>... entries)
Adds values to collection and returns the same collection to allow chaining.- Type Parameters:
K- Key type.V- Value type.M- Map type.- Parameters:
m- Map to add entries to.entries- Entries.- Returns:
- Passed in collection.
-
jmException
public static JMException jmException(Throwable e)
Utility method creatingJMExceptionwith given cause. Keeps only the error message to avoid deserialization failure on remote side due to the other class path.- Parameters:
e- Cause exception.- Returns:
- Newly created
JMException.
-
unwrap
public static Exception unwrap(Throwable t)
Unwraps closure exceptions.- Parameters:
t- Exception.- Returns:
- Unwrapped exception.
-
cast
public static IgniteCheckedException cast(Throwable t)
Casts the passedThrowable ttoIgniteCheckedException.
Iftis aGridClosureException, it is unwrapped and then cast toIgniteCheckedException. Iftis anIgniteCheckedException, it is returned. Iftis not aIgniteCheckedException, a newIgniteCheckedExceptioncaused bytis returned.- Parameters:
t- Throwable to cast.- Returns:
tcast toIgniteCheckedException.
-
p2pLoader
public static boolean p2pLoader(Object o)
Checks if class loader is an internal P2P class loader.- Parameters:
o- Object to check.- Returns:
Trueif P2P class loader.
-
p2pLoader
public static boolean p2pLoader(ClassLoader ldr)
Checks if class loader is an internal P2P class loader.- Parameters:
ldr- Class loader to check.- Returns:
Trueif P2P class loader.
-
contextDeploymentClassLoaderId
public static IgniteUuid contextDeploymentClassLoaderId(GridKernalContext ctx)
Returns Deployment class loader id if method was invoked in the job context (it may be the context of a cache's operation which was triggered by the distributed job) ornullif no context was found or Deployment is switched off.- Parameters:
ctx- Kernal context.- Returns:
- Deployment class loader id or
null.
-
deploymentClassLoader
public static ClassLoader deploymentClassLoader(GridKernalContext ctx, IgniteUuid ldrId)
Gets that deployment class loader matching by the specific id, ornullif the class loader was not found.- Parameters:
ctx- Kernal context.ldrId- Class loader id.- Returns:
- Deployment class loader or
null.
-
restoreDeploymentContext
public static void restoreDeploymentContext(GridKernalContext ctx, IgniteUuid ldrId)
Restores a deployment context for cache deployment.- Parameters:
ctx- Kernal context.ldrId- Class loader id.
-
id2Node
public static IgniteClosure<UUID,ClusterNode> id2Node(GridKernalContext ctx)
- Parameters:
ctx- Kernal context.- Returns:
- Closure that converts node ID to a node.
-
dumpStack
@Deprecated public static void dumpStack(Thread t)
Deprecated.Calls to this method should never be committed to master.Dumps stack for given thread.- Parameters:
t- Thread to dump stack for.
-
dumpStack
@Deprecated public static void dumpStack(Thread t, PrintStream s)
Deprecated.Calls to this method should never be committed to master.Dumps stack for given thread.- Parameters:
t- Thread to dump stack for.s-PrintStreamto use for output.
-
isPrimitiveArray
public static boolean isPrimitiveArray(Object obj)
Checks if object is a primitive array.- Parameters:
obj- Object to check.- Returns:
Trueif Object is primitive array.
-
isPrimitiveOrWrapper
public static boolean isPrimitiveOrWrapper(Class<?> cls)
- Parameters:
cls- Class.- Returns:
Trueif given class represents a primitive or a primitive wrapper class.
-
await
public static void await(Condition cond) throws IgniteInterruptedCheckedException
Awaits for condition.- Parameters:
cond- Condition to await for.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException
-
awaitQuiet
public static void awaitQuiet(Condition cond)
Awaits for condition ignoring interrupts.- Parameters:
cond- Condition to await for.
-
await
public static boolean await(Condition cond, long time, TimeUnit unit) throws IgniteInterruptedCheckedException
Awaits for condition.- Parameters:
cond- Condition to await for.time- The maximum time to wait,unit- The unit of thetimeargument.- Returns:
falseif the waiting time detectably elapsed before return from the method, elsetrue- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException
-
await
public static void await(CountDownLatch latch) throws IgniteInterruptedCheckedException
Awaits for the latch.- Parameters:
latch- Latch to wait for.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException.
-
await
public static boolean await(CountDownLatch latch, long timeout, TimeUnit unit) throws IgniteInterruptedCheckedException
Awaits for the latch.- Parameters:
latch- Latch to wait for.timeout- Maximum time to wait.unit- Time unit for timeout.- Returns:
Trueif the count reached zero andfalseif the waiting time elapsed before the count reached zero.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException.
-
awaitQuiet
public static void awaitQuiet(CountDownLatch latch)
Awaits for the latch until it is counted down, ignoring interruptions.If calling thread was interrupted, interrupted status will be recovered prior to return.
- Parameters:
latch- Latch to wait for.
-
awaitQuiet
public static void awaitQuiet(CyclicBarrier barrier)
Awaits for the barrier ignoring interruptions.If calling thread was interrupted, interrupted status will be recovered prior to return. If the barrier is already broken, return immediately without throwing any exceptions.
- Parameters:
barrier- Barrier to wait for.
-
classLoaderUrls
public static URL[] classLoaderUrls(ClassLoader clsLdr)
Returns URLs of class loader- Parameters:
clsLdr- Class loader.
-
sleep
public static void sleep(long ms) throws IgniteInterruptedCheckedExceptionSleeps for given number of milliseconds.- Parameters:
ms- Time to sleep.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException.
-
join
public static void join(GridWorker w) throws IgniteInterruptedCheckedException
Joins worker.- Parameters:
w- Worker.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException.
-
get
public static <T> T get(Future<T> fut) throws IgniteCheckedException
Gets result from the given future with right exception handling.- Parameters:
fut- Future.- Returns:
- Future result.
- Throws:
IgniteCheckedException- If failed.
-
join
public static void join(@Nullable @Nullable Thread t) throws IgniteInterruptedCheckedExceptionJoins thread.- Parameters:
t- Thread.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException.
-
acquire
public static void acquire(Semaphore sem) throws IgniteInterruptedCheckedException
Acquires a permit from provided semaphore.- Parameters:
sem- Semaphore.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException.
-
tryAcquire
public static boolean tryAcquire(Semaphore sem, long timeout, TimeUnit unit) throws IgniteInterruptedCheckedException
Tries to acquire a permit from provided semaphore duringtimeout.- Parameters:
sem- Semaphore.timeout- The maximum time to wait.unit- The unit of thetimeargument.- Returns:
Trueif acquires a permit,falseanother.- Throws:
IgniteInterruptedCheckedException- WrappedInterruptedException.
-
cacheAttributes
public static GridCacheAttributes[] cacheAttributes(ClusterNode n)
Gets cache attributes for the node.- Parameters:
n- Node to get cache attributes for.- Returns:
- Array of cache attributes for the node.
-
hasNearCache
public static boolean hasNearCache(ClusterNode n, String cacheName)
Checks if given node has near cache enabled for the specified partitioned cache.- Parameters:
n- Node.cacheName- Cache name.- Returns:
trueif given node has near cache enabled for the specified partitioned cache.
-
asyncLogError
public static void asyncLogError(IgniteInternalFuture<?> f, IgniteLogger log)
Adds listener to asynchronously log errors.- Parameters:
f- Future to listen to.log- Logger.
-
nodeIds
public static Collection<UUID> nodeIds(@Nullable @Nullable Collection<? extends ClusterNode> nodes)
Converts collection of nodes to collection of node IDs.- Parameters:
nodes- Nodes.- Returns:
- Node IDs.
-
gridIds
public static Collection<UUID> gridIds(@Nullable @Nullable Collection<? extends Ignite> grids)
Converts collection of Grid instances to collection of node IDs.- Parameters:
grids- Grids.- Returns:
- Node IDs.
-
grids2names
public static Collection<String> grids2names(@Nullable @Nullable Collection<? extends Ignite> grids)
Converts collection of Grid instances to collection of grid names.- Parameters:
grids- Grids.- Returns:
- Grid names.
-
nodes2names
public static Collection<String> nodes2names(@Nullable @Nullable Collection<? extends ClusterNode> nodes)
Converts collection of grid nodes to collection of grid names.- Parameters:
nodes- Nodes.- Returns:
- Grid names.
-
addLastCause
public static boolean addLastCause(@Nullable @Nullable Throwable e, @Nullable @Nullable Throwable cause, IgniteLogger log)Adds cause to the end of cause chain.- Parameters:
e- Error to add cause to.cause- Cause to add.log- Logger to log failure when cause can not be added.- Returns:
Trueif cause was added.
-
nl
public static String nl()
- Returns:
line.separatorsystem property.
-
logger
public static IgniteLogger logger(GridKernalContext ctx, AtomicReference<IgniteLogger> logRef, Object obj)
Initializes logger into/from log reference passed in.- Parameters:
ctx- Context.logRef- Log reference.obj- Object to get logger for.- Returns:
- Logger for the object.
-
logger
public static IgniteLogger logger(GridKernalContext ctx, AtomicReference<IgniteLogger> logRef, Class<?> cls)
Initializes logger into/from log reference passed in.- Parameters:
ctx- Context.logRef- Log reference.cls- Class to get logger for.- Returns:
- Logger for the object.
-
concurrentMapSegment
public static int concurrentMapSegment(int hash, int concurLvl)- Parameters:
hash- Hash code of the object to put.concurLvl- Concurrency level.- Returns:
- Segment index.
-
printConcurrentHashMapInfo
public static <K,V> void printConcurrentHashMapInfo(ConcurrentHashMap<K,V> map)
- Parameters:
map- Map.
-
field
public static <T> T field(Object obj, String fieldName)
Gets field value.- Parameters:
obj- Object.fieldName- Field name.- Returns:
- Field value.
-
hasField
public static boolean hasField(Object obj, String fieldName)
Check that field exist.- Parameters:
obj- Object.fieldName- Field name.- Returns:
- Boolean flag.
-
fieldOffset
public static long fieldOffset(Class<?> cls, String fieldName)
Gets object field offset.- Parameters:
cls- Object class.fieldName- Field name.- Returns:
- Field offset.
-
isFinal
public static boolean isFinal(Class<?> cls)
- Parameters:
cls- Class to check.- Returns:
Trueif class is final.
-
field
public static <T> T field(Class<?> cls, String fieldName) throws IgniteCheckedException
Gets field value.- Parameters:
cls- Class.fieldName- Field name.- Returns:
- Field value.
- Throws:
IgniteCheckedException- If static field with given name cannot be retreived.
-
invoke
public static <T> T invoke(@Nullable @Nullable Class<?> cls, @Nullable @Nullable Object obj, String mtdName, Object... params) throws IgniteCheckedExceptionInvokes method.- Parameters:
cls- Object.obj- Object.mtdName- Field name.params- Parameters.- Returns:
- Field value.
- Throws:
IgniteCheckedException- If static field with given name cannot be retreived.
-
invoke
public static <T> T invoke(@Nullable @Nullable Class<?> cls, @Nullable @Nullable Object obj, String mtdName, Class[] paramTypes, Object... params) throws IgniteCheckedExceptionInvokes method.- Parameters:
cls- Object.obj- Object.mtdName- Field name.paramTypes- Parameter types.params- Parameters.- Returns:
- Field value.
- Throws:
IgniteCheckedException- If static field with given name cannot be retrieved.
-
property
public static <T> T property(Object obj, String propName)
Gets property value.- Parameters:
obj- Object.propName- Property name.- Returns:
- Field value.
-
staticField
public static <T> T staticField(Class<?> cls, String fieldName) throws IgniteCheckedException
Gets static field value.- Parameters:
cls- Class.fieldName- Field name.- Returns:
- Field value.
- Throws:
IgniteCheckedException- If failed.
-
isVisorNodeStartProperty
public static boolean isVisorNodeStartProperty(String name)
Checks whether property is one added by Visor when node is started via remote SSH session.- Parameters:
name- Property name to check.- Returns:
Trueif property is Visor node startup property,falseotherwise.
-
isVisorRequiredProperty
public static boolean isVisorRequiredProperty(String name)
Checks whether property is one required by Visor to work correctly.- Parameters:
name- Property name to check.- Returns:
Trueif property is required by Visor,falseotherwise.
-
addJavaNoOpLogger
public static Collection<Handler> addJavaNoOpLogger()
Adds no-op console handler for root java logger.- Returns:
- Removed handlers.
-
removeJavaNoOpLogger
public static void removeJavaNoOpLogger(Collection<Handler> rmvHnds)
Removes previously added no-op handler for root java logger.- Parameters:
rmvHnds- Previously removed handlers.
-
nodeIdLogFileName
public static String nodeIdLogFileName(UUID nodeId, String fileName)
Attaches node ID to log file name.- Parameters:
nodeId- Node ID.fileName- File name.- Returns:
- File name with node ID.
-
customDirectoryLogFileName
public static String customDirectoryLogFileName(@Nullable @Nullable String dir, String fileName)
Substitutes log directory with a custom one.- Parameters:
dir- Directory.fileName- Original path.- Returns:
- New path.
-
fl
public static String fl(String msg, Object... args)
Creates string for log output.- Parameters:
msg- Message to start string.args- Even length array where the odd elements are parameter names and even elements are parameter values.- Returns:
- Log message, formatted as recommended by Ignite guidelines.
-
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.
-
safeAbs
public static int safeAbs(int i)
Gets absolute value for integer. If integer isInteger.MIN_VALUE, then0is returned.- Parameters:
i- Integer.- Returns:
- Absolute value.
-
safeAbs
public static long safeAbs(long i)
Gets absolute value for long. If argument isLong.MIN_VALUE, then0is returned.- Parameters:
i- Argument.- Returns:
- Absolute value.
-
ensurePositive
public static long ensurePositive(long i, long dflt)Whenlongvalue given is positive returns that value, otherwise returns provided default value.- Parameters:
i- Input value.dflt- Default value.- Returns:
iifi > 0anddfltotherwise.
-
box
@Nullable public static @Nullable Class<?> box(@Nullable @Nullable Class<?> cls)
Gets wrapper class for a primitive type.- Parameters:
cls- Class. Ifnull, method is no-op.- Returns:
- Wrapper class or original class if it is non-primitive.
-
forName
public static Class<?> forName(String clsName, @Nullable @Nullable ClassLoader ldr) throws ClassNotFoundException
Gets class for provided name. Accepts primitive types names.- Parameters:
clsName- Class name.ldr- Class loader.- Returns:
- Class.
- Throws:
ClassNotFoundException- If class not found.
-
forName
public static Class<?> forName(String clsName, @Nullable @Nullable ClassLoader ldr, IgnitePredicate<String> clsFilter) throws ClassNotFoundException
Gets class for provided name. Accepts primitive types names.- Parameters:
clsName- Class name.ldr- Class loader.- Returns:
- Class.
- Throws:
ClassNotFoundException- If class not found.
-
forName
public static Class<?> forName(String clsName, @Nullable @Nullable ClassLoader ldr, 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.
-
hash
public static int hash(int h)
Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions. This is critical because ConcurrentHashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ in lower or upper bits.This function has been taken from Java 8 ConcurrentHashMap with slightly modifications.
- Parameters:
h- Value to hash.- Returns:
- Hash value.
-
hash
public static int hash(Object key)
Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions. This is critical because ConcurrentHashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ in lower or upper bits.This function has been taken from Java 8 ConcurrentHashMap with slightly modifications.
- Parameters:
key- Value to hash.- Returns:
- Hash value.
-
hash
public static int hash(long key)
A primitive override ofhash(Object)to avoid unnecessary boxing.- Parameters:
key- Value to hash.- Returns:
- Hash value.
-
jvmPid
public static int jvmPid()
- Returns:
- PID of the current JVM or
-1if it can't be determined.
-
jvmArgs
public static List<String> jvmArgs()
- Returns:
- Input arguments passed to the JVM which does not include the arguments to the main method.
-
arrayCopy
public static int arrayCopy(byte[] src, int off, byte[] resBuf, int resOff, int len)- Parameters:
src- Buffer to copy from (length included).off- Offset in source buffer.resBuf- Result buffer.resOff- Result offset.len- Length.- Returns:
- Number of bytes overwritten in
bytesarray.
-
consistentId
public static String consistentId(Collection<String> addrs)
- Parameters:
addrs- Node's addresses.- Returns:
- A string compatible with
ClusterNode.consistentId()requirements.
-
consistentId
public static String consistentId(Collection<String> addrs, int port)
- Parameters:
addrs- Node's addresses.port- Port discovery number.- Returns:
- A string compatible with
ClusterNode.consistentId()requirements.
-
maskForFileName
public static String maskForFileName(CharSequence name)
Masks name for a valid directory path.- Parameters:
name- Name.- Returns:
- Masked name.
-
overridesEqualsAndHashCode
public static boolean overridesEqualsAndHashCode(Object obj)
- Parameters:
obj- Object.- Returns:
Trueif given object has overridden equals and hashCode method.
-
overridesEqualsAndHashCode
public static boolean overridesEqualsAndHashCode(Class<?> cls)
- Parameters:
cls- Class.- Returns:
Trueif given class has overridden equals and hashCode method.
-
isMacInvalidArgumentError
public static boolean isMacInvalidArgumentError(Exception e)
Checks if error is MAC invalid argument error which ususally requires special handling.- Parameters:
e- Exception.- Returns:
Trueif error is invalid argument error on MAC.
-
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.
-
startLifecycleAware
public static void startLifecycleAware(Iterable<?> objs) throws IgniteCheckedException
For each object provided by the givenIterablechecks if it implementsLifecycleAwareinterface and executesLifecycleAware.start()method.- Parameters:
objs- Objects.- Throws:
IgniteCheckedException- IfLifecycleAware.start()fails.
-
stopLifecycleAware
public static void stopLifecycleAware(IgniteLogger log, Iterable<?> objs)
For each object provided by the givenIterablechecks if it implementsLifecycleAwareinterface and executesLifecycleAware.stop()method.- Parameters:
log- Logger used to log error message in case of stop failure.objs- Object passed to Ignite configuration.
-
neighborhood
public static Map<String,Collection<ClusterNode>> neighborhood(Iterable<ClusterNode> nodes)
Groups given nodes by the node's physical computer (host).Detection of the same physical computer (host) is based on comparing set of network interface MACs. If two nodes have the same set of MACs, Ignite considers these nodes running on the same physical computer.
- Parameters:
nodes- Nodes.- Returns:
- Collection of projections where each projection represents all nodes (in this projection) from a single physical computer. Result collection can be empty if this projection is empty.
-
toSocketAddresses
public static Collection<InetSocketAddress> toSocketAddresses(ClusterNode node, int port)
Returns the list of resolved socket addresses.- Parameters:
node- Grid node.port- Port.- Returns:
- Socket addresses for given addresses and host names.
-
toSocketAddresses
public static Collection<InetSocketAddress> toSocketAddresses(Collection<String> addrs, Collection<String> hostNames, int port)
Returns the list of resolved socket addresses.- Parameters:
addrs- Addresses.hostNames- Host names.port- Port.- Returns:
- Socket addresses for given addresses and host names.
-
resolveAddresses
public static Collection<InetSocketAddress> resolveAddresses(AddressResolver addrRslvr, Iterable<String> addrs, int port) throws IgniteSpiException
Resolves all not loopback addresses and collect results.- Parameters:
addrRslvr- Address resolver.addrs- Addresses.port- Port.- Returns:
- Resolved socket addresses.
- Throws:
IgniteSpiException- If failed.
-
resolveAddresses
public static Collection<InetSocketAddress> resolveAddresses(AddressResolver addrRslvr, Collection<InetSocketAddress> sockAddr)
- Parameters:
addrRslvr- Address resolver.sockAddr- Addresses.- Returns:
- Resolved addresses.
-
addressesAsString
public static String addressesAsString(ClusterNode node)
Returns string representation of node addresses.- Parameters:
node- Grid node.- Returns:
- String representation of addresses.
-
addressesAsString
public static String addressesAsString(Collection<String> addrs, Collection<String> hostNames)
Returns string representation of addresses.- Parameters:
addrs- Addresses.hostNames- Host names.- Returns:
- String representation of addresses.
-
defaultWorkDirectory
public static String defaultWorkDirectory() throws IgniteCheckedException
Get default work directory.- Returns:
- Default work directory.
- Throws:
IgniteCheckedException
-
workDirectory
public static String workDirectory(@Nullable @Nullable String userWorkDir, @Nullable @Nullable String userIgniteHome) throws IgniteCheckedException
Get work directory for the given user-provided work directory and Ignite home.- Parameters:
userWorkDir- Ignite work folder provided by user.userIgniteHome- Ignite home folder provided by user.- Throws:
IgniteCheckedException
-
nullifyHomeDirectory
public static void nullifyHomeDirectory()
Nullifies Ignite home directory. For test purposes only.
-
resolveWorkDirectory
public static File resolveWorkDirectory(String workDir, String path, boolean delIfExist) throws IgniteCheckedException
Resolves work directory.- Parameters:
workDir- Work directory.path- Path to resolve.delIfExist- Flag indicating whether to delete the specify directory or not.- Returns:
- Resolved work directory.
- Throws:
IgniteCheckedException- If failed.
-
resolveWorkDirectory
public static File resolveWorkDirectory(String workDir, String path, boolean delIfExist, boolean create) throws IgniteCheckedException
Resolves work directory.- Parameters:
workDir- Work directory.path- Path to resolve.delIfExist- Flag indicating whether to delete the specify directory or not.create- Iftruethen directory must be created if not exists.- Returns:
- Resolved work directory.
- Throws:
IgniteCheckedException- If failed.
-
ensureDirectory
public static void ensureDirectory(File dir, String msg, IgniteLogger log) throws IgniteCheckedException
Checks if the given directory exists and attempts to create one if not.- Parameters:
dir- Directory to check.msg- Directory name for the messages.log- Optional logger to log a message that the directory has been resolved.- Throws:
IgniteCheckedException- If directory does not exist and failed to create it, or if a file with the same name already exists.
-
ensureDirectory
public static void ensureDirectory(Path dir, String msg, IgniteLogger log) throws IgniteCheckedException
Checks if the given directory exists and attempts to create one if not.- Parameters:
dir- Directory to check.msg- Directory name for the messages.log- Optional logger to log a message that the directory has been resolved.- Throws:
IgniteCheckedException- If directory does not exist and failed to create it, or if a file with the same name already exists.
-
exceptionWithSuppressed
public static IgniteCheckedException exceptionWithSuppressed(String msg, @Nullable @Nullable Collection<Throwable> suppressed)
CreatesIgniteCheckedExceptionwith the collection of suppressed exceptions.- Parameters:
msg- Message.suppressed- The collections of suppressed exceptions.- Returns:
IgniteCheckedException.
-
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
nullif passed in name is not related to lambda.
-
toDigit
public static int toDigit(char ch, int idx) throws IgniteCheckedExceptionConverts a hexadecimal character to an integer.- Parameters:
ch- A character to convert to an integer digitidx- The index of the character in the source- Returns:
- An integer
- Throws:
IgniteCheckedException- Thrown if ch is an illegal hex character
-
oldest
public static ClusterNode oldest(Collection<ClusterNode> c, @Nullable @Nullable IgnitePredicate<ClusterNode> p)
Gets oldest node out of collection of nodes.- Parameters:
c- Collection of nodes.- Returns:
- Oldest node.
-
youngest
public static ClusterNode youngest(Collection<ClusterNode> c, @Nullable @Nullable IgnitePredicate<ClusterNode> p)
Gets youngest node out of collection of nodes.- Parameters:
c- Collection of nodes.- Returns:
- Youngest node.
-
copyMemory
public static byte[] copyMemory(long ptr, int size)- Parameters:
ptr- Address.size- Size.- Returns:
- Bytes.
-
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.
-
newHashMap
public static <K,V> HashMap<K,V> newHashMap(int expSize)
Creates newHashMapwith 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 newLinkedHashMapwith 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 newHashSetwith 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 newLinkedHashSetwith 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.
-
map
public static <K,V> Map<K,V> map(K k, V v)
Create a map with single key-value pair.- Parameters:
k- Key.v- Value.- Returns:
- Map.
-
map
public static <K,V> Map<K,V> map(K k1, V v1, K k2, V v2)
Create a map with two key-value pairs.- Parameters:
k1- Key 1.v1- Value 1.k2- Key 2.v2- Value 2.- Returns:
- Map.
-
map
public static <K,V> Map<K,V> map(K k1, V v1, K k2, V v2, K k3, V v3)
Create a map with three key-value pairs.- Parameters:
k1- Key 1.v1- Value 1.k2- Key 2.v2- Value 2.k3- Key 3.v3- Value 3.- Returns:
- Map.
-
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
-
inetAddressesComparator
public static Comparator<InetSocketAddress> inetAddressesComparator(boolean sameHost)
Returns comparator that sorts remote node addresses. If remote node resides on the same host, then put loopback addresses first, last otherwise.- Parameters:
sameHost-Trueif remote node resides on the same host,falseotherwise.- Returns:
- Comparator.
-
findNonPublicMethod
@Nullable public static @Nullable Method findNonPublicMethod(Class<?> cls, String name, Class<?>... paramTypes)
Finds a method in the class and it parents. Method.getMethod() does not return non-public method, Method.getDeclaratedMethod() does not look at parent classes.- Parameters:
cls- The class to search,name- Name of the method.paramTypes- Method parameters.- Returns:
- Method or
null.
-
getNonPublicMethod
@Nullable public static @Nullable Method getNonPublicMethod(Class<?> cls, String name, Class<?>... paramTypes)
Gets a method from the class. Method.getMethod() does not return non-public method.- Parameters:
cls- Target class.name- Name of the method.paramTypes- Method parameters.- Returns:
- Method or
null.
-
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.
-
findField
@Nullable public static @Nullable Field findField(Class<?> cls, String name)
- Parameters:
cls- The class to search.name- Name of a field to get.- Returns:
- Field or
null.
-
arrayList
public static <T extends R,R> List<R> arrayList(Collection<T> c, @Nullable @Nullable IgnitePredicate<? super T>... p)
- Parameters:
c- Collection.p- Optional filters.- Returns:
- Resulting array list.
-
arrayList
public static <T extends R,R> List<R> arrayList(Collection<T> c)
- Parameters:
c- Collection.- Returns:
- Resulting array list.
-
arrayList
public static <T extends R,R> List<R> arrayList(Iterator<T> c, int cap, @Nullable @Nullable IgnitePredicate<? super T>... p)
- Parameters:
c- Collection.cap- Initial capacity.p- Optional filters.- Returns:
- Resulting array list.
-
calculateMD5Digest
public static byte[] calculateMD5Digest(@NotNull @NotNull InputStream in) throws NoSuchAlgorithmException, IOExceptionCalculate MD5 digits.- Parameters:
in- Input stream.- Returns:
- Calculated MD5 digest for given input stream.
- Throws:
NoSuchAlgorithmException- If MD5 algorithm was not found.IOException- If an I/O exception occurs.
-
calculateMD5
public static String calculateMD5(InputStream in) throws NoSuchAlgorithmException, IOException
Calculate MD5 string.- Parameters:
in- Input stream.- Returns:
- Calculated MD5 string for given input stream.
- Throws:
NoSuchAlgorithmException- If MD5 algorithm was not found.IOException- If an I/O exception occurs.
-
writeMessageFully
public static int writeMessageFully(Message msg, OutputStream out, ByteBuffer buf, MessageWriter writer) throws IOException
Fully writes communication message to provided stream.- Parameters:
msg- Message.out- Stream to write to.buf- Byte buffer that will be passed toMessage.writeTo(ByteBuffer, MessageWriter)method.writer- Message writer.- Returns:
- Number of written bytes.
- Throws:
IOException- In case of error.
-
assertParameter
public static void assertParameter(boolean cond, String condDesc) throws IgniteExceptionThrows exception with uniform error message if given parameter's assertion condition isfalse.- Parameters:
cond- Assertion condition to check.condDesc- Description of failed condition.- Throws:
IgniteException
-
writeLock
public static void writeLock(ReadWriteLock lock) throws IgniteInterruptedCheckedException
- Parameters:
lock- Lock.- Throws:
IgniteInterruptedCheckedException- If interrupted.
-
isHashCodeMethod
public static boolean isHashCodeMethod(Method mtd)
- Returns:
- Whether provided method is
Object.hashCode().
-
isEqualsMethod
public static boolean isEqualsMethod(Method mtd)
- Returns:
- Whether provided method is
Object.equals(...).
-
isToStringMethod
public static boolean isToStringMethod(Method mtd)
- Returns:
- Whether provided method is
Object.toString().
-
threadName
public static String threadName(long threadId)
- Parameters:
threadId- Thread ID.- Returns:
- Thread name if found.
-
max
public static <T extends Comparable<? super T>> T max(T t0, T t1)
- Type Parameters:
T- Comparable type.- Parameters:
t0- Comparable object.t1- Comparable object.- Returns:
- Maximal object o t0 and t1.
-
unmarshal
public static <T> T unmarshal(Marshaller marsh, InputStream in, @Nullable @Nullable ClassLoader clsLdr) throws IgniteCheckedException
Unmarshals object from the input stream using given class loader. This method should not close given input stream. This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Type Parameters:
T- Type of unmarshalled object.- Parameters:
in- Input stream.clsLdr- Class loader to use.- Returns:
- Unmarshalled object.
- Throws:
IgniteCheckedException- If unmarshalling failed.
-
unmarshalZip
public static <T> T unmarshalZip(Marshaller marsh, byte[] zipBytes, @Nullable @Nullable ClassLoader clsLdr) throws IgniteCheckedException
- Parameters:
marsh- Marshaller.zipBytes- Zip-compressed bytes.clsLdr- Class loader to use.- Returns:
- Unmarshalled object.
- Throws:
IgniteCheckedException
-
unzip
public static byte[] unzip(byte[] zipBytes) throws IgniteCheckedException- Parameters:
zipBytes- Zipped bytes.- Returns:
- Raw bytes.
- Throws:
IgniteCheckedException- If unzip resulted in error.
-
unmarshal
public static <T> T unmarshal(Marshaller marsh, byte[] arr, @Nullable @Nullable ClassLoader clsLdr) throws IgniteCheckedException
Unmarshals object from the input stream using given class loader. This method should not close given input stream. This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Type Parameters:
T- Type of unmarshalled object.- Parameters:
marsh- Marshaller.arr- Byte array.clsLdr- Class loader to use.- Returns:
- Unmarshalled object.
- Throws:
IgniteCheckedException- If unmarshalling failed.
-
unmarshal
public static <T> T unmarshal(GridKernalContext ctx, byte[] arr, @Nullable @Nullable ClassLoader clsLdr) throws IgniteCheckedException
Unmarshals object from the input stream using given class loader. This method should not close given input stream. This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Type Parameters:
T- Type of unmarshalled object.- Parameters:
ctx- Kernal contex.arr- Byte array.clsLdr- Class loader to use.- Returns:
- Unmarshalled object.
- Throws:
IgniteCheckedException- If unmarshalling failed.
-
unmarshal
public static <T> T unmarshal(GridCacheSharedContext ctx, byte[] arr, @Nullable @Nullable ClassLoader clsLdr) throws IgniteCheckedException
Unmarshals object from the input stream using given class loader. This method should not close given input stream. This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Type Parameters:
T- Type of unmarshalled object.- Parameters:
ctx- Kernal contex.arr- Byte array.clsLdr- Class loader to use.- Returns:
- Unmarshalled object.
- Throws:
IgniteCheckedException- If unmarshalling failed.
-
marshal
public static byte[] marshal(Marshaller marsh, Object obj) throws IgniteCheckedException
Marshals object to byte array. This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Parameters:
marsh- Marshaller.obj- Object to marshal.- Returns:
- Byte array.
- Throws:
IgniteCheckedException- If marshalling failed.
-
marshal
public static void marshal(Marshaller marsh, @Nullable @Nullable Object obj, OutputStream out) throws IgniteCheckedException
Marshals object to byte array. This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Parameters:
marsh- Marshaller.obj- Object to marshal.out- Output stream.- Throws:
IgniteCheckedException- If marshalling failed.
-
marshal
public static byte[] marshal(GridKernalContext ctx, Object obj) throws IgniteCheckedException
Marshals object to byte array. Wrap marshaller This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Parameters:
ctx- Kernal context.obj- Object to marshal.- Returns:
- Byte array.
- Throws:
IgniteCheckedException- If marshalling failed.
-
marshal
public static byte[] marshal(GridCacheSharedContext ctx, Object obj) throws IgniteCheckedException
Marshals object to byte array. Wrap marshaller This method wraps marshaller invocations and guaranty throwsIgniteCheckedExceptionin fail case.- Parameters:
ctx- Cache context.obj- Object to marshal.- Returns:
- Byte array.
- Throws:
IgniteCheckedException- If marshalling 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:
Trueif 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.
-
zip
public static byte[] zip(@Nullable @org.jetbrains.annotations.Nullable byte[] bytes) throws IgniteCheckedExceptionZip binary payload using default compression.- Parameters:
bytes- Byte array to compress.- Returns:
- Compressed bytes.
- Throws:
IgniteCheckedException- If failed.
-
zip
public static byte[] zip(@Nullable @org.jetbrains.annotations.Nullable byte[] bytes, int compressionLevel) throws IgniteCheckedException- Parameters:
bytes- Byte array to compress.compressionLevel- Level of compression to encode.- Returns:
- Compressed bytes.
- Throws:
IgniteCheckedException- If failed.
-
toBytes
public static byte[] toBytes(Serializable obj)
Serialize object to byte array.- Parameters:
obj- Object.- Returns:
- Serialized object.
-
fromBytes
public static <T> T fromBytes(byte[] data)
Deserialize object from byte array.- Parameters:
data- Serialized object.- Returns:
- Object.
-
checkpointBufferSize
public static long checkpointBufferSize(DataRegionConfiguration regCfg)
Get checkpoint buffer size for the given configuration.- Parameters:
regCfg- Configuration.- Returns:
- Checkpoint buffer size.
-
adjustedWalHistorySize
public static long adjustedWalHistorySize(DataStorageConfiguration dsCfg, @Nullable @Nullable IgniteLogger log)
Calculates maximum WAL archive size based on maximum checkpoint buffer size, if the default value ofDataStorageConfiguration.getMaxWalArchiveSize()is not overridden.- Returns:
- User-set max WAL archive size of triple size of the maximum checkpoint buffer.
-
fileCount
public static int fileCount(Path dir) throws IOException
Return count of regular file in the directory (including in sub-directories)- Parameters:
dir- path to directory- Returns:
- count of regular file
- Throws:
IOException- sometimes
-
dirSize
public static long dirSize(Path path) throws IgniteCheckedException
Will calculate the size of a directory. If there is concurrent activity in the directory, than returned value may be wrong.- Throws:
IgniteCheckedException
-
searchFileRecursively
public static Path searchFileRecursively(Path path, @NotNull @NotNull String name) throws IgniteCheckedException
- Parameters:
path- Path.name- Name.- Throws:
IgniteCheckedException
-
forRange
public static GridIntIterator forRange(int start, int cnt)
ReturnsGridIntIteratorfor range of primitive integers.- Parameters:
start- Start.cnt- Count.
-
nearestPow2
public static int nearestPow2(int x)
- Parameters:
x- X.
-
nearestPow2
public static int nearestPow2(int x, boolean less)- Parameters:
x- X.less- Less.
-
enhanceThreadName
public static void enhanceThreadName(String text)
Puts additional text to thread name. CallsenhanceThreadName(Thread.currentThread(), text). For details seeenhanceThreadName(Thread, String).- Parameters:
text- Text to be set in thread name in square [] braces. Does nothing if cannot find suitable braces.
-
enhanceThreadName
public static void enhanceThreadName(@Nullable @Nullable Thread thread, String text)Puts additional text to thread name. It finds first square braces in thread name and sets required text in them. For example, thread has name "my-thread-[]-%gridname%". After callingenhanceThreadName(thread, "myText"), the name of the thread will be "my-thread-[myText]-%gridname%".
This allows to set additional mutable info to thread, like remote host IP address or so.- Parameters:
thread- Thread to be renamed, it must contain square braces in name []. Does nothing ifnull.text- Text to be set in thread name in square [] braces. Does nothing if cannot find suitable braces.
-
getBaselineTopology
public static BaselineTopology getBaselineTopology(@NotNull @NotNull GridKernalContext ctx)
- Parameters:
ctx- Context.- Returns:
- instance of current baseline topology if it exists
-
getBaselineTopology
public static BaselineTopology getBaselineTopology(@NotNull @NotNull GridCacheSharedContext cctx)
- Parameters:
cctx- Context.- Returns:
- instance of current baseline topology if it exists
-
getBaselineTopology
public static BaselineTopology getBaselineTopology(@NotNull @NotNull GridCacheContext cctx)
- Parameters:
cctx- Context.- Returns:
- instance of current baseline topology if it exists
-
isOldestNodeVersionAtLeast
public static boolean isOldestNodeVersionAtLeast(IgniteProductVersion ver, Iterable<ClusterNode> nodes)
Check that node Ignite product version is not less then specified.- Parameters:
ver- Target Ignite product version.nodes- Cluster nodes.- Returns:
Trueif ignite product version of all nodes is not less thenver.
-
toHexString
public static String toHexString(long addr, int len)
- Parameters:
addr- pointer in memorylen- how much byte to read (should divide 8)- Returns:
- hex representation of memory region
-
toHexString
public static String toHexString(ByteBuffer buf)
- Parameters:
buf- which content should be converted to string- Returns:
- hex representation of memory region
-
randomServerNode
public static ClusterNode randomServerNode(GridKernalContext ctx)
- Parameters:
ctx- Kernel context.- Returns:
- Random alive server node.
-
availableThreadCount
public static int availableThreadCount(GridKernalContext ctx, byte plc, int reserved)
- Parameters:
ctx- Kernal context.plc- IO Policy.reserved- Thread to reserve.- Returns:
- Number of available threads in executor service for
plc. Ifplcis invalid, return1.
-
doInParallel
public static <T,R> Collection<R> doInParallel(ExecutorService executorSvc, Collection<T> srcDatas, IgniteThrowableFunction<T,R> operation) throws IgniteCheckedException, IgniteInterruptedCheckedException
Execute operation on data in parallel.- Type Parameters:
T- Type of data.- Parameters:
executorSvc- Service for parallel execution.srcDatas- List of data for parallelization.operation- Logic for execution of on each item of data.- Throws:
IgniteCheckedException- if parallel execution was failed.IgniteInterruptedCheckedException
-
doInParallel
public static <T,R> Collection<R> doInParallel(int parallelismLvl, ExecutorService executorSvc, Collection<T> srcDatas, IgniteThrowableFunction<T,R> operation) throws IgniteCheckedException, IgniteInterruptedCheckedException
Execute operation on data in parallel.- Type Parameters:
T- Type of data.R- Type of return value.- Parameters:
parallelismLvl- Number of threads on which it should be executed.executorSvc- Service for parallel execution.srcDatas- List of data for parallelization.operation- Logic for execution of on each item of data.- Throws:
IgniteCheckedException- if parallel execution was failed.IgniteInterruptedCheckedException
-
doInParallelUninterruptibly
public static <T,R> Collection<R> doInParallelUninterruptibly(int parallelismLvl, ExecutorService executorSvc, Collection<T> srcDatas, IgniteThrowableFunction<T,R> operation) throws IgniteCheckedException, IgniteInterruptedCheckedException
Execute operation on data in parallel uninterruptibly.- Type Parameters:
T- Type of data.R- Type of return value.- Parameters:
parallelismLvl- Number of threads on which it should be executed.executorSvc- Service for parallel execution.srcDatas- List of data for parallelization.operation- Logic for execution of on each item of data.- Throws:
IgniteCheckedException- if parallel execution was failed.IgniteInterruptedCheckedException
-
addSuppressed
public static <T extends Throwable> T addSuppressed(T root, T err)
Utility method to add the given throwable error to the given throwable root error. If the given suppressed throwable is anError, but the root error is not, will change the root to theError.- Parameters:
root- Root error to add suppressed error to.err- Error to add.- Returns:
- New root error.
-
isLocalNodeCoordinator
public static boolean isLocalNodeCoordinator(GridDiscoveryManager discoMgr)
- Returns:
trueif local node is coordinator.
-
calculateOptimalBatchSizes
public static int[] calculateOptimalBatchSizes(int parallelismLvl, int size)Split number of tasks into optimized batches.- Parameters:
parallelismLvl- Level of parallelism.size- number of tasks to split.- Returns:
- array of batch sizes.
-
wrapIgniteFuture
public static Runnable wrapIgniteFuture(Runnable r, GridFutureAdapter<?> fut)
- Parameters:
r- Runnable.fut- Grid future apater.- Returns:
- Runnable with wrapped future.
-
createCipher
public static Cipher createCipher(Key key, int encMode)
- Parameters:
key- Cipher Key.encMode- Enc mode seeCipher.ENCRYPT_MODE,Cipher.DECRYPT_MODE, etc.
-
writeFully
public static void writeFully(SocketChannel sockCh, ByteBuffer buf) throws IOException
Safely write buffer fully to blocking socket channel. Will throw assert if non blocking channel passed.- Parameters:
sockCh- WritableByteChannel.buf- Buffer.- Throws:
IOException- IOException.
-
newIdentityHashSet
public static <X> Set<X> newIdentityHashSet()
- Returns:
- New identity hash set.
-
stripeIdx
public static int stripeIdx(int stripes, int grpId, int partId)- Parameters:
stripes- Number of stripes.grpId- Group Id.partId- Partition Id.- Returns:
- Stripe idx.
-
isFlagSet
public static boolean isFlagSet(int flags, int flag)Check if flag set.- Parameters:
flags- Flags.flag- Flag.- Returns:
Trueif set.
-
notifyListeners
public static <T> void notifyListeners(T t, Collection<Consumer<T>> lsnrs, IgniteLogger log)Notifies providedlsnrswith the valuet.- Type Parameters:
T- Type of consumed object.- Parameters:
t- Consumed object.lsnrs- Listeners.
-
awaitForWorkersStop
public static void awaitForWorkersStop(Collection<GridWorker> workers, boolean cancel, @Nullable @Nullable IgniteLogger log)
Stops workers from given collection and waits for their completion.- Parameters:
workers- Workers collection.cancel- Wheter should cancel workers.log- Logger.
-
unquote
public static String unquote(String s)
Unquote the given string.- Parameters:
s- String.- Returns:
- Unquoted string.
-
writeLongString
public static void writeLongString(DataOutput out, @Nullable @Nullable String s) throws IOException
Writes string to output stream accounting fornullvalues.
This method can write string of any length, noUTF_BYTE_LIMITlimits are applied.- Parameters:
out- Output stream to write to.s- String to write, possiblynull.- Throws:
IOException- If write failed.
-
readLongString
@Nullable public static @Nullable String readLongString(DataInput in) throws IOException
Reads string from input stream accounting fornullvalues.
This method can read string of any length, noUTF_BYTE_LIMITlimits are applied.- Parameters:
in- Stream to read from.- Returns:
- Read string, possibly
null. - Throws:
IOException- If read failed.
-
writeCutString
public static void writeCutString(DataOutput out, @Nullable @Nullable String s) throws IOException
Writes string to output stream accounting fornullvalues.
Uses
ObjectOutputStream.writeUTF(String)to write the string under the hood but cuts strings longer thanUTF_BYTE_LIMITto the limit to avoidUTFDataFormatException.Strings written by the method can be read by
readString(DataInput).- Parameters:
out- Output stream to write to.s- String to write, possiblynull.- Throws:
IOException- If write failed.- See Also:
for more information.
-
utfBytes
public static int utfBytes(char c)
Get number of bytes forDataOutput.writeUTF(java.lang.String), depending on character:
One byte - If a charactercis in the range\u0001through\u007f.
Two bytes - If a charactercis\u0000or is in the range\u0080through\u07ff.
Three bytes - If a charactercis in the range\u0800throughuffff.- Parameters:
c- Character.- Returns:
- Number of bytes.
-
broadcastToNodesWithFilterAsync
public static IgniteFuture<Void> broadcastToNodesWithFilterAsync(GridKernalContext kctx, IgniteRunnable job, boolean srvrsOnly, IgnitePredicate<ClusterNode> nodeFilter)
Broadcasts given job to nodes that match filter.- Parameters:
kctx- Kernal context.job- Ignite job.srvrsOnly- Broadcast only on server nodes.nodeFilter- Node filter.
-
readStringMap
public static Map<String,String> readStringMap(DataInput in) throws IOException
Reads string-to-string map written bywriteStringMap(DataOutput, Map).- Parameters:
in- Data input.- Returns:
- Read result.
- Throws:
IOException- If write failed.
-
writeStringMap
public static void writeStringMap(DataOutput out, @Nullable @Nullable Map<String,String> map) throws IOException
Writes string-to-string map to given data output.- Parameters:
out- Data output.map- Map.- Throws:
IOException- If write failed.
-
writeUTF
public static void writeUTF(DataOutput out, @Nullable @Nullable String val) throws IOException
Write UTF string which can benull.- Parameters:
out- Output stream.val- Value.- Throws:
IOException- If failed.
-
readUTF
public static String readUTF(DataInput in) throws IOException
Read UTF string which can benull.- Parameters:
in- Input stream.- Returns:
- Value.
- Throws:
IOException- If failed.
-
humanReadableByteCount
public static String humanReadableByteCount(long bytes)
Converts count of bytes to a human-readable format. Examples: 10 -> 10.0 B, 2048 -> 2.0 KB, etc.- Parameters:
bytes- Byte count.- Returns:
- Human readable format for count of bytes.
-
humanReadableDuration
public static String humanReadableDuration(long millis)
Converts duration to a human-readable format. Examples: 10 -> 10ms, 6_0000 -> 6s, 65_000 -> 1m5s, (65 * 60_000 + 32_000) -> 1h5m32s, etc.- Parameters:
millis- Duration in milliseconds.- Returns:
- Human readable format for duration.
-
uncompressedSize
public static long uncompressedSize(File zip) throws IOException
Getting the total size of uncompressed data in zip.- Parameters:
zip- Zip file.- Returns:
- Total uncompressed size.
- Throws:
IOException- If failed.
-
hashToIndex
public static int hashToIndex(int hash, int size)Maps object hash to some index between 0 and specified size via modulo operation.- Parameters:
hash- Object hash.size- Size greater than 0.- Returns:
- Calculated index in range [0..size).
-
acceptServerSocket
public static Socket acceptServerSocket(ServerSocket srvrSock) throws IOException
InvokesServerSocket.accept()method on the passed server socked, working around the https://bugs.openjdk.java.net/browse/JDK-8247750 in the process.- Parameters:
srvrSock- Server socket.- Returns:
- New socket.
- Throws:
IOException- If an I/O error occurs when waiting for a connection.- See Also:
ServerSocket.accept()
-
language
public static String language(ClassLoader ldr)
- Returns:
- Language runtime.
-
isJmxRemoteEnabled
public static boolean isJmxRemoteEnabled()
- Returns:
Trueif remote JMX management is enabled -falseotherwise.
-
isRestEnabled
public static boolean isRestEnabled(IgniteConfiguration cfg)
- Returns:
trueif the REST processor is enabled,falsethe otherwise.
-
isRestartEnabled
public static boolean isRestartEnabled()
- Returns:
Trueif restart mode is enabled,falseotherwise.
-
isLambda
public static boolean isLambda(Class<?> objectClass)
Returnstrueif class is a lambda.- Parameters:
objectClass- Class.- Returns:
trueif class is a lambda,falseotherwise.
-
classCannotBeLoadedByName
public static boolean classCannotBeLoadedByName(Class<?> objectClass)
Returnstrueif class can not be loaded by name.- Parameters:
objectClass- Class.- Returns:
trueif class can not be loaded by name,falseotherwise.
-
extendToLen
public static String extendToLen(String s, int targetLen)
Appends spaces to end of input string for extending to needed length.- Parameters:
s- Input string.targetLen- Needed length.- Returns:
- String with appended spaces on the end.
-
isTxAwareQueriesEnabled
public static boolean isTxAwareQueriesEnabled(GridKernalContext kctx)
-
-