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