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