1 /*
   2  * Copyright (c) 2013, 2018, 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.testlibrary;
  25 
  26 import static jdk.testlibrary.Asserts.assertTrue;
  27 
  28 import java.io.IOException;
  29 import java.net.InetAddress;
  30 import java.net.ServerSocket;
  31 import java.net.UnknownHostException;
  32 import java.util.ArrayList;
  33 import java.util.List;
  34 import java.util.Arrays;
  35 import java.util.Collections;
  36 import java.util.regex.Pattern;
  37 import java.util.regex.Matcher;
  38 import java.util.concurrent.TimeUnit;
  39 import java.util.function.BooleanSupplier;
  40 import java.util.function.Function;
  41 
  42 /**
  43  * Common library for various test helper functions.
  44  *
  45  * @deprecated This class is deprecated. Use the one from
  46  *             {@code <root>/test/lib/jdk/test/lib}
  47  */
  48 @Deprecated
  49 public final class Utils {
  50 
  51     /**
  52      * Returns the sequence used by operating system to separate lines.
  53      */
  54     public static final String NEW_LINE = System.getProperty("line.separator");
  55 
  56     /**
  57      * Returns the value of 'test.vm.opts'system property.
  58      */
  59     public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
  60 
  61     /**
  62      * Returns the value of 'test.java.opts'system property.
  63      */
  64     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
  65 
  66     /**
  67     * Returns the value of 'test.timeout.factor' system property
  68     * converted to {@code double}.
  69     */
  70     public static final double TIMEOUT_FACTOR;
  71     static {
  72         String toFactor = System.getProperty("test.timeout.factor", "1.0");
  73         TIMEOUT_FACTOR = Double.parseDouble(toFactor);
  74     }
  75 
  76     /**
  77     * Returns the value of JTREG default test timeout in milliseconds
  78     * converted to {@code long}.
  79     */
  80     public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120);
  81 
  82     private Utils() {
  83         // Private constructor to prevent class instantiation
  84     }
  85 
  86     /**
  87      * Returns the list of VM options.
  88      *
  89      * @return List of VM options
  90      */
  91     public static List<String> getVmOptions() {
  92         return Arrays.asList(safeSplitString(VM_OPTIONS));
  93     }
  94 
  95     /**
  96      * Returns the list of VM options with -J prefix.
  97      *
  98      * @return The list of VM options with -J prefix
  99      */
 100     public static List<String> getForwardVmOptions() {
 101         String[] opts = safeSplitString(VM_OPTIONS);
 102         for (int i = 0; i < opts.length; i++) {
 103             opts[i] = "-J" + opts[i];
 104         }
 105         return Arrays.asList(opts);
 106     }
 107 
 108     /**
 109      * Returns the default JTReg arguments for a jvm running a test.
 110      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 111      * @return An array of options, or an empty array if no opptions.
 112      */
 113     public static String[] getTestJavaOpts() {
 114         List<String> opts = new ArrayList<String>();
 115         Collections.addAll(opts, safeSplitString(VM_OPTIONS));
 116         Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
 117         return opts.toArray(new String[0]);
 118     }
 119 
 120     /**
 121      * Combines given arguments with default JTReg arguments for a jvm running a test.
 122      * This is the combination of JTReg arguments test.vm.opts and test.java.opts
 123      * @return The combination of JTReg test java options and user args.
 124      */
 125     public static String[] addTestJavaOpts(String... userArgs) {
 126         List<String> opts = new ArrayList<String>();
 127         Collections.addAll(opts, getTestJavaOpts());
 128         Collections.addAll(opts, userArgs);
 129         return opts.toArray(new String[0]);
 130     }
 131 
 132     /**
 133      * Removes any options specifying which GC to use, for example "-XX:+UseG1GC".
 134      * Removes any options matching: -XX:(+/-)Use*GC
 135      * Used when a test need to set its own GC version. Then any
 136      * GC specified by the framework must first be removed.
 137      * @return A copy of given opts with all GC options removed.
 138      */
 139     private static final Pattern useGcPattern = Pattern.compile(
 140             "(?:\\-XX\\:[\\+\\-]Use.+GC)"
 141             + "|(?:\\-Xconcgc)");
 142     public static List<String> removeGcOpts(List<String> opts) {
 143         List<String> optsWithoutGC = new ArrayList<String>();
 144         for (String opt : opts) {
 145             if (useGcPattern.matcher(opt).matches()) {
 146                 System.out.println("removeGcOpts: removed " + opt);
 147             } else {
 148                 optsWithoutGC.add(opt);
 149             }
 150         }
 151         return optsWithoutGC;
 152     }
 153 
 154     /**
 155      * Splits a string by white space.
 156      * Works like String.split(), but returns an empty array
 157      * if the string is null or empty.
 158      */
 159     private static String[] safeSplitString(String s) {
 160         if (s == null || s.trim().isEmpty()) {
 161             return new String[] {};
 162         }
 163         return s.trim().split("\\s+");
 164     }
 165 
 166     /**
 167      * @return The full command line for the ProcessBuilder.
 168      */
 169     public static String getCommandLine(ProcessBuilder pb) {
 170         StringBuilder cmd = new StringBuilder();
 171         for (String s : pb.command()) {
 172             cmd.append(s).append(" ");
 173         }
 174         return cmd.toString();
 175     }
 176 
 177     /**
 178      * Returns the free port on the local host.
 179      *
 180      * @return The port number
 181      * @throws IOException if an I/O error occurs when opening the socket
 182      */
 183     public static int getFreePort() throws IOException {
 184         try (ServerSocket serverSocket =
 185                 new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) {
 186             return serverSocket.getLocalPort();
 187         }
 188     }
 189 
 190     /**
 191      * Returns the name of the local host.
 192      *
 193      * @return The host name
 194      * @throws UnknownHostException if IP address of a host could not be determined
 195      */
 196     public static String getHostname() throws UnknownHostException {
 197         InetAddress inetAddress = InetAddress.getLocalHost();
 198         String hostName = inetAddress.getHostName();
 199 
 200         assertTrue((hostName != null && !hostName.isEmpty()),
 201                 "Cannot get hostname");
 202 
 203         return hostName;
 204     }
 205 
 206     /**
 207      * Adjusts the provided timeout value for the TIMEOUT_FACTOR
 208      * @param tOut the timeout value to be adjusted
 209      * @return The timeout value adjusted for the value of "test.timeout.factor"
 210      *         system property
 211      */
 212     public static long adjustTimeout(long tOut) {
 213         return Math.round(tOut * Utils.TIMEOUT_FACTOR);
 214     }
 215 
 216     /**
 217      * Wait for condition to be true
 218      *
 219      * @param condition, a condition to wait for
 220      */
 221     public static final void waitForCondition(BooleanSupplier condition) {
 222         waitForCondition(condition, -1L, 100L);
 223     }
 224 
 225     /**
 226      * Wait until timeout for condition to be true
 227      *
 228      * @param condition, a condition to wait for
 229      * @param timeout a time in milliseconds to wait for condition to be true
 230      * specifying -1 will wait forever
 231      * @return condition value, to determine if wait was successfull
 232      */
 233     public static final boolean waitForCondition(BooleanSupplier condition,
 234             long timeout) {
 235         return waitForCondition(condition, timeout, 100L);
 236     }
 237 
 238     /**
 239      * Wait until timeout for condition to be true for specified time
 240      *
 241      * @param condition, a condition to wait for
 242      * @param timeout a time in milliseconds to wait for condition to be true,
 243      * specifying -1 will wait forever
 244      * @param sleepTime a time to sleep value in milliseconds
 245      * @return condition value, to determine if wait was successfull
 246      */
 247     public static final boolean waitForCondition(BooleanSupplier condition,
 248             long timeout, long sleepTime) {
 249         long startTime = System.currentTimeMillis();
 250         while (!(condition.getAsBoolean() || (timeout != -1L
 251                 && ((System.currentTimeMillis() - startTime) > timeout)))) {
 252             try {
 253                 Thread.sleep(sleepTime);
 254             } catch (InterruptedException e) {
 255                 Thread.currentThread().interrupt();
 256                 throw new Error(e);
 257             }
 258         }
 259         return condition.getAsBoolean();
 260     }
 261 
 262     /**
 263      * Interface same as java.lang.Runnable but with
 264      * method {@code run()} able to throw any Throwable.
 265      */
 266     public static interface ThrowingRunnable {
 267         void run() throws Throwable;
 268     }
 269 
 270     /**
 271      * Filters out an exception that may be thrown by the given
 272      * test according to the given filter.
 273      *
 274      * @param test - method that is invoked and checked for exception.
 275      * @param filter - function that checks if the thrown exception matches
 276      *                 criteria given in the filter's implementation.
 277      * @return - exception that matches the filter if it has been thrown or
 278      *           {@code null} otherwise.
 279      * @throws Throwable - if test has thrown an exception that does not
 280      *                     match the filter.
 281      */
 282     public static Throwable filterException(ThrowingRunnable test,
 283             Function<Throwable, Boolean> filter) throws Throwable {
 284         try {
 285             test.run();
 286         } catch (Throwable t) {
 287             if (filter.apply(t)) {
 288                 return t;
 289             } else {
 290                 throw t;
 291             }
 292         }
 293         return null;
 294     }
 295 }