1 /* 2 * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 package jdk.test.lib; 25 26 import java.io.File; 27 import java.io.IOException; 28 import java.lang.annotation.Annotation; 29 import java.lang.reflect.Method; 30 import java.net.Inet6Address; 31 import java.net.InetAddress; 32 import java.net.InetSocketAddress; 33 import java.net.MalformedURLException; 34 import java.net.ServerSocket; 35 import java.net.URL; 36 import java.net.URLClassLoader; 37 import java.net.UnknownHostException; 38 import java.nio.file.Files; 39 import java.nio.file.Path; 40 import java.nio.file.Paths; 41 import java.nio.file.attribute.FileAttribute; 42 import java.nio.channels.SocketChannel; 43 import java.util.ArrayList; 44 import java.util.Arrays; 45 import java.util.Collection; 46 import java.util.Collections; 47 import java.util.Iterator; 48 import java.util.Map; 49 import java.util.HashMap; 50 import java.util.LinkedList; 51 import java.util.List; 52 import java.util.Objects; 53 import java.util.Random; 54 import java.util.function.BooleanSupplier; 55 import java.util.concurrent.TimeUnit; 56 import java.util.function.Consumer; 57 import java.util.function.Function; 58 import java.util.regex.Matcher; 59 import java.util.regex.Pattern; 60 61 import static jdk.test.lib.Asserts.assertTrue; 62 import jdk.test.lib.process.ProcessTools; 63 import jdk.test.lib.process.OutputAnalyzer; 64 65 /** 66 * Common library for various test helper functions. 67 */ 68 public final class Utils { 69 70 /** 71 * Returns the value of 'test.class.path' system property. 72 */ 73 public static final String TEST_CLASS_PATH = System.getProperty("test.class.path", "."); 74 75 /** 76 * Returns the sequence used by operating system to separate lines. 77 */ 78 public static final String NEW_LINE = System.getProperty("line.separator"); 79 80 /** 81 * Returns the value of 'test.vm.opts' system property. 82 */ 83 public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim(); 84 85 /** 86 * Returns the value of 'test.java.opts' system property. 87 */ 88 public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim(); 89 90 /** 91 * Returns the value of 'test.src' system property. 92 */ 93 public static final String TEST_SRC = System.getProperty("test.src", "").trim(); 94 95 /** 96 * Returns the value of 'test.root' system property. 97 */ 98 public static final String TEST_ROOT = System.getProperty("test.root", "").trim(); 99 100 /* 101 * Returns the value of 'test.jdk' system property 102 */ 103 public static final String TEST_JDK = System.getProperty("test.jdk"); 104 105 /* 106 * Returns the value of 'compile.jdk' system property 107 */ 108 public static final String COMPILE_JDK = System.getProperty("compile.jdk", TEST_JDK); 109 110 /** 111 * Returns the value of 'test.classes' system property 112 */ 113 public static final String TEST_CLASSES = System.getProperty("test.classes", "."); 114 115 /** 116 * Returns the value of 'test.name' system property 117 */ 118 public static final String TEST_NAME = System.getProperty("test.name", "."); 119 120 /** 121 * Defines property name for seed value. 122 */ 123 public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed"; 124 125 /* (non-javadoc) 126 * Random generator with (or without) predefined seed. Depends on 127 * "jdk.test.lib.random.seed" property value. 128 */ 129 private static volatile Random RANDOM_GENERATOR; 130 131 /** 132 * Maximum number of attempts to get free socket 133 */ 134 private static final int MAX_SOCKET_TRIES = 10; 135 136 /** 137 * Contains the seed value used for {@link java.util.Random} creation. 138 */ 139 public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong()); 140 /** 141 * Returns the value of 'test.timeout.factor' system property 142 * converted to {@code double}. 143 */ 144 public static final double TIMEOUT_FACTOR; 145 static { 146 String toFactor = System.getProperty("test.timeout.factor", "1.0"); 147 TIMEOUT_FACTOR = Double.parseDouble(toFactor); 148 } 149 150 /** 151 * Returns the value of JTREG default test timeout in milliseconds 152 * converted to {@code long}. 153 */ 154 public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120); 155 156 private Utils() { 157 // Private constructor to prevent class instantiation 158 } 159 160 /** 161 * Returns the list of VM options with -J prefix. 162 * 163 * @return The list of VM options with -J prefix 164 */ 165 public static List<String> getForwardVmOptions() { 166 String[] opts = safeSplitString(VM_OPTIONS); 167 for (int i = 0; i < opts.length; i++) { 168 opts[i] = "-J" + opts[i]; 169 } 170 return Arrays.asList(opts); 171 } 172 173 /** 174 * Returns the default JTReg arguments for a jvm running a test. 175 * This is the combination of JTReg arguments test.vm.opts and test.java.opts. 176 * @return An array of options, or an empty array if no options. 177 */ 178 public static String[] getTestJavaOpts() { 179 List<String> opts = new ArrayList<String>(); 180 Collections.addAll(opts, safeSplitString(VM_OPTIONS)); 181 Collections.addAll(opts, safeSplitString(JAVA_OPTIONS)); 182 return opts.toArray(new String[0]); 183 } 184 185 /** 186 * Combines given arguments with default JTReg arguments for a jvm running a test. 187 * This is the combination of JTReg arguments test.vm.opts and test.java.opts 188 * @return The combination of JTReg test java options and user args. 189 */ 190 public static String[] prependTestJavaOpts(String... userArgs) { 191 List<String> opts = new ArrayList<String>(); 192 Collections.addAll(opts, getTestJavaOpts()); 193 Collections.addAll(opts, userArgs); 194 return opts.toArray(new String[0]); 195 } 196 197 /** 198 * Combines given arguments with default JTReg arguments for a jvm running a test. 199 * This is the combination of JTReg arguments test.vm.opts and test.java.opts 200 * @return The combination of JTReg test java options and user args. 201 */ 202 public static String[] appendTestJavaOpts(String... userArgs) { 203 List<String> opts = new ArrayList<String>(); 204 Collections.addAll(opts, userArgs); 205 Collections.addAll(opts, getTestJavaOpts()); 206 return opts.toArray(new String[0]); 207 } 208 209 /** 210 * Combines given arguments with default JTReg arguments for a jvm running a test. 211 * This is the combination of JTReg arguments test.vm.opts and test.java.opts 212 * @return The combination of JTReg test java options and user args. 213 */ 214 public static String[] addTestJavaOpts(String... userArgs) { 215 return prependTestJavaOpts(userArgs); 216 } 217 218 /** 219 * Removes any options specifying which GC to use, for example "-XX:+UseG1GC". 220 * Removes any options matching: -XX:(+/-)Use*GC 221 * Used when a test need to set its own GC version. Then any 222 * GC specified by the framework must first be removed. 223 * @return A copy of given opts with all GC options removed. 224 */ 225 private static final Pattern useGcPattern = Pattern.compile( 226 "(?:\\-XX\\:[\\+\\-]Use.+GC)"); 227 public static List<String> removeGcOpts(List<String> opts) { 228 List<String> optsWithoutGC = new ArrayList<String>(); 229 for (String opt : opts) { 230 if (useGcPattern.matcher(opt).matches()) { 231 System.out.println("removeGcOpts: removed " + opt); 232 } else { 233 optsWithoutGC.add(opt); 234 } 235 } 236 return optsWithoutGC; 237 } 238 239 /** 240 * Returns the default JTReg arguments for a jvm running a test without 241 * options that matches regular expressions in {@code filters}. 242 * This is the combination of JTReg arguments test.vm.opts and test.java.opts. 243 * @param filters Regular expressions used to filter out options. 244 * @return An array of options, or an empty array if no options. 245 */ 246 public static String[] getFilteredTestJavaOpts(String... filters) { 247 String options[] = getTestJavaOpts(); 248 249 if (filters.length == 0) { 250 return options; 251 } 252 253 List<String> filteredOptions = new ArrayList<String>(options.length); 254 Pattern patterns[] = new Pattern[filters.length]; 255 for (int i = 0; i < filters.length; i++) { 256 patterns[i] = Pattern.compile(filters[i]); 257 } 258 259 for (String option : options) { 260 boolean matched = false; 261 for (int i = 0; i < patterns.length && !matched; i++) { 262 Matcher matcher = patterns[i].matcher(option); 263 matched = matcher.find(); 264 } 265 if (!matched) { 266 filteredOptions.add(option); 267 } 268 } 269 270 return filteredOptions.toArray(new String[filteredOptions.size()]); 271 } 272 273 /** 274 * Splits a string by white space. 275 * Works like String.split(), but returns an empty array 276 * if the string is null or empty. 277 */ 278 private static String[] safeSplitString(String s) { 279 if (s == null || s.trim().isEmpty()) { 280 return new String[] {}; 281 } 282 return s.trim().split("\\s+"); 283 } 284 285 /** 286 * @return The full command line for the ProcessBuilder. 287 */ 288 public static String getCommandLine(ProcessBuilder pb) { 289 StringBuilder cmd = new StringBuilder(); 290 for (String s : pb.command()) { 291 cmd.append(s).append(" "); 292 } 293 return cmd.toString(); 294 } 295 296 /** 297 * Returns the socket address of an endpoint that refuses connections. The 298 * endpoint is an InetSocketAddress where the address is the loopback address 299 * and the port is a system port (1-1023 range). 300 * This method is a better choice than getFreePort for tests that need 301 * an endpoint that refuses connections. 302 */ 303 public static InetSocketAddress refusingEndpoint() { 304 InetAddress lb = InetAddress.getLoopbackAddress(); 305 int port = 1; 306 while (port < 1024) { 307 InetSocketAddress sa = new InetSocketAddress(lb, port); 308 try { 309 SocketChannel.open(sa).close(); 310 } catch (IOException ioe) { 311 return sa; 312 } 313 port++; 314 } 315 throw new RuntimeException("Unable to find system port that is refusing connections"); 316 } 317 318 /** 319 * Returns local addresses with symbolic and numeric scopes 320 */ 321 public static List<InetAddress> getAddressesWithSymbolicAndNumericScopes() { 322 List<InetAddress> result = new LinkedList<>(); 323 try { 324 NetworkConfiguration conf = NetworkConfiguration.probe(); 325 conf.ip4Addresses().forEach(result::add); 326 // Java reports link local addresses with symbolic scope, 327 // but on Windows java.net.NetworkInterface generates its own scope names 328 // which are incompatible with native Windows routines. 329 // So on Windows test only addresses with numeric scope. 330 // On other platforms test both symbolic and numeric scopes. 331 conf.ip6Addresses().forEach(addr6 -> { 332 try { 333 result.add(Inet6Address.getByAddress(null, addr6.getAddress(), addr6.getScopeId())); 334 } catch (UnknownHostException e) { 335 // cannot happen! 336 throw new RuntimeException("Unexpected", e); 337 } 338 if (!Platform.isWindows()) { 339 result.add(addr6); 340 } 341 }); 342 } catch (IOException e) { 343 // cannot happen! 344 throw new RuntimeException("Unexpected", e); 345 } 346 return result; 347 } 348 349 /** 350 * Returns the free port on the local host. 351 * 352 * @return The port number 353 * @throws IOException if an I/O error occurs when opening the socket 354 */ 355 public static int getFreePort() throws IOException { 356 try (ServerSocket serverSocket = 357 new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) { 358 return serverSocket.getLocalPort(); 359 } 360 } 361 362 /** 363 * Returns the free unreserved port on the local host. 364 * 365 * @param reservedPorts reserved ports 366 * @return The port number or -1 if failed to find a free port 367 */ 368 public static int findUnreservedFreePort(int... reservedPorts) { 369 int numTries = 0; 370 while (numTries++ < MAX_SOCKET_TRIES) { 371 int port = -1; 372 try { 373 port = getFreePort(); 374 } catch (IOException e) { 375 e.printStackTrace(); 376 } 377 if (port > 0 && !isReserved(port, reservedPorts)) { 378 return port; 379 } 380 } 381 return -1; 382 } 383 384 private static boolean isReserved(int port, int[] reservedPorts) { 385 for (int p : reservedPorts) { 386 if (p == port) { 387 return true; 388 } 389 } 390 return false; 391 } 392 393 /** 394 * Returns the name of the local host. 395 * 396 * @return The host name 397 * @throws UnknownHostException if IP address of a host could not be determined 398 */ 399 public static String getHostname() throws UnknownHostException { 400 InetAddress inetAddress = InetAddress.getLocalHost(); 401 String hostName = inetAddress.getHostName(); 402 403 assertTrue((hostName != null && !hostName.isEmpty()), 404 "Cannot get hostname"); 405 406 return hostName; 407 } 408 409 /** 410 * Uses "jcmd -l" to search for a jvm pid. This function will wait 411 * forever (until jtreg timeout) for the pid to be found. 412 * @param key Regular expression to search for 413 * @return The found pid. 414 */ 415 public static int waitForJvmPid(String key) throws Throwable { 416 final long iterationSleepMillis = 250; 417 System.out.println("waitForJvmPid: Waiting for key '" + key + "'"); 418 System.out.flush(); 419 while (true) { 420 int pid = tryFindJvmPid(key); 421 if (pid >= 0) { 422 return pid; 423 } 424 Thread.sleep(iterationSleepMillis); 425 } 426 } 427 428 /** 429 * Searches for a jvm pid in the output from "jcmd -l". 430 * 431 * Example output from jcmd is: 432 * 12498 sun.tools.jcmd.JCmd -l 433 * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar 434 * 435 * @param key A regular expression to search for. 436 * @return The found pid, or -1 if not found. 437 * @throws Exception If multiple matching jvms are found. 438 */ 439 public static int tryFindJvmPid(String key) throws Throwable { 440 OutputAnalyzer output = null; 441 try { 442 JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd"); 443 jcmdLauncher.addToolArg("-l"); 444 output = ProcessTools.executeProcess(jcmdLauncher.getCommand()); 445 output.shouldHaveExitValue(0); 446 447 // Search for a line starting with numbers (pid), follwed by the key. 448 Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n"); 449 Matcher matcher = pattern.matcher(output.getStdout()); 450 451 int pid = -1; 452 if (matcher.find()) { 453 pid = Integer.parseInt(matcher.group(1)); 454 System.out.println("findJvmPid.pid: " + pid); 455 if (matcher.find()) { 456 throw new Exception("Found multiple JVM pids for key: " + key); 457 } 458 } 459 return pid; 460 } catch (Throwable t) { 461 System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t)); 462 throw t; 463 } 464 } 465 466 /** 467 * Adjusts the provided timeout value for the TIMEOUT_FACTOR 468 * @param tOut the timeout value to be adjusted 469 * @return The timeout value adjusted for the value of "test.timeout.factor" 470 * system property 471 */ 472 public static long adjustTimeout(long tOut) { 473 return Math.round(tOut * Utils.TIMEOUT_FACTOR); 474 } 475 476 /** 477 * Return the contents of the named file as a single String, 478 * or null if not found. 479 * @param filename name of the file to read 480 * @return String contents of file, or null if file not found. 481 * @throws IOException 482 * if an I/O error occurs reading from the file or a malformed or 483 * unmappable byte sequence is read 484 */ 485 public static String fileAsString(String filename) throws IOException { 486 Path filePath = Paths.get(filename); 487 if (!Files.exists(filePath)) return null; 488 return new String(Files.readAllBytes(filePath)); 489 } 490 491 private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; 492 493 /** 494 * Returns hex view of byte array 495 * 496 * @param bytes byte array to process 497 * @return space separated hexadecimal string representation of bytes 498 */ 499 public static String toHexString(byte[] bytes) { 500 char[] hexView = new char[bytes.length * 3 - 1]; 501 for (int i = 0; i < bytes.length - 1; i++) { 502 hexView[i * 3] = hexArray[(bytes[i] >> 4) & 0x0F]; 503 hexView[i * 3 + 1] = hexArray[bytes[i] & 0x0F]; 504 hexView[i * 3 + 2] = ' '; 505 } 506 hexView[hexView.length - 2] = hexArray[(bytes[bytes.length - 1] >> 4) & 0x0F]; 507 hexView[hexView.length - 1] = hexArray[bytes[bytes.length - 1] & 0x0F]; 508 return new String(hexView); 509 } 510 511 /** 512 * Returns byte array of hex view 513 * 514 * @param hex hexadecimal string representation 515 * @return byte array 516 */ 517 public static byte[] toByteArray(String hex) { 518 int length = hex.length(); 519 byte[] bytes = new byte[length / 2]; 520 for (int i = 0; i < length; i += 2) { 521 bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) 522 + Character.digit(hex.charAt(i + 1), 16)); 523 } 524 return bytes; 525 } 526 527 /** 528 * Returns {@link java.util.Random} generator initialized with particular seed. 529 * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME} 530 * In case no seed is provided, the method uses a random number. 531 * The used seed printed to stdout. 532 * @return {@link java.util.Random} generator with particular seed. 533 */ 534 public static Random getRandomInstance() { 535 if (RANDOM_GENERATOR == null) { 536 synchronized (Utils.class) { 537 if (RANDOM_GENERATOR == null) { 538 RANDOM_GENERATOR = new Random(SEED); 539 System.out.printf("For random generator using seed: %d%n", SEED); 540 System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED); 541 } 542 } 543 } 544 return RANDOM_GENERATOR; 545 } 546 547 /** 548 * Returns random element of non empty collection 549 * 550 * @param <T> a type of collection element 551 * @param collection collection of elements 552 * @return random element of collection 553 * @throws IllegalArgumentException if collection is empty 554 */ 555 public static <T> T getRandomElement(Collection<T> collection) 556 throws IllegalArgumentException { 557 if (collection.isEmpty()) { 558 throw new IllegalArgumentException("Empty collection"); 559 } 560 Random random = getRandomInstance(); 561 int elementIndex = 1 + random.nextInt(collection.size() - 1); 562 Iterator<T> iterator = collection.iterator(); 563 while (--elementIndex != 0) { 564 iterator.next(); 565 } 566 return iterator.next(); 567 } 568 569 /** 570 * Returns random element of non empty array 571 * 572 * @param <T> a type of array element 573 * @param array array of elements 574 * @return random element of array 575 * @throws IllegalArgumentException if array is empty 576 */ 577 public static <T> T getRandomElement(T[] array) 578 throws IllegalArgumentException { 579 if (array == null || array.length == 0) { 580 throw new IllegalArgumentException("Empty or null array"); 581 } 582 Random random = getRandomInstance(); 583 return array[random.nextInt(array.length)]; 584 } 585 586 /** 587 * Wait for condition to be true 588 * 589 * @param condition, a condition to wait for 590 */ 591 public static final void waitForCondition(BooleanSupplier condition) { 592 waitForCondition(condition, -1L, 100L); 593 } 594 595 /** 596 * Wait until timeout for condition to be true 597 * 598 * @param condition, a condition to wait for 599 * @param timeout a time in milliseconds to wait for condition to be true 600 * specifying -1 will wait forever 601 * @return condition value, to determine if wait was successful 602 */ 603 public static final boolean waitForCondition(BooleanSupplier condition, 604 long timeout) { 605 return waitForCondition(condition, timeout, 100L); 606 } 607 608 /** 609 * Wait until timeout for condition to be true for specified time 610 * 611 * @param condition, a condition to wait for 612 * @param timeout a time in milliseconds to wait for condition to be true, 613 * specifying -1 will wait forever 614 * @param sleepTime a time to sleep value in milliseconds 615 * @return condition value, to determine if wait was successful 616 */ 617 public static final boolean waitForCondition(BooleanSupplier condition, 618 long timeout, long sleepTime) { 619 long startTime = System.currentTimeMillis(); 620 while (!(condition.getAsBoolean() || (timeout != -1L 621 && ((System.currentTimeMillis() - startTime) > timeout)))) { 622 try { 623 Thread.sleep(sleepTime); 624 } catch (InterruptedException e) { 625 Thread.currentThread().interrupt(); 626 throw new Error(e); 627 } 628 } 629 return condition.getAsBoolean(); 630 } 631 632 /** 633 * Interface same as java.lang.Runnable but with 634 * method {@code run()} able to throw any Throwable. 635 */ 636 public static interface ThrowingRunnable { 637 void run() throws Throwable; 638 } 639 640 /** 641 * Filters out an exception that may be thrown by the given 642 * test according to the given filter. 643 * 644 * @param test - method that is invoked and checked for exception. 645 * @param filter - function that checks if the thrown exception matches 646 * criteria given in the filter's implementation. 647 * @return - exception that matches the filter if it has been thrown or 648 * {@code null} otherwise. 649 * @throws Throwable - if test has thrown an exception that does not 650 * match the filter. 651 */ 652 public static Throwable filterException(ThrowingRunnable test, 653 Function<Throwable, Boolean> filter) throws Throwable { 654 try { 655 test.run(); 656 } catch (Throwable t) { 657 if (filter.apply(t)) { 658 return t; 659 } else { 660 throw t; 661 } 662 } 663 return null; 664 } 665 666 /** 667 * Ensures a requested class is loaded 668 * @param aClass class to load 669 */ 670 public static void ensureClassIsLoaded(Class<?> aClass) { 671 if (aClass == null) { 672 throw new Error("Requested null class"); 673 } 674 try { 675 Class.forName(aClass.getName(), /* initialize = */ true, 676 ClassLoader.getSystemClassLoader()); 677 } catch (ClassNotFoundException e) { 678 throw new Error("Class not found", e); 679 } 680 } 681 /** 682 * @param parent a class loader to be the parent for the returned one 683 * @return an UrlClassLoader with urls made of the 'test.class.path' jtreg 684 * property and with the given parent 685 */ 686 public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) { 687 URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator)) 688 .map(Paths::get) 689 .map(Path::toUri) 690 .map(x -> { 691 try { 692 return x.toURL(); 693 } catch (MalformedURLException ex) { 694 throw new Error("Test issue. JTREG property" 695 + " 'test.class.path'" 696 + " is not defined correctly", ex); 697 } 698 }).toArray(URL[]::new); 699 return new URLClassLoader(urls, parent); 700 } 701 702 /** 703 * Runs runnable and checks that it throws expected exception. If exceptionException is null it means 704 * that we expect no exception to be thrown. 705 * @param runnable what we run 706 * @param expectedException expected exception 707 */ 708 public static void runAndCheckException(ThrowingRunnable runnable, Class<? extends Throwable> expectedException) { 709 runAndCheckException(runnable, t -> { 710 if (t == null) { 711 if (expectedException != null) { 712 throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName()); 713 } 714 } else { 715 String message = "Got unexpected exception " + t.getClass().getSimpleName(); 716 if (expectedException == null) { 717 throw new AssertionError(message, t); 718 } else if (!expectedException.isAssignableFrom(t.getClass())) { 719 message += " instead of " + expectedException.getSimpleName(); 720 throw new AssertionError(message, t); 721 } 722 } 723 }); 724 } 725 726 /** 727 * Runs runnable and makes some checks to ensure that it throws expected exception. 728 * @param runnable what we run 729 * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise 730 */ 731 public static void runAndCheckException(ThrowingRunnable runnable, Consumer<Throwable> checkException) { 732 Throwable throwable = null; 733 try { 734 runnable.run(); 735 } catch (Throwable t) { 736 throwable = t; 737 } 738 checkException.accept(throwable); 739 } 740 741 /** 742 * Converts to VM type signature 743 * 744 * @param type Java type to convert 745 * @return string representation of VM type 746 */ 747 public static String toJVMTypeSignature(Class<?> type) { 748 if (type.isPrimitive()) { 749 if (type == boolean.class) { 750 return "Z"; 751 } else if (type == byte.class) { 752 return "B"; 753 } else if (type == char.class) { 754 return "C"; 755 } else if (type == double.class) { 756 return "D"; 757 } else if (type == float.class) { 758 return "F"; 759 } else if (type == int.class) { 760 return "I"; 761 } else if (type == long.class) { 762 return "J"; 763 } else if (type == short.class) { 764 return "S"; 765 } else if (type == void.class) { 766 return "V"; 767 } else { 768 throw new Error("Unsupported type: " + type); 769 } 770 } 771 String result = type.getName().replaceAll("\\.", "/"); 772 if (!type.isArray()) { 773 return "L" + result + ";"; 774 } 775 return result; 776 } 777 778 public static Object[] getNullValues(Class<?>... types) { 779 Object[] result = new Object[types.length]; 780 int i = 0; 781 for (Class<?> type : types) { 782 result[i++] = NULL_VALUES.get(type); 783 } 784 return result; 785 } 786 private static Map<Class<?>, Object> NULL_VALUES = new HashMap<>(); 787 static { 788 NULL_VALUES.put(boolean.class, false); 789 NULL_VALUES.put(byte.class, (byte) 0); 790 NULL_VALUES.put(short.class, (short) 0); 791 NULL_VALUES.put(char.class, '\0'); 792 NULL_VALUES.put(int.class, 0); 793 NULL_VALUES.put(long.class, 0L); 794 NULL_VALUES.put(float.class, 0.0f); 795 NULL_VALUES.put(double.class, 0.0d); 796 } 797 798 /** 799 * Returns mandatory property value 800 * @param propName is a name of property to request 801 * @return a String with requested property value 802 */ 803 public static String getMandatoryProperty(String propName) { 804 Objects.requireNonNull(propName, "Requested null property"); 805 String prop = System.getProperty(propName); 806 Objects.requireNonNull(prop, 807 String.format("A mandatory property '%s' isn't set", propName)); 808 return prop; 809 } 810 811 /* 812 * Run uname with specified arguments. 813 */ 814 public static OutputAnalyzer uname(String... args) throws Throwable { 815 String[] cmds = new String[args.length + 1]; 816 cmds[0] = "uname"; 817 System.arraycopy(args, 0, cmds, 1, args.length); 818 return ProcessTools.executeCommand(cmds); 819 } 820 821 /* 822 * Returns the system distro. 823 */ 824 public static String distro() { 825 try { 826 return uname("-v").asLines().get(0); 827 } catch (Throwable t) { 828 throw new RuntimeException("Failed to determine distro.", t); 829 } 830 } 831 832 /** 833 * Creates an empty file in "user.dir" if the property set. 834 * <p> 835 * This method is meant as a replacement for {@code Files#createTempFile(String, String, FileAttribute...)} 836 * that doesn't leave files behind in /tmp directory of the test machine 837 * <p> 838 * If the property "user.dir" is not set, "." will be used. 839 * 840 * @param prefix 841 * @param suffix 842 * @param attrs 843 * @return the path to the newly created file that did not exist before this 844 * method was invoked 845 * @throws IOException 846 * 847 * @see {@link Files#createTempFile(String, String, FileAttribute...)} 848 */ 849 public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException { 850 Path dir = Paths.get(System.getProperty("user.dir", ".")); 851 return Files.createTempFile(dir, prefix, suffix); 852 } 853 854 /** 855 * Creates an empty directory in "user.dir" or "." 856 * <p> 857 * This method is meant as a replacement for {@code Files#createTempDirectory(String, String, FileAttribute...)} 858 * that doesn't leave files behind in /tmp directory of the test machine 859 * <p> 860 * If the property "user.dir" is not set, "." will be used. 861 * 862 * @param prefix 863 * @param attrs 864 * @return the path to the newly created directory 865 * @throws IOException 866 * 867 * @see {@link Files#createTempDirectory(String, String, FileAttribute...)} 868 */ 869 public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException { 870 Path dir = Paths.get(System.getProperty("user.dir", ".")); 871 return Files.createTempDirectory(dir, prefix); 872 } 873 }