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