diff --git a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/TableDdlIntegrationTest.java b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/TableDdlIntegrationTest.java index 98ce8275f2111..052d7fe2d2bfa 100644 --- a/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/TableDdlIntegrationTest.java +++ b/modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/integration/TableDdlIntegrationTest.java @@ -24,6 +24,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -49,7 +50,6 @@ import org.junit.Test; import static org.apache.ignite.internal.processors.query.calcite.TestUtils.hasSize; -import static org.apache.ignite.internal.util.IgniteUtils.map; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.nullValue; @@ -83,7 +83,7 @@ public void createTableSimpleCase() { assertThat( ent.getFields(), equalTo(new LinkedHashMap<>( - map( + Map.of( "ID", Integer.class.getName(), "VAL", String.class.getName() ) diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/JettyRestProcessorAbstractSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/JettyRestProcessorAbstractSelfTest.java index 241ed9a41c6fe..967ab1141ad12 100644 --- a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/JettyRestProcessorAbstractSelfTest.java +++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/JettyRestProcessorAbstractSelfTest.java @@ -643,7 +643,7 @@ public void testPutComplexObject() throws Exception { */ @Test public void testPutJsonArray() throws Exception { - Map map = U.map("1", new int[] {1, 2, 3}); + Map map = Map.of("1", new int[] {1, 2, 3}); putObject(DEFAULT_CACHE_NAME, "1", map, Map.class.getName()); assertTrue(Map.class.isAssignableFrom(jcache().get(1).getClass())); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cache/QueryEntity.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cache/QueryEntity.java index 4324b9059f8a7..5b4e721e5ceec 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/cache/QueryEntity.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cache/QueryEntity.java @@ -22,6 +22,7 @@ import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -104,7 +105,7 @@ private QueryEntity(org.apache.ignite.cache.QueryEntity q) { qryFlds = new LinkedHashMap<>(qryFields); - aliases = U.copyMap(q.getAliases()); + aliases = new HashMap<>(q.getAliases()); Collection qryIdxs = q.getIndexes(); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java index 969c8e4c24d60..ab074cca183ad 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/pagemem/impl/PageMemoryNoStoreImpl.java @@ -42,7 +42,6 @@ import org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMetrics; import org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO; import org.apache.ignite.internal.util.GridUnsafe; -import org.apache.ignite.internal.util.IgniteUtils; import org.apache.ignite.internal.util.OffheapReadWriteLock; import org.apache.ignite.internal.util.offheap.GridOffHeapOutOfMemoryException; import org.apache.ignite.internal.util.typedef.internal.U; @@ -157,7 +156,7 @@ public class PageMemoryNoStoreImpl implements PageMemory { /** Concurrency lvl. */ private final int lockConcLvl = IgniteSystemProperties.getInteger( IGNITE_OFFHEAP_LOCK_CONCURRENCY_LEVEL, - IgniteUtils.nearestPow2(Runtime.getRuntime().availableProcessors() * 4) + U.nearestPow2(Runtime.getRuntime().availableProcessors() * 4, true) ); /** */ diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheWriteBehindStore.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheWriteBehindStore.java index 46a48c64ec732..6a7ca94f4f1df 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheWriteBehindStore.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheWriteBehindStore.java @@ -1536,15 +1536,6 @@ private void setNext(@Nullable Entry val, this.nextStoreOperation = storeOperation; } - /** - * Awaits a signal on flush condition. - * - * @throws IgniteInterruptedCheckedException If thread was interrupted. - */ - private void waitForFlush() throws IgniteInterruptedCheckedException { - U.await(flushCond); - } - /** * Signals flush condition. */ diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java index 172651fd33250..c82d28181c25f 100755 --- a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java @@ -17,7 +17,6 @@ package org.apache.ignite.internal.util; -import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -41,15 +40,11 @@ import java.io.Serializable; import java.io.StringWriter; import java.io.UTFDataFormatException; -import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.management.CompilationMXBean; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; -import java.lang.management.MemoryMXBean; import java.lang.management.MonitorInfo; -import java.lang.management.OperatingSystemMXBean; -import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Array; @@ -73,8 +68,6 @@ import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; -import java.net.URLConnection; -import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileLock; @@ -83,21 +76,11 @@ import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; -import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; import java.security.AccessController; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyManagementException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.security.PrivilegedAction; import java.security.ProtectionDomain; -import java.security.cert.X509Certificate; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; @@ -119,13 +102,11 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.NoSuchElementException; import java.util.Objects; import java.util.Properties; import java.util.Random; import java.util.ServiceLoader; import java.util.Set; -import java.util.StringTokenizer; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.BrokenBarrierException; @@ -142,7 +123,6 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReadWriteLock; @@ -159,35 +139,24 @@ import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -import javax.crypto.Cipher; -import javax.crypto.NoSuchPaddingException; import javax.management.DynamicMBean; import javax.management.JMException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; -import javax.naming.Context; -import javax.naming.NamingException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteClientDisconnectedException; -import org.apache.ignite.IgniteCompute; import org.apache.ignite.IgniteDeploymentException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteIllegalStateException; import org.apache.ignite.IgniteInterruptedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteSystemProperties; -import org.apache.ignite.binary.BinaryRawReader; -import org.apache.ignite.binary.BinaryRawWriter; -import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterGroupEmptyException; import org.apache.ignite.cluster.ClusterMetrics; import org.apache.ignite.cluster.ClusterNode; @@ -206,7 +175,6 @@ import org.apache.ignite.internal.IgniteDeploymentCheckedException; import org.apache.ignite.internal.IgniteFutureCancelledCheckedException; import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException; -import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.internal.IgniteNodeAttributes; import org.apache.ignite.internal.binary.GridBinaryMarshaller; @@ -222,25 +190,19 @@ import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager; import org.apache.ignite.internal.mxbean.IgniteStandardMXBean; import org.apache.ignite.internal.processors.cache.CacheClassLoaderMarker; -import org.apache.ignite.internal.processors.cache.GridCacheAttributes; -import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheSharedContext; import org.apache.ignite.internal.processors.cache.IgnitePeerToPeerClassLoadingException; -import org.apache.ignite.internal.processors.cluster.BaselineTopology; import org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException; import org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException; import org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException; import org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException; import org.apache.ignite.internal.util.future.GridFutureAdapter; -import org.apache.ignite.internal.util.future.IgniteFinishedFutureImpl; import org.apache.ignite.internal.util.future.IgniteFutureImpl; -import org.apache.ignite.internal.util.io.GridFilenameUtils; import org.apache.ignite.internal.util.lang.GridClosureException; import org.apache.ignite.internal.util.lang.GridPeerDeployAware; import org.apache.ignite.internal.util.lang.GridTuple; import org.apache.ignite.internal.util.lang.IgniteThrowableFunction; import org.apache.ignite.internal.util.typedef.C1; -import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.internal.util.typedef.P1; @@ -249,17 +211,14 @@ import org.apache.ignite.internal.util.typedef.internal.LT; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.SB; -import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.util.worker.GridWorker; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lang.IgniteClosure; -import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgniteFutureCancelledException; import org.apache.ignite.lang.IgniteFutureTimeoutException; import org.apache.ignite.lang.IgniteOutClosure; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteProductVersion; -import org.apache.ignite.lang.IgniteRunnable; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.logger.java.JavaLogger; @@ -301,13 +260,11 @@ import static org.apache.ignite.events.EventType.EVT_NODE_METRICS_UPDATED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_DATE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER; -import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CACHE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DATA_REGIONS_OFFHEAP_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_PID; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_OFFHEAP_SIZE; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PHY_RAM; -import static org.apache.ignite.internal.util.GridUnsafe.objectFieldOffset; import static org.apache.ignite.internal.util.GridUnsafe.putObjectVolatile; import static org.apache.ignite.internal.util.GridUnsafe.staticFieldBase; import static org.apache.ignite.internal.util.GridUnsafe.staticFieldOffset; @@ -329,12 +286,6 @@ public abstract class IgniteUtils extends CommonUtils { /** */ public static final long GB = 1024L * 1024 * 1024; - /** - * String limit in bytes for {@link DataOutput#writeUTF} and - * {@link DataInput#readUTF()}, that use "Modified UTF-8". - */ - public static final int UTF_BYTE_LIMIT = 65_535; - /** Minimum checkpointing page buffer size (may be adjusted by Ignite). */ public static final Long DFLT_MIN_CHECKPOINTING_PAGE_BUFFER_SIZE = GB / 4; @@ -382,9 +333,6 @@ public abstract class IgniteUtils extends CommonUtils { private static final ConcurrentMap, Collection>> p2pFields = new ConcurrentHashMap<>(); - /** Secure socket protocol to use. */ - private static final String HTTPS_PROTOCOL = "TLS"; - /** Default working directory name. */ private static final String DEFAULT_WORK_DIR = "work"; @@ -403,108 +351,30 @@ public abstract class IgniteUtils extends CommonUtils { /** Project home directory. */ private static volatile GridTuple ggHome; - /** OS JDK string. */ - private static final String osJdkStr; - /** OS string. */ private static final String osStr; /** JDK string. */ private static String jdkStr; - /** Indicates whether current OS is Windows 95. */ - private static boolean win95; - - /** Indicates whether current OS is Windows 98. */ - private static boolean win98; - - /** Indicates whether current OS is Windows NT. */ - private static boolean winNt; - - /** Indicates whether current OS is Windows Vista. */ - private static boolean winVista; - - /** Indicates whether current OS is Windows 7. */ - private static boolean win7; - - /** Indicates whether current OS is Windows 8. */ - private static boolean win8; - - /** Indicates whether current OS is Windows 8.1. */ - private static boolean win81; - /** Indicates whether current OS is some version of Windows. */ - private static boolean unknownWin; - - /** Indicates whether current OS is Windows 2000. */ - private static boolean win2k; - - /** Indicates whether current OS is Windows XP. */ - private static boolean winXp; - - /** Indicates whether current OS is Windows Server 2003. */ - private static boolean win2003; - - /** Indicates whether current OS is Windows Server 2008. */ - private static boolean win2008; + private static boolean win; /** Indicates whether current OS is UNIX flavor. */ private static boolean unix; - /** Indicates whether current OS is Solaris. */ - private static boolean solaris; - /** Indicates whether current OS is Linux flavor. */ private static boolean linux; - /** Indicates whether current OS is NetWare. */ - private static boolean netware; - /** Indicates whether current OS is Mac OS. */ private static boolean mac; - /** Indicates whether current OS is of RedHat family. */ - private static final boolean redHat; - - /** Indicates whether current OS architecture is Sun Sparc. */ - private static boolean sparc; - - /** Indicates whether current OS architecture is Intel X86. */ - private static boolean x86; - - /** Name of the underlying OS. */ - private static String osName; - - /** Version of the underlying OS. */ - private static String osVer; - - /** CPU architecture of the underlying OS. */ - private static String osArch; - - /** Name of the Java Runtime. */ - private static String javaRtName; - - /** Name of the Java Runtime version. */ - private static String javaRtVer; - - /** Name of the JDK vendor. */ - private static String jdkVendor; - /** Name of the JDK. */ private static String jdkName; /** Version of the JDK. */ private static String jdkVer; - /** Name of JVM specification. */ - private static String jvmSpecName; - - /** Version of JVM implementation. */ - private static String jvmImplVer; - - /** Vendor's name of JVM implementation. */ - private static String jvmImplVendor; - /** Name of the JVM implementation. */ private static String jvmImplName; @@ -690,41 +560,13 @@ public abstract class IgniteUtils extends CommonUtils { assertionsEnabled = assertionsEnabled0; } - redHat = Files.exists(Paths.get("/etc/redhat-release")); // RedHat family OS (Fedora, CentOS, RedHat) - String osName = System.getProperty("os.name"); String osLow = osName.toLowerCase(); // OS type detection. - if (osLow.contains("win")) { - if (osLow.contains("95")) - win95 = true; - else if (osLow.contains("98")) - win98 = true; - else if (osLow.contains("nt")) - winNt = true; - else if (osLow.contains("2000")) - win2k = true; - else if (osLow.contains("vista")) - winVista = true; - else if (osLow.contains("xp")) - winXp = true; - else if (osLow.contains("2003")) - win2003 = true; - else if (osLow.contains("2008")) - win2008 = true; - else if (osLow.contains("7")) - win7 = true; - else if (osLow.contains("8.1")) - win81 = true; - else if (osLow.contains("8")) - win8 = true; - else - unknownWin = true; - } - else if (osLow.contains("netware")) - netware = true; + if (osLow.contains("win")) + win = true; else if (osLow.contains("mac os")) mac = true; else { @@ -736,30 +578,17 @@ else if (osLow.contains("mac os")) break; } - // UNIX name detection. - if (osLow.contains("olaris") || osLow.contains("sunos")) - solaris = true; - else if (osLow.contains("inux")) + if (osLow.contains("inux")) linux = true; } String osArch = System.getProperty("os.arch"); - String archStr = osArch.toLowerCase(); - - // OS architecture detection. - if (archStr.contains("x86")) - x86 = true; - else if (archStr.contains("sparc")) - sparc = true; - String javaRtName = System.getProperty("java.runtime.name"); String javaRtVer = System.getProperty("java.runtime.version"); - String jdkVendor = System.getProperty("java.specification.vendor"); String jdkName = System.getProperty("java.specification.name"); String jdkVer = System.getProperty("java.specification.version"); String osVer = System.getProperty("os.version"); - String jvmSpecName = System.getProperty("java.vm.specification.name"); String jvmImplVer = System.getProperty("java.vm.version"); String jvmImplVendor = System.getProperty("java.vm.vendor"); String jvmImplName = System.getProperty("java.vm.name"); @@ -771,22 +600,12 @@ else if (archStr.contains("sparc")) jvmImplVer; osStr = osName + ' ' + osVer + ' ' + osArch; - osJdkStr = osLow + ", " + jdkStr; // Copy auto variables to static ones. - IgniteUtils.osName = osName; IgniteUtils.jdkName = jdkName; - IgniteUtils.jdkVendor = jdkVendor; IgniteUtils.jdkVer = jdkVer; IgniteUtils.jdkStr = jdkStr; - IgniteUtils.osVer = osVer; - IgniteUtils.osArch = osArch; - IgniteUtils.jvmSpecName = jvmSpecName; - IgniteUtils.jvmImplVer = jvmImplVer; - IgniteUtils.jvmImplVendor = jvmImplVendor; IgniteUtils.jvmImplName = jvmImplName; - IgniteUtils.javaRtName = javaRtName; - IgniteUtils.javaRtVer = javaRtVer; jvm32Bit = "32".equals(jvmArchDataModel); @@ -1049,7 +868,7 @@ public static List allPluginProviders(IgniteConfiguration cfg, b return cfg.getPluginProviders() != null && cfg.getPluginProviders().length > 0 ? Arrays.asList(cfg.getPluginProviders()) : includeClsPath ? - U.allPluginProviders() : + allPluginProviders() : Collections.emptyList(); } @@ -1212,7 +1031,7 @@ public static int[] gridEvents(final int... excl) { * @return {@code True} if ordering is supported. */ public static boolean discoOrdered(DiscoverySpi discoSpi) { - DiscoverySpiOrderSupport ann = U.getAnnotation(discoSpi.getClass(), DiscoverySpiOrderSupport.class); + DiscoverySpiOrderSupport ann = getAnnotation(discoSpi.getClass(), DiscoverySpiOrderSupport.class); return ann != null && ann.value(); } @@ -1236,86 +1055,12 @@ public static void debug(Object msg) { X.error(debugPrefix() + msg); } - /** - * This method should be used for adding quick debug statements in code - * while debugging. Calls to this method should never be committed to master. - * - * @param msg Message to debug. - * @deprecated Calls to this method should never be committed to master. - */ - @Deprecated - public static void debugx(String msg) { - X.printerrln(debugPrefix() + msg); - } - - /** - * This method should be used for adding quick debug statements in code - * while debugging. Calls to this method should never be committed to master. - * - * @param log Logger. - * @param msg Message to debug. - * - * @deprecated Calls to this method should never be committed to master. - */ - @Deprecated - public static void debug(IgniteLogger log, String msg) { - log.info(msg); - } - - /** - * Prints stack trace of the current thread to {@code System.out}. - * - * @deprecated Calls to this method should never be committed to master. - */ - @Deprecated - public static void dumpStack() { - dumpStack("Dumping stack."); - } - - /** - * Prints stack trace of the current thread to {@code System.out}. - * - * @param msg Message to print with the stack. - * - * @deprecated Calls to this method should never be committed to master. - */ - @Deprecated - public static void dumpStack(String msg) { - new Exception(debugPrefix() + msg).printStackTrace(System.err); - } - /** * @param log Logger. * @param msg Message. */ public static void dumpStack(@Nullable IgniteLogger log, String msg) { - U.error(log, "Dumping stack.", new Exception(msg)); - } - - /** - * Prints stack trace of the current thread to provided output stream. - * - * @param msg Message to print with the stack. - * @param out Output to dump stack to. - * - * @deprecated Calls to this method should never be committed to master. - */ - @Deprecated - public static void dumpStack(String msg, PrintStream out) { - new Exception(msg).printStackTrace(out); - } - - /** - * Prints stack trace of the current thread to provided logger. - * - * @param log Logger. - * @param msg Message to print with the stack. - * - * @deprecated Calls to this method should never be committed to master. - */ - @Deprecated - public static void debugStack(IgniteLogger log, String msg) { - log.error(msg, new Exception(debugPrefix() + msg)); + error(log, "Dumping stack.", new Exception(msg)); } /** @@ -1326,19 +1071,6 @@ private static String debugPrefix() { Thread.currentThread().getName() + '>' + ' '; } - /** - * Prints heap usage. - */ - public static void debugHeapUsage() { - System.gc(); - - Runtime runtime = Runtime.getRuntime(); - - X.println('<' + DEBUG_DATE_FMT.format(Instant.now()) + "><" + - Thread.currentThread().getName() + "> Heap stats [free=" + runtime.freeMemory() / (1024 * 1024) + - "M, total=" + runtime.totalMemory() / (1024 * 1024) + "M]"); - } - /** * Gets heap size in GB rounded to specified precision. * @@ -1466,7 +1198,7 @@ public static void dumpThreads(@Nullable IgniteLogger log, boolean isErrorLevel) mxBean.dumpAllThreads(mxBean.isObjectMonitorUsageSupported(), mxBean.isSynchronizerUsageSupported()); GridStringBuilder sb = new GridStringBuilder(THREAD_DUMP_MSG) - .a(THREAD_DUMP_FMT.format(Instant.ofEpochMilli(U.currentTimeMillis()))).a(NL); + .a(THREAD_DUMP_FMT.format(Instant.ofEpochMilli(currentTimeMillis()))).a(NL); for (ThreadInfo info : threadInfos) { printThreadInfo(info, sb, deadlockedThreadsIds); @@ -1534,18 +1266,6 @@ public static void printStackTrace(long threadId, GridStringBuilder sb) { printThreadInfo(threadInfo, sb, Collections.emptySet()); } - /** - * @return Stacktrace of current thread as {@link String}. - */ - public static String stackTrace() { - GridStringBuilder sb = new GridStringBuilder(); - long threadId = Thread.currentThread().getId(); - - printStackTrace(threadId, sb); - - return sb.toString(); - } - /** * @return {@code true} if there is java level deadlock. */ @@ -1785,20 +1505,6 @@ public static String id8(IgniteUuid id) { return s.substring(0, 4) + s.substring(s.length() - 4); } - /** - * - * @param len Number of characters to fill in. - * @param ch Character to fill with. - * @return String. - */ - public static String filler(int len, char ch) { - char[] a = new char[len]; - - Arrays.fill(a, ch); - - return new String(a); - } - /** * Writes array to output stream. * @@ -1903,23 +1609,6 @@ public static void writeCollection(ObjectOutput out, Collection col) throws I out.writeInt(-1); } - /** - * - * @param out Output. - * @param col Set to write. - * @throws IOException If write failed. - */ - public static void writeIntCollection(DataOutput out, Collection col) throws IOException { - if (col != null) { - out.writeInt(col.size()); - - for (Integer i : col) - out.writeInt(i); - } - else - out.writeInt(-1); - } - /** * @param in Input. * @return Deserialized set. @@ -1931,37 +1620,6 @@ public static void writeIntCollection(DataOutput out, Collection col) t return readList(in); } - /** - * @param in Input. - * @return Deserialized set. - * @throws IOException If deserialization failed. - */ - @Nullable public static Collection readIntCollection(DataInput in) throws IOException { - int size = in.readInt(); - - // Check null flag. - if (size == -1) - return null; - - Collection col = new ArrayList<>(size); - - for (int i = 0; i < size; i++) - col.add(in.readInt()); - - return col; - } - - /** - * - * @param m Map to copy. - * @param Key type. - * @param Value type - * @return Copied map. - */ - public static Map copyMap(Map m) { - return new HashMap<>(m); - } - /** * * @param m Map to seal. @@ -1997,33 +1655,6 @@ public static List sealList(E... a) { return Collections.unmodifiableList(Arrays.asList(a)); } - /** - * Gets display name of the network interface this IP address belongs to. - * - * @param addr IP address for which to find network interface name. - * @return Network interface name or {@code null} if can't be found. - */ - @Nullable public static String getNetworkInterfaceName(String addr) { - assert addr != null; - - try { - InetAddress inetAddr = InetAddress.getByName(addr); - - for (NetworkInterface itf : asIterable(INTERFACE_SUPPLIER.getInterfaces())) - for (InetAddress itfAddr : asIterable(itf.getInetAddresses())) - if (itfAddr.equals(inetAddr)) - return itf.getDisplayName(); - } - catch (UnknownHostException ignore) { - return null; - } - catch (SocketException ignore) { - return null; - } - - return null; - } - /** * Tries to resolve host by name, returning local host if input is empty. * This method reflects how {@link org.apache.ignite.configuration.IgniteConfiguration#getLocalHost()} should @@ -2040,19 +1671,6 @@ public static InetAddress resolveLocalHost(@Nullable String hostName) throws IOE InetAddress.getByName(hostName); } - /** - * Determines whether current local host is different from previously cached. - * - * @return {@code true} or {@code false} depending on whether or not local host - * has changed from the cached value. - * @throws IOException If attempt to get local host failed. - */ - public static synchronized boolean isLocalHostChanged() throws IOException { - InetAddress locHost0 = locHost; - - return locHost0 != null && !resetLocalHost().equals(locHost0); - } - /** * @param addrs Addresses. * @return List of reachable addresses. @@ -2432,80 +2050,6 @@ public static synchronized Collection allLocalMACs() { return macs; } - /** - * Downloads resource by URL. - * - * @param url URL to download. - * @param file File where downloaded resource should be stored. - * @return File where downloaded resource should be stored. - * @throws IOException If error occurred. - */ - public static File downloadUrl(URL url, File file) throws IOException { - assert url != null; - assert file != null; - - InputStream in = null; - OutputStream out = null; - - try { - URLConnection conn = url.openConnection(); - - if (conn instanceof HttpsURLConnection) { - HttpsURLConnection https = (HttpsURLConnection)conn; - - https.setHostnameVerifier(new DeploymentHostnameVerifier()); - - SSLContext ctx = SSLContext.getInstance(HTTPS_PROTOCOL); - - ctx.init(null, getTrustManagers(), null); - - // Initialize socket factory. - https.setSSLSocketFactory(ctx.getSocketFactory()); - } - - in = conn.getInputStream(); - - if (in == null) - throw new IOException("Failed to open connection: " + url.toString()); - - out = new BufferedOutputStream(new FileOutputStream(file)); - - copy(in, out); - } - catch (NoSuchAlgorithmException | KeyManagementException e) { - throw new IOException("Failed to open HTTPs connection [url=" + url.toString() + ", msg=" + e + ']', e); - } - finally { - close(in, null); - close(out, null); - } - - return file; - } - - /** - * Construct array with one trust manager which don't reject input certificates. - * - * @return Array with one X509TrustManager implementation of trust manager. - */ - private static TrustManager[] getTrustManagers() { - return new TrustManager[] { - new X509TrustManager() { - @Nullable @Override public X509Certificate[] getAcceptedIssuers() { - return null; - } - - @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { - /* No-op. */ - } - - @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { - /* No-op. */ - } - } - }; - } - /** * Replace password in URI string with a single '*' character. *

@@ -2602,45 +2146,6 @@ public static boolean hasParent(@Nullable ClassLoader parent, ClassLoader ldr) { return true; } - /** - * Writes collection of byte arrays to data output. - * - * @param out Output to write to. - * @param bytes Collection with byte arrays. - * @throws java.io.IOException If write failed. - */ - public static void writeBytesCollection(DataOutput out, Collection bytes) throws IOException { - if (bytes != null) { - out.writeInt(bytes.size()); - - for (byte[] b : bytes) - writeByteArray(out, b); - } - else - out.writeInt(-1); - } - - /** - * Reads collection of byte arrays from data input. - * - * @param in Data input to read from. - * @return List of byte arrays. - * @throws java.io.IOException If read failed. - */ - public static List readBytesList(DataInput in) throws IOException { - int size = in.readInt(); - - if (size < 0) - return null; - - List res = new ArrayList<>(size); - - for (int i = 0; i < size; i++) - res.add(readByteArray(in)); - - return res; - } - /** * Writes byte array to output stream accounting for null values. * @@ -2698,148 +2203,29 @@ public static void writeByteArray(DataOutput out, @Nullable byte[] arr, int maxL } /** - * Reads byte array from given buffers (changing buffer positions). + * Join byte arrays into single one. * - * @param bufs Byte buffers. - * @return Byte array. + * @param bufs list of byte arrays to concatenate. + * @return Concatenated byte's array. */ - public static byte[] readByteArray(ByteBuffer... bufs) { - assert !F.isEmpty(bufs); - + public static byte[] join(byte[]... bufs) { int size = 0; - - for (ByteBuffer buf : bufs) - size += buf.remaining(); + for (byte[] buf : bufs) { + size += buf.length; + } byte[] res = new byte[size]; - - int off = 0; - - for (ByteBuffer buf : bufs) { - int len = buf.remaining(); - - if (len != 0) { - buf.get(res, off, len); - - off += len; - } + int position = 0; + for (byte[] buf : bufs) { + arrayCopy(buf, 0, res, position, buf.length); + position += buf.length; } - assert off == res.length; - return res; } /** - * // FIXME: added for DR dataCenterIds, review if it is needed after GG-6879. - * - * @param out Output. - * @param col Set to write. - * @throws java.io.IOException If write failed. - */ - public static void writeByteCollection(DataOutput out, Collection col) throws IOException { - if (col != null) { - out.writeInt(col.size()); - - for (Byte i : col) - out.writeByte(i); - } - else - out.writeInt(-1); - } - - /** - * // FIXME: added for DR dataCenterIds, review if it is needed after GG-6879. - * - * @param in Input. - * @return Deserialized list. - * @throws java.io.IOException If deserialization failed. - */ - @Nullable public static List readByteList(DataInput in) throws IOException { - int size = in.readInt(); - - // Check null flag. - if (size == -1) - return null; - - List col = new ArrayList<>(size); - - for (int i = 0; i < size; i++) - col.add(in.readByte()); - - return col; - } - - /** - * Join byte arrays into single one. - * - * @param bufs list of byte arrays to concatenate. - * @return Concatenated byte's array. - */ - public static byte[] join(byte[]... bufs) { - int size = 0; - for (byte[] buf : bufs) { - size += buf.length; - } - - byte[] res = new byte[size]; - int position = 0; - for (byte[] buf : bufs) { - arrayCopy(buf, 0, res, position, buf.length); - position += buf.length; - } - - return res; - } - - /** - * 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
-     * ...
-     * 
- * - * @param arr Array of byte. - * @param hdrFmt C-style string format for the first element. - * @param bodyFmt C-style string format for second and following elements, if any. - * @return String with converted bytes. - */ - public static String byteArray2String(byte[] arr, String hdrFmt, String bodyFmt) { - assert arr != null; - assert hdrFmt != null; - assert bodyFmt != null; - - SB sb = new SB(); - - sb.a('{'); - - boolean first = true; - - for (byte b : arr) - if (first) { - sb.a(String.format(hdrFmt, b)); - - first = false; - } - else - sb.a(String.format(bodyFmt, b)); - - sb.a('}'); - - return sb.toString(); - } - - /** - * Convert string with hex values to byte array. + * Convert string with hex values to byte array. * * @param hex Hexadecimal string to convert. * @return array of bytes defined as hex in string. @@ -2943,51 +2329,6 @@ private static byte hexCharToByte(char ch) throws IllegalArgumentException { } } - /** - * Converts primitive double to byte array. - * - * @param d Double to convert. - * @return Byte array. - */ - public static byte[] doubleToBytes(double d) { - return longToBytes(Double.doubleToLongBits(d)); - } - - /** - * Converts primitive {@code double} type to byte array and stores - * it in the specified byte array. - * - * @param d Double to convert. - * @param bytes Array of bytes. - * @param off Offset. - * @return New offset. - */ - public static int doubleToBytes(double d, byte[] bytes, int off) { - return longToBytes(Double.doubleToLongBits(d), bytes, off); - } - - /** - * Converts primitive float to byte array. - * - * @param f Float to convert. - * @return Array of bytes. - */ - public static byte[] floatToBytes(float f) { - return intToBytes(Float.floatToIntBits(f)); - } - - /** - * Converts primitive float to byte array. - * - * @param f Float to convert. - * @param bytes Array of bytes. - * @param off Offset. - * @return New offset. - */ - public static int floatToBytes(float f, byte[] bytes, int off) { - return intToBytes(Float.floatToIntBits(f), bytes, off); - } - /** * Converts primitive {@code long} type to byte array. * @@ -3057,19 +2398,6 @@ public static int shortToBytes(short s, byte[] bytes, int off) { return off + GridClientByteUtils.shortToBytes(s, bytes, off); } - /** - * Encodes {@link java.util.UUID} into a sequence of bytes using the {@link java.nio.ByteBuffer}, - * storing the result into a new byte array. - * - * @param uuid Unique identifier. - * @param arr Byte array to fill with result. - * @param off Offset in {@code arr}. - * @return Number of bytes overwritten in {@code bytes} array. - */ - public static int uuidToBytes(@Nullable UUID uuid, byte[] arr, int off) { - return off + GridClientByteUtils.uuidToBytes(uuid, arr, off); - } - /** * Converts an UUID to byte array. * @@ -3172,28 +2500,6 @@ public static UUID bytesToUuid(byte[] bytes, int off) { return GridClientByteUtils.bytesToUuid(bytes, off); } - /** - * Constructs double from byte array. - * - * @param bytes Byte array. - * @param off Offset in {@code bytes} array. - * @return Double value. - */ - public static double bytesToDouble(byte[] bytes, int off) { - return Double.longBitsToDouble(bytesToLong(bytes, off)); - } - - /** - * Constructs float from byte array. - * - * @param bytes Byte array. - * @param off Offset in {@code bytes} array. - * @return Float value. - */ - public static float bytesToFloat(byte[] bytes, int off) { - return Float.intBitsToFloat(bytesToInt(bytes, off)); - } - /** * Compares fragments of byte arrays. * @@ -3314,17 +2620,6 @@ public static Pattern fixedLengthNumberNamePattern(@Nullable String ext) { return Pattern.compile(pattern); } - /** - * Verifier always returns successful result for any host. - */ - private static class DeploymentHostnameVerifier implements HostnameVerifier { - /** {@inheritDoc} */ - @Override public boolean verify(String hostname, SSLSession ses) { - // Remote host trusted by default. - return true; - } - } - /** * Makes a {@code '+---+'} dash line. * @@ -3341,20 +2636,6 @@ public static String dash(int len) { return new String(dash); } - /** - * Creates space filled string of given length. - * - * @param len Number of spaces. - * @return Space filled string of given length. - */ - public static String pad(int len) { - char[] dash = new char[len]; - - Arrays.fill(dash, ' '); - - return new String(dash); - } - /** * Formats system time in milliseconds for printing in logs. * @@ -3579,54 +2860,6 @@ public static int copy(InputStream in, OutputStream out) throws IOException { return cnt; } - /** - * Copies input character stream to output character stream. - * - * @param in Input character stream. - * @param out Output character stream. - * @return Number of the copied characters. - * @throws IOException Thrown if an I/O error occurs. - */ - public static int copy(Reader in, Writer out) throws IOException { - assert in != null; - assert out != null; - - char[] buf = new char[BUF_SIZE]; - - int cnt = 0; - - for (int n; (n = in.read(buf)) > 0; ) { - out.write(buf, 0, n); - - cnt += n; - } - - return cnt; - } - - /** - * Writes string to file. - * - * @param file File. - * @param s String to write. - * @throws IOException Thrown if an I/O error occurs. - */ - public static void writeStringToFile(File file, String s) throws IOException { - writeStringToFile(file, s, Charset.defaultCharset().toString(), false); - } - - /** - * Writes string to file. - * - * @param file File. - * @param s String to write. - * @param charset Encoding. - * @throws IOException Thrown if an I/O error occurs. - */ - public static void writeStringToFile(File file, String s, String charset) throws IOException { - writeStringToFile(file, s, charset, false); - } - /** * Reads file to string using specified charset. * @@ -4007,7 +3240,7 @@ public static URL resolveSpringUrl(String springCfgPath) throws IgniteCheckedExc url = new URL(springCfgPath); } catch (MalformedURLException e) { - url = U.resolveIgniteUrl(springCfgPath); + url = resolveIgniteUrl(springCfgPath); if (url == null) url = resolveInClasspath(springCfgPath); @@ -4315,17 +3548,6 @@ public static void close(@Nullable SelectionKey rsrc, @Nullable IgniteLogger log close(rsrc.channel(), log); } - /** - * Quietly closes given resource ignoring possible checked exceptions. - * - * @param rsrc Resource to close. If it's {@code null} - it's no-op. - */ - public static void closeQuiet(@Nullable SelectionKey rsrc) { - if (rsrc != null) - // This apply will automatically deregister the selection key as well. - closeQuiet(rsrc.channel()); - } - /** * Closes given resource. * @@ -4353,53 +3575,6 @@ public static void close(@Nullable Selector rsrc, @Nullable IgniteLogger log) { } } - /** - * Quietly closes given resource ignoring possible checked exception. - * - * @param rsrc Resource to close. If it's {@code null} - it's no-op. - */ - public static void closeQuiet(@Nullable Selector rsrc) { - if (rsrc != null) - try { - if (rsrc.isOpen()) - rsrc.close(); - } - catch (IOException ignored) { - // No-op. - } - } - - /** - * Closes given resource logging possible checked exception. - * - * @param rsrc Resource to close. If it's {@code null} - it's no-op. - * @param log Logger to log possible checked exception with (optional). - */ - public static void close(@Nullable Context rsrc, @Nullable IgniteLogger log) { - if (rsrc != null) - try { - rsrc.close(); - } - catch (NamingException e) { - warn(log, "Failed to close resource: " + e.getMessage()); - } - } - - /** - * Quietly closes given resource ignoring possible checked exception. - * - * @param rsrc Resource to close. If it's {@code null} - it's no-op. - */ - public static void closeQuiet(@Nullable Context rsrc) { - if (rsrc != null) - try { - rsrc.close(); - } - catch (NamingException ignored) { - // No-op. - } - } - /** * Closes class loader logging possible checked exception. * @@ -4673,12 +3848,12 @@ public static void initWorkDir(IgniteConfiguration cfg) throws IgniteCheckedExce // Set Ignite home. if (igniteHome == null) - igniteHome = U.getIgniteHome(); + igniteHome = getIgniteHome(); String userProvidedWorkDir = cfg.getWorkDirectory(); // Correctly resolve work directory and set it back to configuration. - cfg.setWorkDirectory(U.workDirectory(userProvidedWorkDir, igniteHome)); + cfg.setWorkDirectory(workDirectory(userProvidedWorkDir, igniteHome)); } /** @@ -4725,7 +3900,7 @@ public static IgniteLogger initLogger( if (log4jCls != null) { try { - URL url = U.resolveIgniteUrl("config/ignite-log4j.xml"); + URL url = resolveIgniteUrl("config/ignite-log4j.xml"); if (url == null) { File cfgFile = new File("config/ignite-log4j.xml"); @@ -4776,7 +3951,7 @@ public static IgniteLogger initLogger( ((IgniteLoggerEx)cfgLog).setApplicationAndNode(app, nodeId); if (log4jInitErr != null) - U.warn(cfgLog, "Failed to initialize Log4J2Logger (falling back to standard java logging): " + warn(cfgLog, "Failed to initialize Log4J2Logger (falling back to standard java logging): " + log4jInitErr.getCause()); return cfgLog; @@ -4892,7 +4067,7 @@ public static void quietMultipleLines(boolean err, String multiline) { */ public static void quietAndInfo(IgniteLogger log, String msg) { if (log.isQuiet()) - U.quiet(false, msg); + quiet(false, msg); if (log.isInfoEnabled()) log.info(msg); @@ -5158,20 +4333,6 @@ public static boolean joinThreads(Iterable workers, @Nullable return retval; } - /** - * Starts given threads. - * - * @param threads Threads to start. - */ - public static void startThreads(Iterable threads) { - if (threads != null) { - for (Thread thread : threads) { - if (thread != null) - thread.start(); - } - } - } - /** * Cancels given runnable. * @@ -5247,7 +4408,7 @@ public static void shutdownNow(Class owner, @Nullable ExecutorService exec, @ List tasks = exec.shutdownNow(); if (!F.isEmpty(tasks)) - U.warn(log, "Runnable tasks outlived thread pool executor service [owner=" + getSimpleName(owner) + + warn(log, "Runnable tasks outlived thread pool executor service [owner=" + getSimpleName(owner) + ", tasks=" + tasks + ']'); try { @@ -5274,174 +4435,49 @@ public static ClusterGroupEmptyCheckedException emptyTopologyException() { } /** - * Writes UUIDs to output stream. This method is meant to be used by + * Writes UUID to output stream. This method is meant to be used by * implementations of {@link Externalizable} interface. * * @param out Output stream. - * @param col UUIDs to write. + * @param uid UUID to write. * @throws IOException If write failed. */ - public static void writeUuids(DataOutput out, @Nullable Collection col) throws IOException { - if (col != null) { - out.writeInt(col.size()); + public static void writeUuid(DataOutput out, UUID uid) throws IOException { + // Write null flag. + out.writeBoolean(uid == null); - for (UUID id : col) - writeUuid(out, id); + if (uid != null) { + out.writeLong(uid.getMostSignificantBits()); + out.writeLong(uid.getLeastSignificantBits()); } - else - out.writeInt(-1); } /** - * Reads UUIDs from input stream. This method is meant to be used by + * Reads UUID from input stream. This method is meant to be used by * implementations of {@link Externalizable} interface. * * @param in Input stream. - * @return Read UUIDs. + * @return Read UUID. * @throws IOException If read failed. */ - @Nullable public static List readUuids(DataInput in) throws IOException { - int size = in.readInt(); - - // Check null flag. - if (size == -1) - return null; - - List col = new ArrayList<>(size); + @Nullable public static UUID readUuid(DataInput in) throws IOException { + // If UUID is not null. + if (!in.readBoolean()) { + long most = in.readLong(); + long least = in.readLong(); - for (int i = 0; i < size; i++) - col.add(readUuid(in)); + return IgniteUuidCache.onIgniteUuidRead(new UUID(most, least)); + } - return col; + return null; } /** - * Writes Ignite UUIDs to output stream. This method is meant to be used by + * Writes {@link org.apache.ignite.lang.IgniteUuid} to output stream. This method is meant to be used by * implementations of {@link Externalizable} interface. * * @param out Output stream. - * @param col Ignite UUIDs to write. - * @throws IOException If write failed. - */ - public static void writeIgniteUuids(DataOutput out, @Nullable Collection col) throws IOException { - if (col != null) { - out.writeBoolean(true); - - out.writeInt(col.size()); - - for (IgniteUuid id : col) - writeIgniteUuid(out, id); - } - else - out.writeBoolean(false); - } - - /** - * Reads Ignite UUIDs from input stream. This method is meant to be used by - * implementations of {@link Externalizable} interface. - * - * @param in Input stream. - * @return Read Ignite UUIDs. - * @throws IOException If read failed. - */ - @Nullable public static List readIgniteUuids(DataInput in) throws IOException { - List col = null; - - // Check null flag. - if (in.readBoolean()) { - int size = in.readInt(); - - col = new ArrayList<>(size); - - for (int i = 0; i < size; i++) - col.add(readIgniteUuid(in)); - } - - return col; - } - - /** - * Writes UUID to output stream. This method is meant to be used by - * implementations of {@link Externalizable} interface. - * - * @param out Output stream. - * @param uid UUID to write. - * @throws IOException If write failed. - */ - public static void writeUuid(DataOutput out, UUID uid) throws IOException { - // Write null flag. - out.writeBoolean(uid == null); - - if (uid != null) { - out.writeLong(uid.getMostSignificantBits()); - out.writeLong(uid.getLeastSignificantBits()); - } - } - - /** - * Reads UUID from input stream. This method is meant to be used by - * implementations of {@link Externalizable} interface. - * - * @param in Input stream. - * @return Read UUID. - * @throws IOException If read failed. - */ - @Nullable public static UUID readUuid(DataInput in) throws IOException { - // If UUID is not null. - if (!in.readBoolean()) { - long most = in.readLong(); - long least = in.readLong(); - - return IgniteUuidCache.onIgniteUuidRead(new UUID(most, least)); - } - - return null; - } - - /** - * Writes UUID to binary writer. - * - * @param out Output Binary writer. - * @param uid UUID to write. - * @throws IOException If write failed. - */ - public static void writeUuid(BinaryRawWriter out, UUID uid) { - // Write null flag. - if (uid != null) { - out.writeBoolean(true); - - out.writeLong(uid.getMostSignificantBits()); - out.writeLong(uid.getLeastSignificantBits()); - } - else - out.writeBoolean(false); - } - - /** - * Reads UUID from binary reader. - * - * @param in Binary reader. - * @return Read UUID. - * @throws IOException If read failed. - */ - @Nullable public static UUID readUuid(BinaryRawReader in) { - // If UUID is not null. - if (in.readBoolean()) { - long most = in.readLong(); - long least = in.readLong(); - - return new UUID(most, least); - } - else - return null; - } - - /** - * Writes {@link org.apache.ignite.lang.IgniteUuid} to output stream. This method is meant to be used by - * implementations of {@link Externalizable} interface. - * - * @param out Output stream. - * @param uid UUID to write. + * @param uid UUID to write. * @throws IOException If write failed. */ public static void writeIgniteUuid(DataOutput out, IgniteUuid uid) throws IOException { @@ -5480,70 +4516,6 @@ public static void writeIgniteUuid(DataOutput out, IgniteUuid uid) throws IOExce return null; } - /** - * Converts {@link IgniteUuid} to bytes. - * - * @param uuid {@link IgniteUuid} to convert. - * @return Bytes. - */ - public static byte[] igniteUuidToBytes(IgniteUuid uuid) { - assert uuid != null; - - byte[] out = new byte[24]; - - igniteUuidToBytes(uuid, out, 0); - - return out; - } - - /** - * Converts {@link IgniteUuid} to bytes. - * - * @param uuid {@link IgniteUuid} to convert. - * @param out Output array to write to. - * @param off Offset from which to write. - */ - public static void igniteUuidToBytes(IgniteUuid uuid, byte[] out, int off) { - assert uuid != null; - - longToBytes(uuid.globalId().getMostSignificantBits(), out, off); - longToBytes(uuid.globalId().getLeastSignificantBits(), out, off + 8); - longToBytes(uuid.localId(), out, off + 16); - } - - /** - * Converts bytes to {@link IgniteUuid}. - * - * @param in Input byte array. - * @param off Offset from which start reading. - * @return {@link IgniteUuid} instance. - */ - public static IgniteUuid bytesToIgniteUuid(byte[] in, int off) { - long most = bytesToLong(in, off); - long least = bytesToLong(in, off + 8); - long locId = bytesToLong(in, off + 16); - - return new IgniteUuid(IgniteUuidCache.onIgniteUuidRead(new UUID(most, least)), locId); - } - - /** - * Writes boolean array to output stream accounting for null values. - * - * @param out Output stream to write to. - * @param arr Array to write, possibly null. - * @throws IOException If write failed. - */ - public static void writeBooleanArray(DataOutput out, @Nullable boolean[] arr) throws IOException { - if (arr == null) - out.writeInt(-1); - else { - out.writeInt(arr.length); - - for (boolean b : arr) - out.writeBoolean(b); - } - } - /** * Writes int array to output stream accounting for null values. * @@ -5580,27 +4552,6 @@ public static void writeLongArray(DataOutput out, @Nullable long[] arr) throws I } } - /** - * Reads boolean array from input stream accounting for null values. - * - * @param in Stream to read from. - * @return Read byte array, possibly null. - * @throws IOException If read failed. - */ - @Nullable public static boolean[] readBooleanArray(DataInput in) throws IOException { - int len = in.readInt(); - - if (len == -1) - return null; // Value "-1" indicates null. - - boolean[] res = new boolean[len]; - - for (int i = 0; i < len; i++) - res[i] = in.readBoolean(); - - return res; - } - /** * Reads int array from input stream accounting for null values. * @@ -5643,28 +4594,6 @@ public static void writeLongArray(DataOutput out, @Nullable long[] arr) throws I return res; } - /** - * Calculates hash code for the given byte buffers contents. Compatible with {@link Arrays#hashCode(byte[])} - * with the same content. Does not change buffers positions. - * - * @param bufs Byte buffers. - * @return Hash code. - */ - public static int hashCode(ByteBuffer... bufs) { - int res = 1; - - for (ByteBuffer buf : bufs) { - int pos = buf.position(); - - while (buf.hasRemaining()) - res = 31 * res + buf.get(); - - buf.position(pos); - } - - return res; - } - /** * @param out Output. * @param map Map to write. @@ -5779,7 +4708,7 @@ public static int hashCode(Object obj) { if (size == -1) return null; - HashMap map = U.newHashMap(size); + HashMap map = newHashMap(size); for (int i = 0; i < size; i++) map.put((K)in.readObject(), (V)in.readObject()); @@ -5810,87 +4739,6 @@ public static int hashCode(Object obj) { return map; } - /** - * @param out Output. - * @param map Map to write. - * @throws IOException If write failed. - */ - public static void writeIntKeyMap(ObjectOutput out, Map map) throws IOException { - if (map != null) { - out.writeInt(map.size()); - - for (Map.Entry e : map.entrySet()) { - out.writeInt(e.getKey()); - out.writeObject(e.getValue()); - } - } - else - out.writeInt(-1); - } - - /** - * @param in Input. - * @return Read map. - * @throws IOException If de-serialization failed. - * @throws ClassNotFoundException If deserialized class could not be found. - */ - @Nullable public static Map readIntKeyMap(ObjectInput in) throws IOException, - ClassNotFoundException { - int size = in.readInt(); - - // Check null flag. - if (size == -1) - return null; - - Map map = new HashMap<>(size, 1.0f); - - for (int i = 0; i < size; i++) - map.put(in.readInt(), (V)in.readObject()); - - return map; - } - - /** - * @param out Output. - * @param map Map to write. - * @throws IOException If write failed. - */ - public static void writeIntKeyIntValueMap(DataOutput out, Map map) throws IOException { - if (map != null) { - out.writeBoolean(true); - - out.writeInt(map.size()); - - for (Map.Entry e : map.entrySet()) { - out.writeInt(e.getKey()); - out.writeInt(e.getValue()); - } - } - else - out.writeBoolean(false); - } - - /** - * @param in Input. - * @return Read map. - * @throws IOException If de-serialization failed. - */ - @Nullable public static Map readIntKeyIntValueMap(DataInput in) throws IOException { - Map map = null; - - // Check null flag. - if (in.readBoolean()) { - int size = in.readInt(); - - map = new HashMap<>(size, 1.0f); - - for (int i = 0; i < size; i++) - map.put(in.readInt(), in.readInt()); - } - - return map; - } - /** * @param in Input. * @return Deserialized list. @@ -5912,26 +4760,6 @@ public static void writeIntKeyIntValueMap(DataOutput out, Map return col; } - /** - * @param in Input. - * @return Deserialized list. - * @throws IOException If deserialization failed. - */ - @Nullable public static List readIntList(DataInput in) throws IOException { - int size = in.readInt(); - - // Check null flag. - if (size == -1) - return null; - - List col = new ArrayList<>(size); - - for (int i = 0; i < size; i++) - col.add(in.readInt()); - - return col; - } - /** * @param in Input. * @return Deserialized set. @@ -5954,50 +4782,19 @@ public static void writeIntKeyIntValueMap(DataOutput out, Map return set; } - /** - * @param in Input. - * @return Deserialized set. - * @throws IOException If deserialization failed. - */ - @Nullable public static Set readIntSet(DataInput in) throws IOException { - int size = in.readInt(); - - // Check null flag. - if (size == -1) - return null; - - Set set = new HashSet<>(size, 1.0f); - - for (int i = 0; i < size; i++) - set.add(in.readInt()); - - return set; - } - /** * Writes string to output stream accounting for {@code null} values. *

- * Limitation for max string lenght of {@link #UTF_BYTE_LIMIT} bytes is caused by {@link ObjectOutputStream#writeUTF} + * Limitation for max string lenght of 65535 bytes is caused by {@link DataOutput#writeUTF} * used under the hood to perform an actual write. *

*

* If longer string is passes a {@link UTFDataFormatException} exception will be thrown. *

*

- * To write longer strings use one of two options: - *

    - *
  • - * {@link #writeLongString(DataOutput, String)} writes string as is converting it into binary array of UTF-8 - * encoded characters. - * To read the value back {@link #readLongString(DataInput)} should be used. - *
  • - *
  • - * {@link #writeCutString(DataOutput, String)} cuts passed string to {@link #UTF_BYTE_LIMIT} bytes - * 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 regular - * {@link #readString(DataInput)} method. - *
  • - *
+ * To write longer strings use {@link #writeLongString(DataOutput, String)} writes string as is converting it into binary array of UTF-8 + * encoded characters. + * To read the value back {@link #readLongString(DataInput)} should be used. *

* * @param out Output stream to write to. @@ -6015,10 +4812,9 @@ public static void writeString(DataOutput out, String s) throws IOException { /** * Reads string from input stream accounting for {@code null} values. * - * Method enables to read strings shorter than {@link #UTF_BYTE_LIMIT} bytes in UTF-8 otherwise an exception will be thrown. + * Method enables to read strings shorter than 65535 bytes in UTF-8 otherwise an exception will be thrown. * - * Strings written by {@link #writeString(DataOutput, String)} or {@link #writeCutString(DataOutput, String)} - * can be read by this method. + * Strings written by {@link #writeString(DataOutput, String)} can be read by this method. * * @see #writeString(DataOutput, String) for more information about writing strings. * @@ -6058,31 +4854,6 @@ public static > E readEnum(DataInput in, Class enumCls) thr return idx < values.length ? values[idx] : null; } - /** - * Gets collection value by index. - * - * @param vals Collection of values. - * @param idx Index of value in the collection. - * @param Type of collection values. - * @return Value at the given index. - */ - public static T getByIndex(Collection vals, int idx) { - assert idx < vals.size(); - - int i = 0; - - for (T val : vals) { - if (idx == i) - return val; - - i++; - } - - assert false : "Should never be reached."; - - return null; - } - /** * Gets annotation for a class. * @@ -6294,15 +5065,6 @@ public static String classNameToResourceName(String clsName) { return clsName.replaceAll("\\.", "/") + ".class"; } - /** - * Gets runtime MBean. - * - * @return Runtime MBean. - */ - public static RuntimeMXBean getRuntimeMx() { - return ManagementFactory.getRuntimeMXBean(); - } - /** * Gets threading MBean. * @@ -6312,23 +5074,6 @@ public static ThreadMXBean getThreadMx() { return ManagementFactory.getThreadMXBean(); } - /** - * Gets OS MBean. - * @return OS MBean. - */ - public static OperatingSystemMXBean getOsMx() { - return ManagementFactory.getOperatingSystemMXBean(); - } - - /** - * Gets memory MBean. - * - * @return Memory MBean. - */ - public static MemoryMXBean getMemoryMx() { - return ManagementFactory.getMemoryMXBean(); - } - /** * Gets amount of RAM memory available on this machine. * @@ -6373,10 +5118,10 @@ public static Class detectClass(Object obj) { if (obj instanceof GridPeerDeployAware) return ((GridPeerDeployAware)obj).deployClass(); - if (U.isPrimitiveArray(obj)) + if (isPrimitiveArray(obj)) return obj.getClass(); - if (!U.isJdk(obj.getClass())) + if (!isJdk(obj.getClass())) return obj.getClass(); if (obj instanceof Iterable) { @@ -6392,7 +5137,7 @@ public static Class detectClass(Object obj) { if (e != null) { Object k = e.getKey(); - if (k != null && !U.isJdk(k.getClass())) + if (k != null && !isJdk(k.getClass())) return k.getClass(); Object v = e.getValue(); @@ -6460,7 +5205,7 @@ public static boolean isLoadableBy(String clsName, @Nullable ClassLoader ldr) { if (ldr == null) ldr = gridClassLoader; - String lambdaParent = U.lambdaEnclosingClassName(clsName); + String lambdaParent = lambdaEnclosingClassName(clsName); try { ldr.loadClass(lambdaParent == null ? clsName : lambdaParent); @@ -6618,7 +5363,7 @@ public static GridPeerDeployAware peerDeployAware0(Object obj) { if (obj instanceof Iterable) return peerDeployAware0((Iterable)obj); - if (obj.getClass().isArray() && !U.isPrimitiveArray(obj)) + if (obj.getClass().isArray() && !isPrimitiveArray(obj)) return peerDeployAware0((Object[])obj); return peerDeployAware(obj); @@ -6909,15 +5654,6 @@ public static boolean assertionsEnabled() { return assertionsEnabled; } - /** - * Gets OS JDK string. - * - * @return OS JDK string. - */ - public static String osJdkString() { - return osJdkStr; - } - /** * Gets OS string. * @@ -6945,23 +5681,6 @@ public static boolean isLinux() { return linux; } - /** - * Gets JDK name. - * @return JDK name. - */ - public static String jdkName() { - return jdkName; - } - - /** - * Gets JDK vendor. - * - * @return JDK vendor. - */ - public static String jdkVendor() { - return jdkVendor; - } - /** * Gets JDK version. * @@ -6971,33 +5690,6 @@ public static String jdkVersion() { return jdkVer; } - /** - * Gets OS CPU-architecture. - * - * @return OS CPU-architecture. - */ - public static String osArchitecture() { - return osArch; - } - - /** - * Gets underlying OS name. - * - * @return Underlying OS name. - */ - public static String osName() { - return osName; - } - - /** - * Gets underlying OS version. - * - * @return Underlying OS version. - */ - public static String osVersion() { - return osVer; - } - /** * Indicates whether current OS is Mac OS. * @@ -7007,49 +5699,6 @@ public static boolean isMacOs() { return mac; } - /** - * @return {@code True} if current OS is RedHat. - */ - public static boolean isRedHat() { - return redHat; - } - - /** - * Indicates whether current OS is Netware. - * - * @return {@code true} if current OS is Netware - {@code false} otherwise. - */ - public static boolean isNetWare() { - return netware; - } - - /** - * Indicates whether current OS is Solaris. - * - * @return {@code true} if current OS is Solaris (SPARC or x86) - {@code false} otherwise. - */ - public static boolean isSolaris() { - return solaris; - } - - /** - * Indicates whether current OS is Solaris on Spark box. - * - * @return {@code true} if current OS is Solaris SPARC - {@code false} otherwise. - */ - public static boolean isSolarisSparc() { - return solaris && sparc; - } - - /** - * Indicates whether current OS is Solaris on x86 box. - * - * @return {@code true} if current OS is Solaris x86 - {@code false} otherwise. - */ - public static boolean isSolarisX86() { - return solaris && x86; - } - /** * Indicates whether current OS is UNIX flavor. * @@ -7065,134 +5714,7 @@ public static boolean isUnix() { * @return {@code true} if current OS is Windows (any versions) - {@code false} otherwise. */ public static boolean isWindows() { - return win7 || win8 || win81 || winXp || win95 || win98 || winNt || win2k || - win2003 || win2008 || winVista || unknownWin; - } - - /** - * Indicates whether current OS is Windows Vista. - * - * @return {@code true} if current OS is Windows Vista - {@code false} otherwise. - */ - public static boolean isWindowsVista() { - return winVista; - } - - /** - * Indicates whether current OS is Windows 7. - * - * @return {@code true} if current OS is Windows 7 - {@code false} otherwise. - */ - public static boolean isWindows7() { - return win7; - } - - /** - * Indicates whether current OS is Windows 8. - * - * @return {@code true} if current OS is Windows 8 - {@code false} otherwise. - */ - public static boolean isWindows8() { - return win8; - } - - /** - * Indicates whether current OS is Windows 8.1. - * - * @return {@code true} if current OS is Windows 8.1 - {@code false} otherwise. - */ - public static boolean isWindows81() { - return win81; - } - - /** - * Indicates whether current OS is Windows 2000. - * - * @return {@code true} if current OS is Windows 2000 - {@code false} otherwise. - */ - public static boolean isWindows2k() { - return win2k; - } - - /** - * Indicates whether current OS is Windows Server 2003. - * - * @return {@code true} if current OS is Windows Server 2003 - {@code false} otherwise. - */ - public static boolean isWindows2003() { - return win2003; - } - - /** - * Indicates whether current OS is Windows Server 2008. - * - * @return {@code true} if current OS is Windows Server 2008 - {@code false} otherwise. - */ - public static boolean isWindows2008() { - return win2008; - } - - /** - * Indicates whether current OS is Windows 95. - * - * @return {@code true} if current OS is Windows 95 - {@code false} otherwise. - */ - public static boolean isWindows95() { - return win95; - } - - /** - * Indicates whether current OS is Windows 98. - * - * @return {@code true} if current OS is Windows 98 - {@code false} otherwise. - */ - public static boolean isWindows98() { - return win98; - } - - /** - * Indicates whether current OS is Windows NT. - * - * @return {@code true} if current OS is Windows NT - {@code false} otherwise. - */ - public static boolean isWindowsNt() { - return winNt; - } - - /** - * Indicates whether current OS is Windows XP. - * - * @return {@code true} if current OS is Windows XP- {@code false} otherwise. - */ - public static boolean isWindowsXp() { - return winXp; - } - - /** - * Gets JVM specification name. - * - * @return JVM specification name. - */ - public static String jvmSpec() { - return jvmSpecName; - } - - /** - * Gets JVM implementation version. - * - * @return JVM implementation version. - */ - public static String jvmVersion() { - return jvmImplVer; - } - - /** - * Gets JVM implementation vendor. - * - * @return JVM implementation vendor. - */ - public static String jvmVendor() { - return jvmImplVendor; + return win; } /** @@ -7213,46 +5735,6 @@ public static boolean jvm32Bit() { return jvm32Bit; } - /** - * Compare java implementation version - * - * @param v1 - java implementation version - * @param v2 - java implementation version - * @return the value {@code 0} if {@code v1 == v2}; - * a value less than {@code 0} if {@code v1 < v2}; and - * a value greater than {@code 0} if {@code v1 > v2} - */ - public static int compareVersionNumbers(@Nullable String v1, @Nullable String v2) { - if (v1 == null && v2 == null) - return 0; - - if (v1 == null) - return -1; - - if (v2 == null) - return 1; - - String[] part1 = v1.split("[\\.\\_\\-]"); - String[] part2 = v2.split("[\\.\\_\\-]"); - int idx = 0; - - for (; idx < part1.length && idx < part2.length; idx++) { - String p1 = part1[idx]; - String p2 = part2[idx]; - - int cmp = (p1.matches("\\d+") && p2.matches("\\d+")) - ? Integer.valueOf(p1).compareTo(Integer.valueOf(p2)) : p1.compareTo(p2); - - if (cmp != 0) - return cmp; - } - - if (part1.length == part2.length) - return 0; - else - return part1.length > idx ? 1 : -1; - } - /** * Gets node product version based on node attributes. * @@ -7264,37 +5746,9 @@ public static IgniteProductVersion productVersion(ClusterNode node) { String buildDate = node.attribute(ATTR_BUILD_DATE); if (buildDate != null) - verStr += '-' + buildDate; - - return IgniteProductVersion.fromString(verStr); - } - - /** - * Compare running Java Runtime version with {@code v} - * - * @param v - java implementation version - * @return {@code true} if running on Java Runtime version greater than {@code v} - */ - public static boolean isJavaVersionAtLeast(String v) { - return compareVersionNumbers(javaRtVer, v) >= 0; - } - - /** - * Gets Java Runtime name. - * - * @return Java Runtime name. - */ - public static String jreName() { - return javaRtName; - } + verStr += '-' + buildDate; - /** - * Gets Java Runtime version. - * - * @return Java Runtime version. - */ - public static String jreVersion() { - return javaRtVer; + return IgniteProductVersion.fromString(verStr); } /** @@ -7324,15 +5778,6 @@ public static int majorJavaVersion(String verStr) { } } - /** - * Indicates whether HotSpot VM is used. - * - * @return {@code true} if current JVM implementation is a Sun HotSpot VM, {@code false} otherwise. - */ - public static boolean isHotSpot() { - return jvmImplName.contains("Java HotSpot(TM)"); - } - /** * Sets thread context class loader to the given loader, executes the closure, and then * resets thread context class loader to its initial value. @@ -7543,24 +5988,6 @@ public static long[] toLongArray(@Nullable Collection c) { return arr; } - /** - * Converts array of longs into list. - * - * @param arr Array of longs. - * @return List of longs. - */ - public static List toLongList(@Nullable long[] arr) { - if (arr == null || arr.length == 0) - return Collections.emptyList(); - - List ret = new ArrayList<>(arr.length); - - for (long l : arr) - ret.add(l); - - return ret; - } - /** * Concats two integers to long. * @@ -7591,19 +6018,6 @@ public static T[] toArray(Collection c, T[] arr) { return arr; } - /** - * Swaps two objects in array. - * - * @param arr Array. - * @param a Index of the first object. - * @param b Index of the second object. - */ - public static void swap(Object[] arr, int a, int b) { - Object tmp = arr[a]; - arr[a] = arr[b]; - arr[b] = tmp; - } - /** * Returns array which is the union of two arrays * (array of elements contained in any of provided arrays). @@ -7744,74 +6158,6 @@ public static int[] copyIfExceeded(int[] arr, int len) { return len == arr.length ? arr : Arrays.copyOf(arr, len); } - /** - * - * @param t Tokenizer. - * @param str Input string. - * @param date Date. - * @return Next token. - * @throws IgniteCheckedException Thrown in case of any errors. - */ - private static boolean checkNextToken(StringTokenizer t, String str, String date) throws IgniteCheckedException { - try { - if (t.nextToken().equals(str)) - return true; - else - throw new IgniteCheckedException("Invalid date format: " + date); - } - catch (NoSuchElementException ignored) { - return false; - } - } - - /** - * Adds values to collection and returns the same collection to allow chaining. - * - * @param c Collection to add values to. - * @param vals Values. - * @param Value type. - * @return Passed in collection. - */ - public static > C addAll(C c, V... vals) { - Collections.addAll(c, vals); - - return c; - } - - /** - * Adds values to collection and returns the same collection to allow chaining. - * - * @param m Map to add entries to. - * @param entries Entries. - * @param Key type. - * @param Value type. - * @param Map type. - * @return Passed in collection. - */ - public static > M addAll(M m, Map.Entry... entries) { - for (Map.Entry e : entries) - m.put(e.getKey(), e.getValue()); - - return m; - } - - /** - * Adds values to collection and returns the same collection to allow chaining. - * - * @param m Map to add entries to. - * @param entries Entries. - * @param Key type. - * @param Value type. - * @param Map type. - * @return Passed in collection. - */ - public static > M addAll(M m, IgniteBiTuple... entries) { - for (IgniteBiTuple t : entries) - m.put(t.get1(), t.get2()); - - return m; - } - /** * Utility method creating {@link JMException} with given cause. Keeps only the error message to avoid * deserialization failure on remote side due to the other class path. @@ -7866,16 +6212,6 @@ public static IgniteCheckedException cast(Throwable t) { : new IgniteCheckedException(t); } - /** - * Checks if class loader is an internal P2P class loader. - * - * @param o Object to check. - * @return {@code True} if P2P class loader. - */ - public static boolean p2pLoader(Object o) { - return o != null && p2pLoader(o.getClass().getClassLoader()); - } - /** * Checks if class loader is an internal P2P class loader. * @@ -7966,37 +6302,6 @@ public static IgniteClosure id2Node(final GridKernalContext c }; } - /** - * Dumps stack for given thread. - * - * @param t Thread to dump stack for. - * - * @deprecated Calls to this method should never be committed to master. - */ - @Deprecated - public static void dumpStack(Thread t) { - dumpStack(t, System.err); - } - - /** - * Dumps stack for given thread. - * - * @param t Thread to dump stack for. - * @param s {@code PrintStream} to use for output. - * - * @deprecated Calls to this method should never be committed to master. - */ - @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) - @Deprecated - public static void dumpStack(Thread t, PrintStream s) { - synchronized (s) { - s.println("Dumping stack trace for thread: " + t); - - for (StackTraceElement trace : t.getStackTrace()) - s.println("\tat " + trace); - } - } - /** * Checks if object is a primitive array. * @@ -8012,41 +6317,6 @@ public static boolean isPrimitiveArray(Object obj) { return cls.isArray() && cls.getComponentType().isPrimitive(); } - /** - * @param cls Class. - * @return {@code True} if given class represents a primitive or a primitive wrapper class. - * - */ - public static boolean isPrimitiveOrWrapper(Class cls) { - return cls.isPrimitive() || - Boolean.class.equals(cls) || - Byte.class.equals(cls) || - Character.class.equals(cls) || - Short.class.equals(cls) || - Integer.class.equals(cls) || - Long.class.equals(cls) || - Float.class.equals(cls) || - Double.class.equals(cls) || - Void.class.equals(cls); - } - - /** - * Awaits for condition. - * - * @param cond Condition to await for. - * @throws IgniteInterruptedCheckedException Wrapped {@link InterruptedException} - */ - public static void await(Condition cond) throws IgniteInterruptedCheckedException { - try { - cond.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - - throw new IgniteInterruptedCheckedException(e); - } - } - /** * Awaits for condition ignoring interrupts. * @@ -8357,56 +6627,6 @@ public static boolean tryAcquire(Semaphore sem, long timeout, TimeUnit unit) } } - /** - * Gets cache attributes for the node. - * - * @param n Node to get cache attributes for. - * @return Array of cache attributes for the node. - */ - public static GridCacheAttributes[] cacheAttributes(ClusterNode n) { - return n.attribute(ATTR_CACHE); - } - - /** - * Checks if given node has near cache enabled for the specified - * partitioned cache. - * - * @param n Node. - * @param cacheName Cache name. - * @return {@code true} if given node has near cache enabled for the - * specified partitioned cache. - */ - public static boolean hasNearCache(ClusterNode n, String cacheName) { - GridCacheAttributes[] caches = n.attribute(ATTR_CACHE); - - if (caches != null) - for (GridCacheAttributes attrs : caches) - if (Objects.equals(cacheName, attrs.cacheName())) - return attrs.nearCacheEnabled(); - - return false; - } - - /** - * Adds listener to asynchronously log errors. - * - * @param f Future to listen to. - * @param log Logger. - */ - public static void asyncLogError(IgniteInternalFuture f, final IgniteLogger log) { - if (f != null) - f.listen(new CI1>() { - @Override public void apply(IgniteInternalFuture f) { - try { - f.get(); - } - catch (IgniteCheckedException e) { - U.error(log, "Failed to execute future: " + f, e); - } - } - }); - } - /** * Converts collection of nodes to collection of node IDs. * @@ -8417,20 +6637,6 @@ public static Collection nodeIds(@Nullable Collection gridIds(@Nullable Collection grids) { - return F.viewReadOnly(grids, new C1() { - @Override public UUID apply(Ignite g) { - return g.cluster().localNode().id(); - } - }); - } - /** * Converts collection of Grid instances to collection of grid names. * @@ -8459,39 +6665,6 @@ public static Collection nodes2names(@Nullable Collection>> 10); - hash += (hash << 3); - hash ^= (hash >>> 6); - hash += (hash << 2) + (hash << 14); - - int shift = 0; - int size = 1; - - while (size < concurLvl) { - ++shift; - size <<= 1; - } - - int segmentShift = 32 - shift; - int segmentMask = size - 1; - - return (hash >>> segmentShift) & segmentMask; - } - - /** - * @param map Map. - */ - public static void printConcurrentHashMapInfo(ConcurrentHashMap map) { - assert map != null; - - Object[] segs = field(map, "segments"); - - X.println("Concurrent map stats [identityHash= " + System.identityHashCode(map) + - ", segsCnt=" + segs.length + ']'); - - int emptySegsCnt = 0; - - int totalCollisions = 0; - - for (int i = 0; i < segs.length; i++) { - int segCnt = IgniteUtils.field(segs[i], "count"); - - if (segCnt == 0) { - emptySegsCnt++; - - continue; - } - - Object[] tab = field(segs[i], "table"); - - int tabLen = tab.length; - - X.println(" Segment-" + i + " [count=" + segCnt + ", len=" + tabLen + ']'); - - // Group buckets by entries count. - Map bucketsStats = new TreeMap<>(); - - for (Object entry : tab) { - int cnt = 0; - - while (entry != null) { - cnt++; - - entry = field(entry, "next"); - } - - Integer bucketCnt = bucketsStats.get(cnt); - - if (bucketCnt == null) - bucketCnt = 0; - - bucketCnt++; - - bucketsStats.put(cnt, bucketCnt); - - if (cnt > 1) - totalCollisions += (cnt - 1); - } - - for (Map.Entry e : bucketsStats.entrySet()) - X.println(" Buckets with count " + e.getKey() + ": " + e.getValue()); - } - - X.println(" Map summary [emptySegs=" + emptySegsCnt + ", collisions=" + totalCollisions + ']'); - } - /** * Gets field value. * @@ -8667,22 +6752,6 @@ public static boolean hasField(Object obj, String fieldName) { } } - /** - * Gets object field offset. - * - * @param cls Object class. - * @param fieldName Field name. - * @return Field offset. - */ - public static long fieldOffset(Class cls, String fieldName) { - try { - return objectFieldOffset(cls.getDeclaredField(fieldName)); - } - catch (NoSuchFieldException e) { - throw new IllegalStateException(e); - } - } - /** * @param cls Class to check. * @return {@code True} if class is final. @@ -8768,61 +6837,8 @@ public static T invoke(@Nullable Class cls, @Nullable Object obj, String } } - if (mtd == null) - continue; - - boolean accessible = mtd.isAccessible(); - - T res; - - try { - mtd.setAccessible(true); - - res = (T)mtd.invoke(obj, params); - } - finally { - if (!accessible) - mtd.setAccessible(false); - } - - return res; - } - } - catch (Exception e) { - throw new IgniteCheckedException("Failed to invoke [mtdName=" + mtdName + ", cls=" + cls + ']', - e); - } - - throw new IgniteCheckedException("Failed to invoke (method was not found) [mtdName=" + mtdName + - ", cls=" + cls + ']'); - } - - /** - * Invokes method. - * - * @param cls Object. - * @param obj Object. - * @param mtdName Field name. - * @param paramTypes Parameter types. - * @param params Parameters. - * @return Field value. - * @throws IgniteCheckedException If static field with given name cannot be retrieved. - */ - public static T invoke(@Nullable Class cls, @Nullable Object obj, String mtdName, - Class[] paramTypes, Object... params) throws IgniteCheckedException { - assert cls != null || obj != null; - assert mtdName != null; - - try { - for (cls = cls != null ? cls : obj.getClass(); cls != Object.class; cls = cls.getSuperclass()) { - Method mtd; - - try { - mtd = cls.getDeclaredMethod(mtdName, paramTypes); - } - catch (NoSuchMethodException ignored) { + if (mtd == null) continue; - } boolean accessible = mtd.isAccessible(); @@ -9007,74 +7023,6 @@ public static void removeJavaNoOpLogger(Collection rmvHnds) { } } - /** - * Attaches node ID to log file name. - * - * @param nodeId Node ID. - * @param fileName File name. - * @return File name with node ID. - */ - @SuppressWarnings("IfMayBeConditional") - public static String nodeIdLogFileName(UUID nodeId, String fileName) { - assert nodeId != null; - assert fileName != null; - - fileName = GridFilenameUtils.separatorsToSystem(fileName); - - int dot = fileName.lastIndexOf('.'); - - if (dot < 0 || dot == fileName.length() - 1) - return fileName + '-' + U.id8(nodeId); - else - return fileName.substring(0, dot) + '-' + U.id8(nodeId) + fileName.substring(dot); - } - - /** - * Substitutes log directory with a custom one. - * - * @param dir Directory. - * @param fileName Original path. - * @return New path. - */ - public static String customDirectoryLogFileName(@Nullable String dir, String fileName) { - assert fileName != null; - - if (dir == null) - return fileName; - - int sep = fileName.lastIndexOf(File.separator); - - return dir + (sep < 0 ? File.separator + fileName : fileName.substring(sep)); - } - - /** - * Creates string for log output. - * - * @param msg Message to start string. - * @param args Even length array where the odd elements are parameter names - * and even elements are parameter values. - * @return Log message, formatted as recommended by Ignite guidelines. - */ - public static String fl(String msg, Object... args) { - assert args.length % 2 == 0; - - StringBuilder sb = new StringBuilder(msg); - - if (args.length > 0) { - sb.append(" ["); - - for (int i = 0; i < args.length / 2; i++) { - sb.append(args[i * 2]).append('=').append(args[i * 2 + 1]); - sb.append(", "); - } - - sb.delete(sb.length() - 2, sb.length()); - sb.append(']'); - } - - return sb.toString(); - } - /** * Round up the argument to the next highest power of 2; * @@ -9150,7 +7098,7 @@ public static long ensurePositive(long i, long dflt) { * @throws ClassNotFoundException If class not found. */ public static Class forName(String clsName, @Nullable ClassLoader ldr) throws ClassNotFoundException { - return U.forName(clsName, ldr, null, GridBinaryMarshaller.USE_CACHE.get()); + return forName(clsName, ldr, null, GridBinaryMarshaller.USE_CACHE.get()); } /** @@ -9436,28 +7384,6 @@ public static String maskForFileName(CharSequence name) { return b.toString(); } - /** - * @param obj Object. - * @return {@code True} if given object has overridden equals and hashCode method. - */ - public static boolean overridesEqualsAndHashCode(Object obj) { - return overridesEqualsAndHashCode(obj.getClass()); - } - - /** - * @param cls Class. - * @return {@code True} if given class has overridden equals and hashCode method. - */ - public static boolean overridesEqualsAndHashCode(Class cls) { - try { - return !Object.class.equals(cls.getMethod("equals", Object.class).getDeclaringClass()) && - !Object.class.equals(cls.getMethod("hashCode").getDeclaringClass()); - } - catch (NoSuchMethodException | SecurityException ignore) { - return true; // Ignore. - } - } - /** * Checks if error is MAC invalid argument error which ususally requires special handling. * @@ -9465,7 +7391,7 @@ public static boolean overridesEqualsAndHashCode(Class cls) { * @return {@code True} if error is invalid argument error on MAC. */ public static boolean isMacInvalidArgumentError(Exception e) { - return U.isMacOs() && e instanceof SocketException && e.getMessage() != null && + return isMacOs() && e instanceof SocketException && e.getMessage() != null && e.getMessage().toLowerCase().contains("invalid argument"); } @@ -9521,7 +7447,7 @@ public static void stopLifecycleAware(IgniteLogger log, Iterable objs) { ((LifecycleAware)obj).stop(); } catch (Exception e) { - U.error(log, "Failed to stop component (ignoring): " + obj, e); + error(log, "Failed to stop component (ignoring): " + obj, e); } } } @@ -9632,12 +7558,12 @@ private static InetSocketAddress createResolved(String addr, int port) { long duration = endNanos - startNanos; - long threshold = U.millisToNanos(200); + long threshold = millisToNanos(200); if (duration > threshold) { log.log(Level.FINE, new TimeoutException(), () -> S.toString( "Resolving address took too much time", - "duration(ms)", U.nanosToMillis(duration), false, + "duration(ms)", nanosToMillis(duration), false, "addr", addr, false, "port", port, false, "thread", Thread.currentThread().getName(), false @@ -9803,13 +7729,16 @@ else if (!F.isEmpty(userIgniteHome)) File readme = new File(igniteDir, "README.txt"); if (!readme.exists()) { - U.writeStringToFile(readme, + writeStringToFile( + readme, "This is Apache Ignite working directory that contains information that \n" + " Ignite nodes need in order to function normally.\n" + "Don't delete it unless you're sure you know what you're doing.\n\n" + "You can change the location of working directory with \n" + " igniteConfiguration.setWorkDirectory(location) or \n" + - " in IgniteConfiguration .\n"); + " in IgniteConfiguration .\n", + Charset.defaultCharset().toString(), + false); } } catch (Exception ignore) { @@ -9876,7 +7805,7 @@ public static File resolveWorkDirectory(String workDir, String path, boolean del } if (delIfExist && dir.exists()) { - if (!U.delete(dir)) + if (!delete(dir)) throw new IgniteCheckedException("Failed to delete directory: " + dir); } @@ -9918,32 +7847,6 @@ else if (!dir.isDirectory()) log.info("Resolved " + msg + ": " + dir.getAbsolutePath()); } - /** - * Checks if the given directory exists and attempts to create one if not. - * - * @param dir Directory to check. - * @param msg Directory name for the messages. - * @param 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. - */ - public static void ensureDirectory(Path dir, String msg, IgniteLogger log) throws IgniteCheckedException { - if (!Files.exists(dir)) { - try { - Files.createDirectories(dir); - } - catch (IOException e) { - throw new IgniteCheckedException("Failed to create " + msg + ": " + dir.toAbsolutePath(), e); - } - } - else if (!Files.isDirectory(dir)) - throw new IgniteCheckedException("Failed to initialize " + msg + - " (a file with the same name already exists): " + dir.toAbsolutePath()); - - if (log != null && log.isInfoEnabled()) - log.info("Resolved " + msg + ": " + dir.toAbsolutePath()); - } - /** * Creates {@code IgniteCheckedException} with the collection of suppressed exceptions. * @@ -10114,60 +8017,6 @@ public static Map limitedMap(int limit) { return new HashMap<>(capacity(limit), 0.75f); } - /** - * Create a map with single key-value pair. - * - * @param k Key. - * @param v Value. - * @return Map. - */ - public static Map map(K k, V v) { - GridLeanMap map = new GridLeanMap<>(1); - - map.put(k, v); - - return map; - } - - /** - * Create a map with two key-value pairs. - * - * @param k1 Key 1. - * @param v1 Value 1. - * @param k2 Key 2. - * @param v2 Value 2. - * @return Map. - */ - public static Map map(K k1, V v1, K k2, V v2) { - GridLeanMap map = new GridLeanMap<>(2); - - map.put(k1, v1); - map.put(k2, v2); - - return map; - } - - /** - * Create a map with three key-value pairs. - * - * @param k1 Key 1. - * @param v1 Value 1. - * @param k2 Key 2. - * @param v2 Value 2. - * @param k3 Key 3. - * @param v3 Value 3. - * @return Map. - */ - public static Map map(K k1, V v1, K k2, V v2, K k3, V v3) { - GridLeanMap map = new GridLeanMap<>(3); - - map.put(k1, v1); - map.put(k2, v2); - map.put(k3, v3); - - return map; - } - /** * @param col non-null collection with one element * @return a SingletonList containing the element in the original collection @@ -10385,47 +8234,6 @@ public static List arrayList(Iterator c, int cap, return list; } - /** - * Calculate MD5 digits. - * - * @param in Input stream. - * @return Calculated MD5 digest for given input stream. - * @throws NoSuchAlgorithmException If MD5 algorithm was not found. - * @throws IOException If an I/O exception occurs. - */ - public static byte[] calculateMD5Digest(@NotNull InputStream in) throws NoSuchAlgorithmException, IOException { - MessageDigest md = MessageDigest.getInstance("MD5"); - InputStream fis = new BufferedInputStream(in); - byte[] dataBytes = new byte[1024]; - - int nread; - - while ((nread = fis.read(dataBytes)) != -1) - md.update(dataBytes, 0, nread); - - return md.digest(); - } - - /** - * Calculate MD5 string. - * - * @param in Input stream. - * @return Calculated MD5 string for given input stream. - * @throws NoSuchAlgorithmException If MD5 algorithm was not found. - * @throws IOException If an I/O exception occurs. - */ - public static String calculateMD5(InputStream in) throws NoSuchAlgorithmException, IOException { - byte[] md5Bytes = calculateMD5Digest(in); - - // Convert the byte to hex format. - StringBuilder sb = new StringBuilder(); - - for (byte md5Byte : md5Bytes) - sb.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1)); - - return sb.toString(); - } - /** * Fully writes communication message to provided stream. * @@ -10590,33 +8398,6 @@ public static T unmarshalZip(Marshaller marsh, byte[] zipBytes, @Nullable Cl } } - /** - * @param zipBytes Zipped bytes. - * @return Raw bytes. - * @throws IgniteCheckedException If unzip resulted in error. - */ - public static byte[] unzip(byte[] zipBytes) throws IgniteCheckedException { - assert zipBytes != null; - - try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(zipBytes))) { - - in.getNextEntry(); - - byte[] tmp = new byte[4 << 10]; - - int size; - - while ((size = in.read(tmp)) != -1) - baos.write(tmp, 0, size); - - return baos.toByteArray(); - } - catch (Exception e) { - throw new IgniteCheckedException(e); - } - } - /** * Unmarshals object from the input stream using given class loader. * This method should not close given input stream. @@ -10665,7 +8446,7 @@ public static T unmarshal(GridKernalContext ctx, byte[] arr, @Nullable Class assert arr != null; try { - return U.unmarshal(ctx.marshaller(), arr, clsLdr); + return unmarshal(ctx.marshaller(), arr, clsLdr); } catch (IgniteCheckedException e) { throw e; @@ -10694,7 +8475,7 @@ public static T unmarshal(GridCacheSharedContext ctx, byte[] arr, @Nullable assert arr != null; try { - return U.unmarshal(ctx.marshaller(), arr, clsLdr); + return unmarshal(ctx.marshaller(), arr, clsLdr); } catch (IgniteCheckedException e) { throw e; @@ -10986,8 +8767,8 @@ public static long adjustedWalHistorySize(DataStorageConfiguration dsCfg, @Nulla if (adjustedWalArchiveSize > dsCfg.getMaxWalArchiveSize()) { if (log != null) - U.quietAndInfo(log, "Automatically adjusted max WAL archive size to " + - U.readableSize(adjustedWalArchiveSize, false) + + quietAndInfo(log, "Automatically adjusted max WAL archive size to " + + readableSize(adjustedWalArchiveSize, false) + " (to override, use DataStorageConfiguration.setMaxWalArchiveSize)"); return adjustedWalArchiveSize; @@ -11019,113 +8800,6 @@ else if (Files.isRegularFile(d)) return cnt; } - /** - * Will calculate the size of a directory. - * - * If there is concurrent activity in the directory, than returned value may be wrong. - */ - public static long dirSize(Path path) throws IgniteCheckedException { - final AtomicLong s = new AtomicLong(0); - - try { - Files.walkFileTree(path, new SimpleFileVisitor() { - @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - s.addAndGet(attrs.size()); - - return FileVisitResult.CONTINUE; - } - - @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { - U.error(null, "file skipped - " + file, exc); - - // Skip directory or file - return FileVisitResult.CONTINUE; - } - - @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { - if (exc != null) - U.error(null, "error during size calculation of directory - " + dir, exc); - - // Ignoring - return FileVisitResult.CONTINUE; - } - }); - } - catch (IOException e) { - throw new IgniteCheckedException("walkFileTree will not throw IOException if the FileVisitor does not"); - } - - return s.get(); - } - - /** - * @param path Path. - * @param name Name. - */ - public static Path searchFileRecursively(Path path, @NotNull final String name) throws IgniteCheckedException { - final AtomicReference res = new AtomicReference<>(); - - try { - Files.walkFileTree(path, new SimpleFileVisitor() { - @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - if (name.equals(file.getFileName().toString())) { - res.set(file); - - return FileVisitResult.TERMINATE; - } - - return FileVisitResult.CONTINUE; - } - - @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { - U.error(null, "file skipped during recursive search - " + file, exc); - - // Ignoring. - return FileVisitResult.CONTINUE; - } - - @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { - if (exc != null) - U.error(null, "error during recursive search - " + dir, exc); - - // Ignoring. - return FileVisitResult.CONTINUE; - } - }); - } - catch (IOException e) { - throw new IgniteCheckedException("walkFileTree will not throw IOException if the FileVisitor does not"); - } - - return res.get(); - } - - /** - * Returns {@link GridIntIterator} for range of primitive integers. - * @param start Start. - * @param cnt Count. - */ - public static GridIntIterator forRange(final int start, final int cnt) { - return new GridIntIterator() { - int c = 0; - - @Override public boolean hasNext() { - return c < cnt; - } - - @Override public int next() { - return start + c++; - } - }; - } - - /** - * @param x X. - */ - public static int nearestPow2(int x) { - return nearestPow2(x, true); - } - /** * @param x X. * @param less Less. @@ -11190,33 +8864,6 @@ public static void enhanceThreadName(@Nullable Thread thread, String text) { thread.setName(sb.toString()); } - /** - * @param ctx Context. - * - * @return instance of current baseline topology if it exists - */ - public static BaselineTopology getBaselineTopology(@NotNull GridKernalContext ctx) { - return ctx.state().clusterState().baselineTopology(); - } - - /** - * @param cctx Context. - * - * @return instance of current baseline topology if it exists - */ - public static BaselineTopology getBaselineTopology(@NotNull GridCacheSharedContext cctx) { - return getBaselineTopology(cctx.kernalContext()); - } - - /** - * @param cctx Context. - * - * @return instance of current baseline topology if it exists - */ - public static BaselineTopology getBaselineTopology(@NotNull GridCacheContext cctx) { - return getBaselineTopology(cctx.kernalContext()); - } - /** * Check that node Ignite product version is not less then specified. * @@ -11569,7 +9216,7 @@ public static boolean isLocalNodeCoordinator(GridDiscoveryManager discoMgr) { return spi instanceof TcpDiscoverySpi ? ((TcpDiscoverySpi)spi).isLocalNodeCoordinator() - : Objects.equals(discoMgr.localNode(), U.oldest(discoMgr.aliveServerNodes(), null)); + : Objects.equals(discoMgr.localNode(), oldest(discoMgr.aliveServerNodes(), null)); } /** @@ -11694,26 +9341,6 @@ public static Runnable wrapIgniteFuture(Runnable r, GridFutureAdapter fut) { }; } - /** - * @param key Cipher Key. - * @param encMode Enc mode see {@link Cipher#ENCRYPT_MODE}, {@link Cipher#DECRYPT_MODE}, etc. - */ - public static Cipher createCipher(Key key, int encMode) { - if (key == null) - throw new IgniteException("Cipher Key cannot be null"); - - try { - Cipher cipher = Cipher.getInstance(key.getAlgorithm()); - - cipher.init(encMode, key); - - return cipher; - } - catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { - throw new IgniteException(e); - } - } - /** * Safely write buffer fully to blocking socket channel. * Will throw assert if non blocking channel passed. @@ -11757,17 +9384,6 @@ public static int stripeIdx(int stripes, int grpId, int partId) { return Math.abs((Math.abs(grpId) + partId)) % stripes; } - /** - * Check if flag set. - * - * @param flags Flags. - * @param flag Flag. - * @return {@code True} if set. - */ - public static boolean isFlagSet(int flags, int flag) { - return (flags & flag) == flag; - } - /** * Notifies provided {@code lsnrs} with the value {@code t}. * @@ -11784,7 +9400,7 @@ public static void notifyListeners(T t, Collection> lsnrs, Ignit lsnr.accept(t); } catch (Exception e) { - U.warn(log, "Listener error", e); + warn(log, "Listener error", e); } } } @@ -11815,19 +9431,10 @@ public static void awaitForWorkersStop( } } - /** - * Unquote the given string. - * @param s String. - * @return Unquoted string. - */ - public static String unquote(String s) { - return s == null ? null : s.replaceAll("^\"|\"$", ""); - } - /** * Writes string to output stream accounting for {@code null} values.
* - * This method can write string of any length, no {@link #UTF_BYTE_LIMIT} limits are applied. + * This method can write string of any length, limit of 65535 is not applied. * * @param out Output stream to write to. * @param s String to write, possibly {@code null}. @@ -11867,7 +9474,7 @@ else if (utfBytes == 3) { /** * Reads string from input stream accounting for {@code null} values.
* - * This method can read string of any length, no {@link #UTF_BYTE_LIMIT} limits are applied. + * This method can read string of any length, limit of 65535 is not applied. * * @param in Stream to read from. * @return Read string, possibly {@code null}. @@ -11927,42 +9534,6 @@ else if (utfBytes == 3) { return strBuilder.toString(); } - /** - * Writes string to output stream accounting for {@code null} values.
- * - *

- * Uses {@link ObjectOutputStream#writeUTF(String)} to write the string under the hood - * but cuts strings longer than {@link #UTF_BYTE_LIMIT} to the limit to avoid {@link UTFDataFormatException}. - *

- * - *

- * Strings written by the method can be read by {@link #readString(DataInput)}. - *

- * - * @see #writeString(DataOutput, String) for more information. - * - * @param out Output stream to write to. - * @param s String to write, possibly {@code null}. - * @throws IOException If write failed. - */ - public static void writeCutString(DataOutput out, @Nullable String s) throws IOException { - // Write null flag. - out.writeBoolean(isNull(s)); - - if (isNull(s)) - return; - - //Conversion of string to limit. - for (int i = 0, bs = 0; i < s.length(); i++) { - if ((bs += utfBytes(s.charAt(i))) > UTF_BYTE_LIMIT) { - s = s.substring(0, i); - break; - } - } - - out.writeUTF(s); - } - /** * Get number of bytes for {@link DataOutput#writeUTF}, * depending on character:
@@ -11984,35 +9555,6 @@ public static int utfBytes(char c) { return (c >= 0x0001 && c <= 0x007F) ? 1 : (c > 0x07FF) ? 3 : 2; } - /** - * Broadcasts given job to nodes that match filter. - * - * @param kctx Kernal context. - * @param job Ignite job. - * @param srvrsOnly Broadcast only on server nodes. - * @param nodeFilter Node filter. - */ - public static IgniteFuture broadcastToNodesWithFilterAsync( - GridKernalContext kctx, - IgniteRunnable job, - boolean srvrsOnly, - IgnitePredicate nodeFilter - ) { - ClusterGroup cl = kctx.grid().cluster(); - - if (srvrsOnly) - cl = cl.forServers(); - - ClusterGroup grp = nodeFilter != null ? cl.forPredicate(nodeFilter) : cl; - - if (grp.nodes().isEmpty()) - return new IgniteFinishedFutureImpl<>(); - - IgniteCompute compute = kctx.grid().compute(grp); - - return compute.broadcastAsync(job); - } - /** * Reads string-to-string map written by {@link #writeStringMap(DataOutput, Map)}. * @@ -12026,7 +9568,7 @@ public static Map readStringMap(DataInput in) throws IOException if (size == -1) return null; else { - Map map = U.newHashMap(size); + Map map = newHashMap(size); for (int i = 0; i < size; i++) map.put(readUTF(in), readUTF(in)); @@ -12288,7 +9830,7 @@ else if (s.contains("clojure")) { } // How to get Groovy and Clojure version at runtime?!? - return groovy ? "Groovy" : clojure ? "Clojure" : U.jdkName() + " ver. " + U.jdkVersion(); + return groovy ? "Groovy" : clojure ? "Clojure" : jdkName + " ver. " + jdkVersion(); } /** diff --git a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/messages/NodeIdMessage.java b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/messages/NodeIdMessage.java index 12e2522ce4f05..80ee095fb8dc4 100644 --- a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/messages/NodeIdMessage.java +++ b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/messages/NodeIdMessage.java @@ -67,21 +67,6 @@ public byte[] nodeIdBytes() { return nodeIdBytes; } - /** - * @param nodeId Node ID. - * @return Marshalled node ID bytes with direct message type. - */ - public static byte[] nodeIdBytesWithType(UUID nodeId) { - byte[] nodeIdBytesWithType = new byte[MESSAGE_FULL_SIZE]; - - nodeIdBytesWithType[0] = (byte)(TcpCommunicationSpi.NODE_ID_MSG_TYPE & 0xFF); - nodeIdBytesWithType[1] = (byte)((TcpCommunicationSpi.NODE_ID_MSG_TYPE >> 8) & 0xFF); - - U.uuidToBytes(nodeId, nodeIdBytesWithType, 2); - - return nodeIdBytesWithType; - } - /** {@inheritDoc} */ @Override public void onAckReceived() { // No-op. diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/internal/DiscoveryDataPacket.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/internal/DiscoveryDataPacket.java index 8d861450f4b7a..5dff4b089b8fe 100644 --- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/internal/DiscoveryDataPacket.java +++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/internal/DiscoveryDataPacket.java @@ -407,21 +407,6 @@ private void marshalData( } } - /** - * @param log Logger. - */ - public void unzipData(IgniteLogger log) { - for (Map.Entry entry : joiningNodeData.entrySet()) { - try { - entry.setValue(U.unzip(entry.getValue())); - } - catch (IgniteCheckedException e) { - U.error(log, "Failed to unzip discovery data " + - "[comp=" + entry.getKey() + ']', e); - } - } - } - /** * TODO https://issues.apache.org/jira/browse/IGNITE-4435 */ diff --git a/modules/core/src/test/java/org/apache/ignite/internal/metric/JmxExporterSpiTest.java b/modules/core/src/test/java/org/apache/ignite/internal/metric/JmxExporterSpiTest.java index c0f2db8fb1b76..ed21575c046f4 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/metric/JmxExporterSpiTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/metric/JmxExporterSpiTest.java @@ -1127,7 +1127,7 @@ public void testPagesList() throws Exception { for (int i = 0; i < 10; i++) cache.put(i, i); - TabularDataSupport view = filteredSystemView(ignite, CACHE_GRP_PAGE_LIST_VIEW, U.map( + TabularDataSupport view = filteredSystemView(ignite, CACHE_GRP_PAGE_LIST_VIEW, Map.of( CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId(cacheName), CachePagesListViewWalker.PARTITION_ID_FILTER, 0, CachePagesListViewWalker.BUCKET_NUMBER_FILTER, 0 @@ -1135,7 +1135,7 @@ CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId(cacheName), assertEquals(1, view.size()); - view = filteredSystemView(ignite, CACHE_GRP_PAGE_LIST_VIEW, U.map( + view = filteredSystemView(ignite, CACHE_GRP_PAGE_LIST_VIEW, Map.of( CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId(cacheName), CachePagesListViewWalker.BUCKET_NUMBER_FILTER, 0 )); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/metric/SystemViewSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/metric/SystemViewSelfTest.java index 5aacefb068d81..80f022dd81fd2 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/metric/SystemViewSelfTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/metric/SystemViewSelfTest.java @@ -2084,7 +2084,7 @@ public void testPagesList() throws Exception { // Test filtering. assertTrue(cacheGrpPageLists instanceof FiltrableSystemView); - Iterator iter = ((FiltrableSystemView)cacheGrpPageLists).iterator(U.map( + Iterator iter = ((FiltrableSystemView)cacheGrpPageLists).iterator(Map.of( CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId("cache1"), CachePagesListViewWalker.PARTITION_ID_FILTER, 0, CachePagesListViewWalker.BUCKET_NUMBER_FILTER, 0 @@ -2092,7 +2092,7 @@ CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId("cache1"), assertEquals(1, F.size(iter)); - iter = ((FiltrableSystemView)cacheGrpPageLists).iterator(U.map( + iter = ((FiltrableSystemView)cacheGrpPageLists).iterator(Map.of( CachePagesListViewWalker.CACHE_GROUP_ID_FILTER, cacheId("cache1"), CachePagesListViewWalker.BUCKET_NUMBER_FILTER, 0 )); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/partitioned/GridCachePartitionedQueueEntryMoveSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/partitioned/GridCachePartitionedQueueEntryMoveSelfTest.java index cfe72e4bbc8c3..9a88f28b973ba 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/partitioned/GridCachePartitionedQueueEntryMoveSelfTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/partitioned/GridCachePartitionedQueueEntryMoveSelfTest.java @@ -87,7 +87,7 @@ public class GridCachePartitionedQueueEntryMoveSelfTest extends IgniteCollection public void testQueue() throws Exception { final String queueName = "qq"; - System.out.println(U.filler(20, '\n')); + System.out.println(U.nl().repeat(20)); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); @@ -127,7 +127,7 @@ public void testQueue() throws Exception { startAdditionalNodes(BACKUP_CNT + 2, queueName); - System.out.println(U.filler(20, '\n')); + System.out.println(U.nl().repeat(20)); latch2.countDown(); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/ContinuousQueryRemoteFilterMissingInClassPathSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/ContinuousQueryRemoteFilterMissingInClassPathSelfTest.java index 0853a53bcb8c2..62873ce51fd01 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/ContinuousQueryRemoteFilterMissingInClassPathSelfTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/ContinuousQueryRemoteFilterMissingInClassPathSelfTest.java @@ -20,6 +20,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; +import java.util.Map; import javax.cache.configuration.Factory; import javax.cache.event.CacheEntryEvent; import javax.cache.event.CacheEntryEventFilter; @@ -35,7 +36,6 @@ import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.util.typedef.X; -import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.GridStringLogger; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.ListeningTestLogger; @@ -101,7 +101,7 @@ public class ContinuousQueryRemoteFilterMissingInClassPathSelfTest extends GridC cfg.setGridLogger(log); if (setFilterAttr) - cfg.setUserAttributes(U.map("filter", 1)); + cfg.setUserAttributes(Map.of("filter", 1)); return cfg; } diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxPartitionCounterStateOnePrimaryTwoBackupsTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxPartitionCounterStateOnePrimaryTwoBackupsTest.java index 1ce5ef69f5192..3deaf4f980921 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxPartitionCounterStateOnePrimaryTwoBackupsTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxPartitionCounterStateOnePrimaryTwoBackupsTest.java @@ -34,13 +34,14 @@ import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.internal.util.typedef.T2; import org.apache.ignite.internal.util.typedef.X; -import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteClosure; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.testframework.GridTestUtils; import org.jetbrains.annotations.Nullable; import org.junit.Test; +import static java.util.Map.of; + /** * Tests scenarios for tx reordering, missed updates and recovery for 2PC. */ @@ -273,8 +274,8 @@ public void testCommitReorderWithRollbackNoRebalanceAfterRestart() throws Except Ignite primary = map.get(PARTITION_ID).get1(); return new TwoPhaseCommitTxCallbackAdapter( - U.map((IgniteEx)primary, assignOrder), - U.map((IgniteEx)primary, prepOrder), + of((IgniteEx)primary, assignOrder), + of((IgniteEx)primary, prepOrder), new HashMap<>(), sizes.length) { @@ -398,7 +399,7 @@ public void testMissingUpdateBetweenMultipleCheckpoints() throws Exception { Ignite backup1 = map.get(PARTITION_ID).get2().get(delayBackupIdx); return new TwoPhaseCommitTxCallbackAdapter( - U.map((IgniteEx)primary, assignOrder), + of((IgniteEx)primary, assignOrder), new HashMap<>(), new HashMap<>(), sizes.length) { @@ -472,8 +473,8 @@ private void doTestPartialCommit_3tx_1(boolean skipCheckpointOnNodeStop) throws Ignite primary = map.get(PARTITION_ID).get1(); Ignite backup1 = map.get(PARTITION_ID).get2().get(0); - return new TwoPhaseCommitTxCallbackAdapter(U.map((IgniteEx)primary, PREPARE_ORDER), - U.map((IgniteEx)primary, PRIMARY_COMMIT_ORDER, (IgniteEx)backup1, BACKUP_COMMIT_ORDER), + return new TwoPhaseCommitTxCallbackAdapter(of((IgniteEx)primary, PREPARE_ORDER), + of((IgniteEx)primary, PRIMARY_COMMIT_ORDER, (IgniteEx)backup1, BACKUP_COMMIT_ORDER), SIZES.length) { @Override protected boolean onBackupCommitted(IgniteEx backup, int idx) { super.onBackupCommitted(backup, idx); @@ -605,8 +606,8 @@ private void doTestPartialPrepare_3tx(boolean skipCheckpointOnNodeStop, int[] as Ignite backup2 = map.get(PARTITION_ID).get2().get(1); return new TwoPhaseCommitTxCallbackAdapter( - U.map((IgniteEx)primary, assignOrder), - U.map((IgniteEx)backup1, new int[] {2, 0, 1}, (IgniteEx)backup2, new int[] {2, 1, 0}), + of((IgniteEx)primary, assignOrder), + of((IgniteEx)backup1, new int[] {2, 0, 1}, (IgniteEx)backup2, new int[] {2, 1, 0}), new HashMap<>(), SIZES.length) { @Override protected boolean onBackupPrepared(IgniteEx backup, IgniteInternalTx tx, int idx) { @@ -712,8 +713,8 @@ private void doTestPartialPrepare_2tx(boolean skipCheckpointOnNodeStop, Ignite backup2 = map.get(PARTITION_ID).get2().get(1); return new TwoPhaseCommitTxCallbackAdapter( - U.map((IgniteEx)primary, assignOrder), - U.map((IgniteEx)backup1, backup1PrepOrder, (IgniteEx)backup2, backup2PrepOrder), + of((IgniteEx)primary, assignOrder), + of((IgniteEx)backup1, backup1PrepOrder, (IgniteEx)backup2, backup2PrepOrder), new HashMap<>(), sizes.length) { @Override protected boolean onBackupPrepared(IgniteEx backup, IgniteInternalTx tx, int idx) { @@ -800,8 +801,8 @@ private void doTestPartialCommit_2tx(boolean skipCheckpointOnNodeStop, int[] ass Ignite backup2 = map.get(PARTITION_ID).get2().get(1); return new TwoPhaseCommitTxCallbackAdapter( - U.map((IgniteEx)primary, assignOrder), - U.map((IgniteEx)backup1, new int[] {1, 0}, (IgniteEx)backup2, new int[] {1, 0}), + of((IgniteEx)primary, assignOrder), + of((IgniteEx)backup1, new int[] {1, 0}, (IgniteEx)backup2, new int[] {1, 0}), new HashMap<>(), sizes.length) { @Override public boolean beforeBackupFinish(IgniteEx primary, IgniteEx backup, @@ -871,8 +872,8 @@ private void doTestPartialCommit_3tx_2(boolean skipCheckpointOnStop) throws Exce final Ignite backup2 = map.get(PARTITION_ID).get2().get(1); return new TwoPhaseCommitTxCallbackAdapter( - U.map((IgniteEx)primary, new int[] {0, 1, 2}), - U.map( + of((IgniteEx)primary, new int[] {0, 1, 2}), + of( (IgniteEx)primary, new int[] {0, 1, 2}, (IgniteEx)backup1, new int[] {0, 1, 2}, (IgniteEx)backup2, new int[] {0, 1, 2}), diff --git a/modules/core/src/test/java/org/apache/ignite/internal/util/IgniteUtilsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/util/IgniteUtilsSelfTest.java index 46b7efde4e3a4..658032623d8aa 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/util/IgniteUtilsSelfTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/util/IgniteUtilsSelfTest.java @@ -38,15 +38,12 @@ import java.math.BigInteger; import java.net.InetAddress; import java.net.InetSocketAddress; -import java.net.URL; -import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Random; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; @@ -81,7 +78,6 @@ import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.testframework.GridTestClassLoader; import org.apache.ignite.testframework.GridTestUtils; -import org.apache.ignite.testframework.http.GridEmbeddedHttpServer; import org.apache.ignite.testframework.junits.WithSystemProperty; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.testframework.junits.common.GridCommonTest; @@ -205,15 +201,6 @@ public void testAllLocalMACsMultiThreaded() throws Exception { }, 32, "thread"); } - /** - * @throws Exception If failed. - */ - @Test - public void testByteArray2String() throws Exception { - assertEquals("{0x0A,0x14,0x1E,0x28,0x32,0x3C,0x46,0x50,0x5A}", - U.byteArray2String(new byte[]{10, 20, 30, 40, 50, 60, 70, 80, 90}, "0x%02X", ",0x%02X")); - } - /** * @throws Exception If failed. */ @@ -242,68 +229,6 @@ private void printFormatMins(long mins) { System.out.println("For " + mins + " minutes: " + U.formatMins(mins)); } - /** - * @throws Exception If failed. - */ - @Test - public void testDownloadUrlFromHttp() throws Exception { - GridEmbeddedHttpServer srv = null; - try { - String urlPath = "/testDownloadUrl/"; - srv = GridEmbeddedHttpServer.startHttpServer().withFileDownloadingHandler(urlPath, - GridTestUtils.resolveIgnitePath("/modules/core/src/test/config/tests.properties")); - - File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "url-http.file"); - - file = U.downloadUrl(new URL(srv.getBaseUrl() + urlPath), file); - - assert file.exists(); - assert file.delete(); - } - finally { - if (srv != null) - srv.stop(1); - } - } - - /** - * @throws Exception If failed. - */ - @Test - public void testDownloadUrlFromHttps() throws Exception { - GridEmbeddedHttpServer srv = null; - try { - String urlPath = "/testDownloadUrl/"; - srv = GridEmbeddedHttpServer.startHttpsServer().withFileDownloadingHandler(urlPath, - GridTestUtils.resolveIgnitePath("modules/core/src/test/config/tests.properties")); - - File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "url-http.file"); - - file = U.downloadUrl(new URL(srv.getBaseUrl() + urlPath), file); - - assert file.exists(); - assert file.delete(); - } - finally { - if (srv != null) - srv.stop(1); - } - } - - /** - * @throws Exception If failed. - */ - @Test - public void testDownloadUrlFromLocalFile() throws Exception { - File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "url-http.file"); - - file = U.downloadUrl( - GridTestUtils.resolveIgnitePath("modules/core/src/test/config/tests.properties").toURI().toURL(), file); - - assert file.exists(); - assert file.delete(); - } - /** * @throws Exception If failed. */ @@ -311,23 +236,10 @@ public void testDownloadUrlFromLocalFile() throws Exception { public void testOs() throws Exception { System.out.println("OS string: " + U.osString()); System.out.println("JDK string: " + U.jdkString()); - System.out.println("OS/JDK string: " + U.osJdkString()); System.out.println("Is Windows: " + U.isWindows()); - System.out.println("Is Windows 95: " + U.isWindows95()); - System.out.println("Is Windows 98: " + U.isWindows98()); - System.out.println("Is Windows NT: " + U.isWindowsNt()); - System.out.println("Is Windows 2000: " + U.isWindows2k()); - System.out.println("Is Windows 2003: " + U.isWindows2003()); - System.out.println("Is Windows XP: " + U.isWindowsXp()); - System.out.println("Is Windows Vista: " + U.isWindowsVista()); System.out.println("Is Linux: " + U.isLinux()); System.out.println("Is Mac OS: " + U.isMacOs()); - System.out.println("Is Netware: " + U.isNetWare()); - System.out.println("Is Solaris: " + U.isSolaris()); - System.out.println("Is Solaris SPARC: " + U.isSolarisSparc()); - System.out.println("Is Solaris x86: " + U.isSolarisX86()); - System.out.println("Is Windows7: " + U.isWindows7()); } /** @@ -538,74 +450,6 @@ public void testsGetBytes() { } } - /** - * - */ - @SuppressWarnings("ZeroLengthArrayAllocation") - @Test - public void testReadByteArray() { - assertTrue(Arrays.equals(new byte[0], U.readByteArray(ByteBuffer.allocate(0)))); - assertTrue(Arrays.equals(new byte[0], U.readByteArray(ByteBuffer.allocate(0), ByteBuffer.allocate(0)))); - - Random rnd = new Random(); - - byte[] bytes = new byte[13]; - - rnd.nextBytes(bytes); - - assertTrue(Arrays.equals(bytes, U.readByteArray(ByteBuffer.wrap(bytes)))); - assertTrue(Arrays.equals(bytes, U.readByteArray(ByteBuffer.wrap(bytes), ByteBuffer.allocate(0)))); - assertTrue(Arrays.equals(bytes, U.readByteArray(ByteBuffer.allocate(0), ByteBuffer.wrap(bytes)))); - - for (int i = 0; i < 1000; i++) { - int n = rnd.nextInt(100); - - bytes = new byte[n]; - - rnd.nextBytes(bytes); - - ByteBuffer[] bufs = new ByteBuffer[1 + rnd.nextInt(10)]; - - int x = 0; - - for (int j = 0; j < bufs.length - 1; j++) { - int size = x == n ? 0 : rnd.nextInt(n - x); - - bufs[j] = (ByteBuffer)ByteBuffer.wrap(bytes).position(x).limit(x += size); - } - - bufs[bufs.length - 1] = (ByteBuffer)ByteBuffer.wrap(bytes).position(x).limit(n); - - assertTrue(Arrays.equals(bytes, U.readByteArray(bufs))); - } - } - - /** - * - */ - @SuppressWarnings("ZeroLengthArrayAllocation") - @Test - public void testHashCodeFromBuffers() { - assertEquals(Arrays.hashCode(new byte[0]), U.hashCode(ByteBuffer.allocate(0))); - assertEquals(Arrays.hashCode(new byte[0]), U.hashCode(ByteBuffer.allocate(0), ByteBuffer.allocate(0))); - - Random rnd = new Random(); - - for (int i = 0; i < 1000; i++) { - ByteBuffer[] bufs = new ByteBuffer[1 + rnd.nextInt(15)]; - - for (int j = 0; j < bufs.length; j++) { - byte[] bytes = new byte[rnd.nextInt(25)]; - - rnd.nextBytes(bytes); - - bufs[j] = ByteBuffer.wrap(bytes); - } - - assertEquals(U.hashCode(bufs), Arrays.hashCode(U.readByteArray(bufs))); - } - } - /** * Test annotation look up. */ @@ -755,14 +599,6 @@ public void testInetAddressesComparator() { assertTrue(ips.get(ips.size() - 1).isUnresolved()); } - /** */ - @Test - public void testMD5Calculation() throws Exception { - String md5 = U.calculateMD5(new ByteArrayInputStream("Corrupted information.".getBytes())); - - assertEquals("d7dbe555be2eee7fa658299850169fa1", md5); - } - /** * @throws Exception If failed. */ @@ -1311,7 +1147,7 @@ public void testDoInParallelException() { * 3)Simple strings.
* * 4)Various combinations of strings with one, two, and three-byte - * characters with size greater than {@link IgniteUtils#UTF_BYTE_LIMIT}.
+ * characters with size greater than 65535.
* * @throws Exception If failed. */ @@ -1332,60 +1168,6 @@ public void testReadWriteBigUTF() throws Exception { } } - /** - * Testing method {@link IgniteUtils#writeCutString} using resource files, - * where each line is needed to test different cases:
- * 1){@code null}.
- * - * 2)Empty line.
- * - * 3)Simple strings.
- * - * 4)String containing single-byte characters of size - * {@link IgniteUtils#UTF_BYTE_LIMIT}.
- * - * 5)String containing single-byte characters of size more than - * {@link IgniteUtils#UTF_BYTE_LIMIT}.
- * - * 6)String containing two-byte characters of size - * {@link IgniteUtils#UTF_BYTE_LIMIT}.
- * - * 7)String containing two-byte characters of size more than - * {@link IgniteUtils#UTF_BYTE_LIMIT}.
- * - * 8)String containing three-byte characters of size - * {@link IgniteUtils#UTF_BYTE_LIMIT}.
- * - * 9)String containing three-byte characters of size more than - * {@link IgniteUtils#UTF_BYTE_LIMIT}.
- * - * @throws Exception If failed. - */ - @Test - public void testWriteLimitUTF() throws Exception { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - readLines("org.apache.ignite.util/limitUtf.txt", readLine -> { - baos.reset(); - - DataOutput dOut = new DataOutputStream(baos); - U.writeCutString(dOut, readLine); - - DataInputStream dIn = new DataInputStream(new ByteArrayInputStream(baos.toByteArray())); - String readUTF = U.readString(dIn); - - if (nonNull(readLine)) { - AtomicInteger utfBytes = new AtomicInteger(); - - readLine = readLine.chars() - .filter(c -> utfBytes.addAndGet(U.utfBytes((char)c)) <= U.UTF_BYTE_LIMIT) - .mapToObj(c -> String.valueOf((char)c)).collect(joining()); - } - - assertEquals(readLine, readUTF); - }); - } - } - /** * Test of {@link U#humanReadableDuration}. */ diff --git a/modules/core/src/test/java/org/apache/ignite/lang/GridSetWrapperSelfTest.java b/modules/core/src/test/java/org/apache/ignite/lang/GridSetWrapperSelfTest.java index d2b3a7325b75e..561d6fcc3cfc6 100644 --- a/modules/core/src/test/java/org/apache/ignite/lang/GridSetWrapperSelfTest.java +++ b/modules/core/src/test/java/org/apache/ignite/lang/GridSetWrapperSelfTest.java @@ -19,12 +19,10 @@ import java.util.Collection; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import org.apache.ignite.internal.util.GridSetWrapper; -import org.apache.ignite.internal.util.IgniteUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.testframework.junits.common.GridCommonTest; import org.junit.Test; @@ -131,7 +129,7 @@ public void testSetRemoveAll() throws Exception { set.add("v4"); set.add("v5"); - set.removeAll(IgniteUtils.addAll(new HashSet(), "v2", "v4", "v5")); + set.removeAll(Set.of("v2", "v4", "v5")); assertEquals(2, set.size()); diff --git a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java index 2bed467111a78..d1f9883ca868b 100644 --- a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java +++ b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java @@ -1202,7 +1202,7 @@ public void testLoopbackProblemFirstNodeOnLoopback() throws Exception { // On Windows and Mac machines two nodes can reside on the same port // (if one node has localHost="127.0.0.1" and another has localHost="0.0.0.0"). // So two nodes do not even discover each other. - if (U.isWindows() || U.isMacOs() || U.isSolaris()) + if (U.isWindows() || U.isMacOs()) return; try { diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java index 6666fca6136da..88293c5a582d9 100644 --- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java +++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2Utils.java @@ -781,7 +781,9 @@ public static void bubbleUp(Z[] arr, int off, Comparator cmp) { if (cmp.compare(arr[i], arr[i + 1]) <= 0) break; - U.swap(arr, i, i + 1); + Z tmp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = tmp; } }