1/*
2 * Copyright (c) 2013, 2016, 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.IOException;
29import java.net.InetAddress;
30import java.net.ServerSocket;
31import java.net.UnknownHostException;
32import java.util.ArrayList;
33import java.util.List;
34import java.util.Arrays;
35import java.util.Collections;
36import java.util.regex.Pattern;
37import java.util.regex.Matcher;
38import java.util.concurrent.TimeUnit;
39import java.util.function.BooleanSupplier;
40import 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
49public 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     * The function will spin until a valid port number is found.
180     *
181     * @return The port number
182     * @throws InterruptedException if any thread has interrupted the current thread
183     * @throws IOException if an I/O error occurs when opening the socket
184     */
185    public static int getFreePort() throws InterruptedException, IOException {
186        int port = -1;
187
188        while (port <= 0) {
189            Thread.sleep(100);
190
191            ServerSocket serverSocket = null;
192            try {
193                serverSocket = new ServerSocket(0);
194                port = serverSocket.getLocalPort();
195            } finally {
196                serverSocket.close();
197            }
198        }
199
200        return port;
201    }
202
203    /**
204     * Returns the name of the local host.
205     *
206     * @return The host name
207     * @throws UnknownHostException if IP address of a host could not be determined
208     */
209    public static String getHostname() throws UnknownHostException {
210        InetAddress inetAddress = InetAddress.getLocalHost();
211        String hostName = inetAddress.getHostName();
212
213        assertTrue((hostName != null && !hostName.isEmpty()),
214                "Cannot get hostname");
215
216        return hostName;
217    }
218
219    /**
220     * Adjusts the provided timeout value for the TIMEOUT_FACTOR
221     * @param tOut the timeout value to be adjusted
222     * @return The timeout value adjusted for the value of "test.timeout.factor"
223     *         system property
224     */
225    public static long adjustTimeout(long tOut) {
226        return Math.round(tOut * Utils.TIMEOUT_FACTOR);
227    }
228
229    /**
230     * Wait for condition to be true
231     *
232     * @param condition, a condition to wait for
233     */
234    public static final void waitForCondition(BooleanSupplier condition) {
235        waitForCondition(condition, -1L, 100L);
236    }
237
238    /**
239     * Wait until timeout for condition to be true
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     * @return condition value, to determine if wait was successfull
245     */
246    public static final boolean waitForCondition(BooleanSupplier condition,
247            long timeout) {
248        return waitForCondition(condition, timeout, 100L);
249    }
250
251    /**
252     * Wait until timeout for condition to be true for specified time
253     *
254     * @param condition, a condition to wait for
255     * @param timeout a time in milliseconds to wait for condition to be true,
256     * specifying -1 will wait forever
257     * @param sleepTime a time to sleep value in milliseconds
258     * @return condition value, to determine if wait was successfull
259     */
260    public static final boolean waitForCondition(BooleanSupplier condition,
261            long timeout, long sleepTime) {
262        long startTime = System.currentTimeMillis();
263        while (!(condition.getAsBoolean() || (timeout != -1L
264                && ((System.currentTimeMillis() - startTime) > timeout)))) {
265            try {
266                Thread.sleep(sleepTime);
267            } catch (InterruptedException e) {
268                Thread.currentThread().interrupt();
269                throw new Error(e);
270            }
271        }
272        return condition.getAsBoolean();
273    }
274
275    /**
276     * Interface same as java.lang.Runnable but with
277     * method {@code run()} able to throw any Throwable.
278     */
279    public static interface ThrowingRunnable {
280        void run() throws Throwable;
281    }
282
283    /**
284     * Filters out an exception that may be thrown by the given
285     * test according to the given filter.
286     *
287     * @param test - method that is invoked and checked for exception.
288     * @param filter - function that checks if the thrown exception matches
289     *                 criteria given in the filter's implementation.
290     * @return - exception that matches the filter if it has been thrown or
291     *           {@code null} otherwise.
292     * @throws Throwable - if test has thrown an exception that does not
293     *                     match the filter.
294     */
295    public static Throwable filterException(ThrowingRunnable test,
296            Function<Throwable, Boolean> filter) throws Throwable {
297        try {
298            test.run();
299        } catch (Throwable t) {
300            if (filter.apply(t)) {
301                return t;
302            } else {
303                throw t;
304            }
305        }
306        return null;
307    }
308}
309