1 /*
   2  * Copyright (c) 2013, 2014, 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 com.oracle.java.testlibrary;
  25 
  26 import static com.oracle.java.testlibrary.Asserts.assertTrue;
  27 import java.io.BufferedReader;
  28 import java.io.File;
  29 import java.io.FileReader;
  30 import java.io.IOException;
  31 import java.lang.reflect.Field;
  32 import java.net.InetAddress;
  33 import java.net.ServerSocket;
  34 import java.net.UnknownHostException;
  35 import java.util.ArrayList;
  36 import java.util.Arrays;
  37 import java.util.Collections;
  38 import java.util.List;
  39 import java.util.Random;
  40 import java.util.regex.Matcher;
  41 import java.util.regex.Pattern;
  42 import sun.misc.Unsafe;
  43 
  44 /**
  45  * Common library for various test helper functions.
  46  */
  47 public final class Utils {
  48 
  49     /**
  50      * Returns the sequence used by operating system to separate lines.
  51      */
  52     public static final String NEW_LINE = System.getProperty("line.separator");
  53 
  54     /**
  55      * Returns the value of 'test.vm.opts'system property.
  56      */
  57     public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
  58 
  59     /**
  60      * Returns the value of 'test.java.opts'system property.
  61      */
  62     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
  63 
  64     private static Unsafe unsafe = null;
  65 
  66     /**
  67      * Defines property name for seed value.
  68      */
  69     public static final String SEED_PROPERTY_NAME = "com.oracle.java.testlibrary.random.seed";
  70 
  71     /* (non-javadoc)
  72      * Random generator with (or without) predefined seed. Depends on
  73      * "com.oracle.java.testlibrary.random.seed" property value.
  74      */
  75     private static volatile Random RANDOM_GENERATOR;
  76 
  77     /**
  78      * Contains the seed value used for {@link java.util.Random} creation.
  79      */
  80     public static final long SEED = Long.getLong(SEED_PROPERTY_NAME, new Random().nextLong());
  81     /**
  82     * Returns the value of 'test.timeout.factor' system property
  83     * converted to {@code double}.
  84     */
  85     public static final double TIMEOUT_FACTOR;
  86     static {
  87         String toFactor = System.getProperty("test.timeout.factor", "1.0");
  88         TIMEOUT_FACTOR = Double.parseDouble(toFactor);
  89     }
  90 
  91     private Utils() {
  92         // Private constructor to prevent class instantiation
  93     }
  94 
  95     /**
  96      * Returns the list of VM options.
  97      *
  98      * @return List of VM options
  99      */
 100     public static List<String> getVmOptions() {
 101         return Arrays.asList(safeSplitString(VM_OPTIONS));
 102     }
 103 
 104     /**
 105      * Returns the list of VM options with -J prefix.
 106      *
 107      * @return The list of VM options with -J prefix
 108      */
 109     public static List<String> getForwardVmOptions() {
 110         String[] opts = safeSplitString(VM_OPTIONS);
 111         for (int i = 0; i < opts.length; i++) {
 112             opts[i] = "-J" + opts[i];
 113         }
 114         return Arrays.asList(opts);
 115     }
 116 
 117     /**
 118      * Returns the default JTReg arguments for a jvm running a test.
 119      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 120      * @return An array of options, or an empty array if no opptions.
 121      */
 122     public static String[] getTestJavaOpts() {
 123         List<String> opts = new ArrayList<String>();
 124         Collections.addAll(opts, safeSplitString(VM_OPTIONS));
 125         Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
 126         return opts.toArray(new String[0]);
 127     }
 128 
 129     /**
 130      * Returns the default JTReg arguments for a jvm running a test without
 131      * options that matches regular expressions in {@code filters}.
 132      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 133      * @param filters Regular expressions used to filter out options.
 134      * @return An array of options, or an empty array if no options.
 135      */
 136     public static String[] getFilteredTestJavaOpts(String... filters) {
 137         String options[] = getTestJavaOpts();
 138 
 139         if (filters.length == 0) {
 140             return options;
 141         }
 142 
 143         List<String> filteredOptions = new ArrayList<String>(options.length);
 144         Pattern patterns[] = new Pattern[filters.length];
 145         for (int i = 0; i < filters.length; i++) {
 146             patterns[i] = Pattern.compile(filters[i]);
 147         }
 148 
 149         for (String option : options) {
 150             boolean matched = false;
 151             for (int i = 0; i < patterns.length && !matched; i++) {
 152                 Matcher matcher = patterns[i].matcher(option);
 153                 matched = matcher.find();
 154             }
 155             if (!matched) {
 156                 filteredOptions.add(option);
 157             }
 158         }
 159 
 160         return filteredOptions.toArray(new String[filteredOptions.size()]);
 161     }
 162 
 163     /**
 164      * Combines given arguments with default JTReg arguments for a jvm running a test.
 165      * This is the combination of JTReg arguments test.vm.opts and test.java.opts
 166      * @return The combination of JTReg test java options and user args.
 167      */
 168     public static String[] addTestJavaOpts(String... userArgs) {
 169         List<String> opts = new ArrayList<String>();
 170         Collections.addAll(opts, getTestJavaOpts());
 171         Collections.addAll(opts, userArgs);
 172         return opts.toArray(new String[0]);
 173     }
 174 
 175     /**
 176      * Splits a string by white space.
 177      * Works like String.split(), but returns an empty array
 178      * if the string is null or empty.
 179      */
 180     private static String[] safeSplitString(String s) {
 181         if (s == null || s.trim().isEmpty()) {
 182             return new String[] {};
 183         }
 184         return s.trim().split("\\s+");
 185     }
 186 
 187     /**
 188      * @return The full command line for the ProcessBuilder.
 189      */
 190     public static String getCommandLine(ProcessBuilder pb) {
 191         StringBuilder cmd = new StringBuilder();
 192         for (String s : pb.command()) {
 193             cmd.append(s).append(" ");
 194         }
 195         return cmd.toString();
 196     }
 197 
 198     /**
 199      * Returns the free port on the local host.
 200      * The function will spin until a valid port number is found.
 201      *
 202      * @return The port number
 203      * @throws InterruptedException if any thread has interrupted the current thread
 204      * @throws IOException if an I/O error occurs when opening the socket
 205      */
 206     public static int getFreePort() throws InterruptedException, IOException {
 207         int port = -1;
 208 
 209         while (port <= 0) {
 210             Thread.sleep(100);
 211 
 212             ServerSocket serverSocket = null;
 213             try {
 214                 serverSocket = new ServerSocket(0);
 215                 port = serverSocket.getLocalPort();
 216             } finally {
 217                 serverSocket.close();
 218             }
 219         }
 220 
 221         return port;
 222     }
 223 
 224     /**
 225      * Returns the name of the local host.
 226      *
 227      * @return The host name
 228      * @throws UnknownHostException if IP address of a host could not be determined
 229      */
 230     public static String getHostname() throws UnknownHostException {
 231         InetAddress inetAddress = InetAddress.getLocalHost();
 232         String hostName = inetAddress.getHostName();
 233 
 234         assertTrue((hostName != null && !hostName.isEmpty()),
 235                 "Cannot get hostname");
 236 
 237         return hostName;
 238     }
 239 
 240     /**
 241      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 242      * forever (until jtreg timeout) for the pid to be found.
 243      * @param key Regular expression to search for
 244      * @return The found pid.
 245      */
 246     public static int waitForJvmPid(String key) throws Throwable {
 247         final long iterationSleepMillis = 250;
 248         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 249         System.out.flush();
 250         while (true) {
 251             int pid = tryFindJvmPid(key);
 252             if (pid >= 0) {
 253                 return pid;
 254             }
 255             Thread.sleep(iterationSleepMillis);
 256         }
 257     }
 258 
 259     /**
 260      * Searches for a jvm pid in the output from "jcmd -l".
 261      *
 262      * Example output from jcmd is:
 263      * 12498 sun.tools.jcmd.JCmd -l
 264      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 265      *
 266      * @param key A regular expression to search for.
 267      * @return The found pid, or -1 if Enot found.
 268      * @throws Exception If multiple matching jvms are found.
 269      */
 270     public static int tryFindJvmPid(String key) throws Throwable {
 271         OutputAnalyzer output = null;
 272         try {
 273             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 274             jcmdLauncher.addToolArg("-l");
 275             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 276             output.shouldHaveExitValue(0);
 277 
 278             // Search for a line starting with numbers (pid), follwed by the key.
 279             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 280             Matcher matcher = pattern.matcher(output.getStdout());
 281 
 282             int pid = -1;
 283             if (matcher.find()) {
 284                 pid = Integer.parseInt(matcher.group(1));
 285                 System.out.println("findJvmPid.pid: " + pid);
 286                 if (matcher.find()) {
 287                     throw new Exception("Found multiple JVM pids for key: " + key);
 288                 }
 289             }
 290             return pid;
 291         } catch (Throwable t) {
 292             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 293             throw t;
 294         }
 295     }
 296 
 297     /**
 298      * Returns file content as a list of strings
 299      *
 300      * @param file File to operate on
 301      * @return List of strings
 302      * @throws IOException
 303      */
 304     public static List<String> fileAsList(File file) throws IOException {
 305         assertTrue(file.exists() && file.isFile(),
 306                 file.getAbsolutePath() + " does not exist or not a file");
 307         List<String> output = new ArrayList<>();
 308         try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
 309             while (reader.ready()) {
 310                 output.add(reader.readLine().replace(NEW_LINE, ""));
 311             }
 312         }
 313         return output;
 314     }
 315 
 316     /**
 317      * Return the contents of the named file as a single String,
 318      * or null if not found.
 319      * @param filename name of the file to read
 320      * @return String contents of file, or null if file not found.
 321      */
 322     public static String fileAsString(String filename) {
 323         StringBuilder result = new StringBuilder();
 324         try {
 325             File file = new File(filename);
 326             if (file.exists()) {
 327                 BufferedReader reader = new BufferedReader(new FileReader(file));
 328                 while (true) {
 329                     String line = reader.readLine();
 330                     if (line == null) {
 331                         break;
 332                     }
 333                     result.append(line).append("\n");
 334                 }
 335             } else {
 336                 // Does not exist:
 337                 return null;
 338             }
 339         } catch (Exception e) {
 340             e.printStackTrace();
 341         }
 342         return result.toString();
 343     }
 344 
 345     /**
 346      * @return Unsafe instance.
 347      */
 348     public static synchronized Unsafe getUnsafe() {
 349         if (unsafe == null) {
 350             try {
 351                 Field f = Unsafe.class.getDeclaredField("theUnsafe");
 352                 f.setAccessible(true);
 353                 unsafe = (Unsafe) f.get(null);
 354             } catch (NoSuchFieldException | IllegalAccessException e) {
 355                 throw new RuntimeException("Unable to get Unsafe instance.", e);
 356             }
 357         }
 358         return unsafe;
 359     }
 360     private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
 361 
 362     /**
 363      * Returns hex view of byte array
 364      *
 365      * @param bytes byte array to process
 366      * @return Space separated hexadecimal string representation of bytes
 367      */
 368 
 369     public static String toHexString(byte[] bytes) {
 370         char[] hexView = new char[bytes.length * 3];
 371         int i = 0;
 372         for (byte b : bytes) {
 373             hexView[i++] = hexArray[(b >> 4) & 0x0F];
 374             hexView[i++] = hexArray[b & 0x0F];
 375             hexView[i++] = ' ';
 376         }
 377         return new String(hexView);
 378     }
 379 
 380     /**
 381      * Returns {@link java.util.Random} generator initialized with particular seed.
 382      * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME}
 383      * In case no seed is provided, the method uses a random number.
 384      * The used seed printed to stdout.
 385      * @return {@link java.util.Random} generator with particular seed.
 386      */
 387     public static Random getRandomInstance() {
 388         if (RANDOM_GENERATOR == null) {
 389             synchronized (Utils.class) {
 390                 if (RANDOM_GENERATOR == null) {
 391                     RANDOM_GENERATOR = new Random(SEED);
 392                     System.out.printf("For random generator using seed: %d%n", SEED);
 393                     System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED);
 394                 }
 395             }
 396         }
 397         return RANDOM_GENERATOR;
 398     }
 399 }