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 
  28 import java.io.BufferedReader;
  29 import java.io.File;
  30 import java.io.FileReader;
  31 import java.io.IOException;
  32 import java.net.InetAddress;
  33 import java.net.ServerSocket;
  34 import java.net.UnknownHostException;
  35 import java.util.ArrayList;
  36 import java.util.List;
  37 import java.util.Arrays;
  38 import java.util.Collections;
  39 import java.util.regex.Pattern;
  40 import java.util.regex.Matcher;
  41 
  42 /**
  43  * Common library for various test helper functions.
  44  */
  45 public final class Utils {
  46 
  47     /**
  48      * Returns the sequence used by operating system to separate lines.
  49      */
  50     public static final String NEW_LINE = System.getProperty("line.separator");
  51 
  52     /**
  53      * Returns the value of 'test.vm.opts'system property.
  54      */
  55     public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
  56 
  57     /**
  58      * Returns the value of 'test.java.opts'system property.
  59      */
  60     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
  61 
  62     /**
  63     * Returns the value of 'test.timeout.factor' system property
  64     * converted to {@code double}.
  65     */
  66     public static final double TIMEOUT_FACTOR;
  67     static {
  68         String toFactor = System.getProperty("test.timeout.factor", "1.0");
  69         TIMEOUT_FACTOR = Double.parseDouble(toFactor);
  70     }
  71 
  72     private Utils() {
  73         // Private constructor to prevent class instantiation
  74     }
  75 
  76     /**
  77      * Returns the list of VM options.
  78      *
  79      * @return List of VM options
  80      */
  81     public static List<String> getVmOptions() {
  82         return Arrays.asList(safeSplitString(VM_OPTIONS));
  83     }
  84 
  85     /**
  86      * Returns the list of VM options with -J prefix.
  87      *
  88      * @return The list of VM options with -J prefix
  89      */
  90     public static List<String> getForwardVmOptions() {
  91         String[] opts = safeSplitString(VM_OPTIONS);
  92         for (int i = 0; i < opts.length; i++) {
  93             opts[i] = "-J" + opts[i];
  94         }
  95         return Arrays.asList(opts);
  96     }
  97 
  98     /**
  99      * Returns the default JTReg arguments for a jvm running a test.
 100      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 101      * @return An array of options, or an empty array if no opptions.
 102      */
 103     public static String[] getTestJavaOpts() {
 104         List<String> opts = new ArrayList<String>();
 105         Collections.addAll(opts, safeSplitString(VM_OPTIONS));
 106         Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
 107         return opts.toArray(new String[0]);
 108     }
 109 
 110     /**
 111      * Returns the default JTReg arguments for a jvm running a test without
 112      * options that matches regular expresions in {@code filters}.
 113      * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
 114      * @param filters Regular expressions used to filter out options.
 115      * @return An array of options, or an empty array if no opptions.
 116      */
 117     public static String[] getFilteredTestJavaOpts(String... filters) {
 118         String options[] = getTestJavaOpts();
 119 
 120         if (filters.length == 0) {
 121             return options;
 122         }
 123 
 124         List<String> filteredOptions = new ArrayList<String>(options.length);
 125         Pattern patterns[] = new Pattern[filters.length];
 126         for (int i = 0; i < filters.length; i++) {
 127             patterns[i] = Pattern.compile(filters[i]);
 128         }
 129 
 130         for (String option : options) {
 131             boolean matched = false;
 132             for (int i = 0; i < patterns.length && !matched; i++) {
 133                 Matcher matcher = patterns[i].matcher(option);
 134                 matched = matcher.find();
 135             }
 136             if (!matched) {
 137                 filteredOptions.add(option);
 138             }
 139         }
 140 
 141         return filteredOptions.toArray(new String[filteredOptions.size()]);
 142     }
 143 
 144     /**
 145      * Combines given arguments with default JTReg arguments for a jvm running a test.
 146      * This is the combination of JTReg arguments test.vm.opts and test.java.opts
 147      * @return The combination of JTReg test java options and user args.
 148      */
 149     public static String[] addTestJavaOpts(String... userArgs) {
 150         List<String> opts = new ArrayList<String>();
 151         Collections.addAll(opts, getTestJavaOpts());
 152         Collections.addAll(opts, userArgs);
 153         return opts.toArray(new String[0]);
 154     }
 155 
 156     /**
 157      * Splits a string by white space.
 158      * Works like String.split(), but returns an empty array
 159      * if the string is null or empty.
 160      */
 161     private static String[] safeSplitString(String s) {
 162         if (s == null || s.trim().isEmpty()) {
 163             return new String[] {};
 164         }
 165         return s.trim().split("\\s+");
 166     }
 167 
 168     /**
 169      * @return The full command line for the ProcessBuilder.
 170      */
 171     public static String getCommandLine(ProcessBuilder pb) {
 172         StringBuilder cmd = new StringBuilder();
 173         for (String s : pb.command()) {
 174             cmd.append(s).append(" ");
 175         }
 176         return cmd.toString();
 177     }
 178 
 179     /**
 180      * Returns the free port on the local host.
 181      * The function will spin until a valid port number is found.
 182      *
 183      * @return The port number
 184      * @throws InterruptedException if any thread has interrupted the current thread
 185      * @throws IOException if an I/O error occurs when opening the socket
 186      */
 187     public static int getFreePort() throws InterruptedException, IOException {
 188         int port = -1;
 189 
 190         while (port <= 0) {
 191             Thread.sleep(100);
 192 
 193             ServerSocket serverSocket = null;
 194             try {
 195                 serverSocket = new ServerSocket(0);
 196                 port = serverSocket.getLocalPort();
 197             } finally {
 198                 serverSocket.close();
 199             }
 200         }
 201 
 202         return port;
 203     }
 204 
 205     /**
 206      * Returns the name of the local host.
 207      *
 208      * @return The host name
 209      * @throws UnknownHostException if IP address of a host could not be determined
 210      */
 211     public static String getHostname() throws UnknownHostException {
 212         InetAddress inetAddress = InetAddress.getLocalHost();
 213         String hostName = inetAddress.getHostName();
 214 
 215         assertTrue((hostName != null && !hostName.isEmpty()),
 216                 "Cannot get hostname");
 217 
 218         return hostName;
 219     }
 220 
 221     /**
 222      * Uses "jcmd -l" to search for a jvm pid. This function will wait
 223      * forever (until jtreg timeout) for the pid to be found.
 224      * @param key Regular expression to search for
 225      * @return The found pid.
 226      */
 227     public static int waitForJvmPid(String key) throws Throwable {
 228         final long iterationSleepMillis = 250;
 229         System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
 230         System.out.flush();
 231         while (true) {
 232             int pid = tryFindJvmPid(key);
 233             if (pid >= 0) {
 234                 return pid;
 235             }
 236             Thread.sleep(iterationSleepMillis);
 237         }
 238     }
 239 
 240     /**
 241      * Searches for a jvm pid in the output from "jcmd -l".
 242      *
 243      * Example output from jcmd is:
 244      * 12498 sun.tools.jcmd.JCmd -l
 245      * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 246      *
 247      * @param key A regular expression to search for.
 248      * @return The found pid, or -1 if Enot found.
 249      * @throws Exception If multiple matching jvms are found.
 250      */
 251     public static int tryFindJvmPid(String key) throws Throwable {
 252         OutputAnalyzer output = null;
 253         try {
 254             JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
 255             jcmdLauncher.addToolArg("-l");
 256             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
 257             output.shouldHaveExitValue(0);
 258 
 259             // Search for a line starting with numbers (pid), follwed by the key.
 260             Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
 261             Matcher matcher = pattern.matcher(output.getStdout());
 262 
 263             int pid = -1;
 264             if (matcher.find()) {
 265                 pid = Integer.parseInt(matcher.group(1));
 266                 System.out.println("findJvmPid.pid: " + pid);
 267                 if (matcher.find()) {
 268                     throw new Exception("Found multiple JVM pids for key: " + key);
 269                 }
 270             }
 271             return pid;
 272         } catch (Throwable t) {
 273             System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
 274             throw t;
 275         }
 276     }
 277 
 278     /**
 279      * Returns file content as a list of strings
 280      *
 281      * @param file File to operate on
 282      * @return List of strings
 283      * @throws IOException
 284      */
 285     public static List<String> fileAsList(File file) throws IOException {
 286         assertTrue(file.exists() && file.isFile(),
 287                 file.getAbsolutePath() + " does not exist or not a file");
 288         List<String> output = new ArrayList<>();
 289         try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
 290             while (reader.ready()) {
 291                 output.add(reader.readLine().replace(NEW_LINE, ""));
 292             }
 293         }
 294         return output;
 295     }
 296 
 297 }