--- old/test/java/lang/invoke/modules/ModuleAccessControlTest.java 2016-10-07 11:39:27.000000000 -0700 +++ new/test/java/lang/invoke/modules/ModuleAccessControlTest.java 2016-10-07 11:39:27.000000000 -0700 @@ -26,7 +26,7 @@ import java.util.Arrays; import java.util.List; -import static jdk.testlibrary.ProcessTools.executeTestJava; +import jdk.testlibrary.tasks.JavaTask; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -36,7 +36,7 @@ * @test * @library /lib/testlibrary * @modules jdk.compiler - * @build CompilerUtils jdk.testlibrary.* + * @build CompilerUtils jdk.testlibrary.tasks.JavaTask * @run testng ModuleAccessControlTest * @summary Driver for testing module access checking by MethodHandles.Lookup */ @@ -69,13 +69,9 @@ */ @Test public void runTest() throws Exception { - int exitValue = executeTestJava("--module-path", MODS_DIR.toString(), - "-m", "m1/p1.Main") - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask().ignoreStandardModuleOptions() + .modulepath(MODS_DIR.toString()) + .moduleName("m1").className("p1.Main").run(); } } --- old/test/java/lang/reflect/Proxy/ProxyClassAccessTest.java 2016-10-07 11:39:28.000000000 -0700 +++ new/test/java/lang/reflect/Proxy/ProxyClassAccessTest.java 2016-10-07 11:39:28.000000000 -0700 @@ -30,7 +30,7 @@ import java.util.Arrays; import java.util.List; -import static jdk.testlibrary.ProcessTools.executeTestJava; +import jdk.testlibrary.tasks.JavaTask; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -40,7 +40,7 @@ * @test * @library /lib/testlibrary * @modules jdk.compiler - * @build ProxyClassAccessTest q.NP CompilerUtils jdk.testlibrary.* + * @build ProxyClassAccessTest q.NP CompilerUtils jdk.testlibrary.tasks.JavaTask * @run testng ProxyClassAccessTest * @summary Driver for testing proxy class doesn't have access to * types referenced by proxy interfaces @@ -73,13 +73,9 @@ */ @Test public void runTest() throws Exception { - int exitValue = executeTestJava("--module-path", MODS_DIR.toString(), - "-m", "test/jdk.test.ProxyClassAccess") - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask().ignoreStandardModuleOptions() + .modulepath(MODS_DIR.toString()) + .moduleName("test").className("jdk.test.ProxyClassAccess").run(); } /** --- old/test/java/lang/reflect/Proxy/ProxyTest.java 2016-10-07 11:39:29.000000000 -0700 +++ new/test/java/lang/reflect/Proxy/ProxyTest.java 2016-10-07 11:39:28.000000000 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ import java.util.Arrays; import java.util.List; -import static jdk.testlibrary.ProcessTools.executeTestJava; +import jdk.testlibrary.tasks.JavaTask; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -36,7 +36,7 @@ * @test * @library /lib/testlibrary * @modules jdk.compiler - * @build ProxyTest q.U CompilerUtils jdk.testlibrary.* + * @build ProxyTest q.U CompilerUtils jdk.testlibrary.tasks.JavaTask * @run testng ProxyTest * @summary Driver for testing proxies accessing interfaces in named modules */ @@ -70,13 +70,9 @@ */ @Test public void runTest() throws Exception { - int exitValue = executeTestJava("-cp", CPATH_DIR.toString(), - "--module-path", MODS_DIR.toString(), - "-m", "test/jdk.test.Main") - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask().ignoreStandardModuleOptions() + .classpath(CPATH_DIR.toString()) + .modulepath(MODS_DIR.toString()) + .moduleName("test").className("jdk.test.Main").run(); } } --- old/test/java/util/ResourceBundle/modules/security/TestPermission.java 2016-10-07 11:39:29.000000000 -0700 +++ new/test/java/util/ResourceBundle/modules/security/TestPermission.java 2016-10-07 11:39:29.000000000 -0700 @@ -26,7 +26,7 @@ import java.util.Arrays; import java.util.List; -import static jdk.testlibrary.ProcessTools.executeTestJava; +import jdk.testlibrary.tasks.JavaTask; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -36,7 +36,7 @@ * @test * @library /lib/testlibrary * @modules jdk.compiler - * @build TestPermission CompilerUtils jdk.testlibrary.* + * @build TestPermission CompilerUtils jdk.testlibrary.tasks.JavaTask * @run testng TestPermission * @summary Driver for testing ResourceBundle::getBundle(String, Module) */ @@ -68,13 +68,9 @@ */ @Test public void runTest() throws Exception { - int exitValue = executeTestJava("--module-path", MODS_DIR.toString(), - "--add-modules", "m1", - "-m", "test/jdk.test.Main") - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask().ignoreStandardModuleOptions() + .modulepath(MODS_DIR.toString()) + .addModules("m1") + .moduleName("test").className("jdk.test.Main").run(); } } --- old/test/tools/launcher/modules/addexports/AddExportsTest.java 2016-10-07 11:39:30.000000000 -0700 +++ new/test/tools/launcher/modules/addexports/AddExportsTest.java 2016-10-07 11:39:30.000000000 -0700 @@ -25,7 +25,7 @@ * @test * @library /lib/testlibrary * @modules jdk.compiler - * @build AddExportsTest CompilerUtils jdk.testlibrary.* + * @build AddExportsTest CompilerUtils jdk.testlibrary.* jdk.testlibrary.tasks.JavaTask * @run testng AddExportsTest * @summary Basic tests for java --add-exports */ @@ -34,6 +34,8 @@ import java.nio.file.Paths; import static jdk.testlibrary.ProcessTools.*; +import jdk.testlibrary.tasks.JavaTask; +import jdk.testlibrary.tasks.Task; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; @@ -105,15 +107,10 @@ * Sanity check with -version */ public void testSanity() throws Exception { - - int exitValue - = executeTestJava("--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED", - "-version") - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask() + .addExports("java.base/jdk.internal.reflect=ALL-UNNAMED") + .vmOptions("-version") + .run(); } @@ -125,16 +122,12 @@ // java --add-exports java.base/jdk.internal.misc=ALL-UNNAMED \ // -cp mods/$TESTMODULE jdk.test.UsesUnsafe - String classpath = MODS_DIR.resolve(TEST1_MODULE).toString(); - int exitValue - = executeTestJava("--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED", - "-cp", classpath, - TEST1_MAIN_CLASS) - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask() + .addExports("java.base/jdk.internal.misc=ALL-UNNAMED") + .vmOptions("-version") + .classpath(MODS_DIR.resolve(TEST1_MODULE).toString()) + .className(TEST1_MAIN_CLASS) + .run(); } @@ -146,16 +139,11 @@ // java --add-exports java.base/jdk.internal.misc=test \ // --module-path mods -m $TESTMODULE/$MAIN_CLASS - String mid = TEST1_MODULE + "/" + TEST1_MAIN_CLASS; - int exitValue = - executeTestJava("--add-exports", "java.base/jdk.internal.misc=" + TEST1_MODULE, - "--module-path", MODS_DIR.toString(), - "-m", mid) - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask() + .addExports("java.base/jdk.internal.misc=" + TEST1_MODULE) + .modulepath(MODS_DIR.toString()) + .moduleName(TEST1_MODULE).className(TEST1_MAIN_CLASS) + .run(); } @@ -166,17 +154,12 @@ // java --add-exports java.transaction/javax.transaction.internal=m2 // --upgrade-module-path upgrademods --module-path mods -m ... - String mid = TEST2_MODULE + "/" + TEST2_MAIN_CLASS; - int exitValue = executeTestJava( - "--add-exports", "java.transaction/javax.transaction.internal=m2", - "--upgrade-module-path", UPGRADE_MODS_DIRS.toString(), - "--module-path", MODS_DIR.toString(), - "-m", mid) - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask().ignoreStandardModuleOptions() + .addExports("java.transaction/javax.transaction.internal=m2") + .vmOptions("--upgrade-module-path", UPGRADE_MODS_DIRS.toString()) + .modulepath(MODS_DIR.toString()) + .moduleName(TEST2_MODULE).className(TEST2_MAIN_CLASS) + .run(); } @@ -187,17 +170,11 @@ public void testWithAddMods() throws Exception { // java --add-exports m4/jdk.test4=m3 --module-path mods -m ... - String mid = TEST3_MODULE + "/" + TEST3_MAIN_CLASS; - int exitValue = executeTestJava( - "--add-exports", "m4/jdk.test4=m3", - "--module-path", MODS_DIR.toString(), - "--add-modules", TEST4_MODULE, - "-m", mid) - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue == 0); + new JavaTask().ignoreStandardModuleOptions() + .addExports("m4/jdk.test4=m3").addModules(TEST4_MODULE) + .modulepath(MODS_DIR.toString()) + .moduleName(TEST3_MODULE).className(TEST3_MAIN_CLASS) + .run(); } @@ -205,17 +182,12 @@ * --add-exports can only be specified once */ public void testWithDuplicateOption() throws Exception { - - int exitValue - = executeTestJava("--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED", - "--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED", - "-version") - .outputTo(System.out) - .errorTo(System.out) - .shouldContain("specified more than once") - .getExitValue(); - - assertTrue(exitValue != 0); + new JavaTask() + .vmOptions( + "--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED", + "-version") + .run(Task.Expect.FAIL); } @@ -224,16 +196,11 @@ */ @Test(dataProvider = "badvalues") public void testWithBadValue(String value, String ignore) throws Exception { - // --add-exports $VALUE -version - int exitValue = - executeTestJava("--add-exports", value, - "-version") - .outputTo(System.out) - .errorTo(System.out) - .getExitValue(); - - assertTrue(exitValue != 0); + new JavaTask() + .addExports(value) + .vmOptions("-version") + .run(Task.Expect.FAIL); } @DataProvider(name = "badvalues") --- /dev/null 2016-10-07 11:39:31.000000000 -0700 +++ new/test/lib/testlibrary/jdk/testlibrary/tasks/AbstractTask.java 2016-10-07 11:39:31.000000000 -0700 @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.testlibrary.tasks; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.stream.Collectors; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import jdk.testlibrary.JDKToolFinder; + +/** + * A utility base class to simplify the implementation of tasks. + * Provides support for running the task in a process and for + * capturing output written by the task to stdout, stderr and + * other writers where applicable. + * @param the implementing subclass + */ +abstract class AbstractTask> implements Task { + protected final Mode mode; + private final Map redirects = new EnumMap<>(OutputKind.class); + private String inputRedirect; + private final Map envVars = new HashMap<>(); + private Expect expect = Expect.SUCCESS; + int expectedExitCode = 0; + + /** + * Create a task that will execute in the specified mode. + * @param mode the mode + */ + protected AbstractTask(Mode mode) { + this.mode = mode; + } + + /** + * Sets the expected outcome of the task and calls {@code run()}. + * @param expect the expected outcome + * @return the result of calling {@code run()} + */ + public Result run(Expect expect) { + expect(expect, Integer.MIN_VALUE); + return run(); + } + + /** + * Sets the expected outcome of the task and calls {@code run()}. + * @param expect the expected outcome + * @param exitCode the expected exit code if the expected outcome + * is {@code FAIL} + * @return the result of calling {@code run()} + */ + public Result run(Expect expect, int exitCode) { + expect(expect, exitCode); + return run(); + } + + /** + * Sets the expected outcome and expected exit code of the task. + * The exit code will not be checked if the outcome is + * {@code Expect.SUCCESS} or if the exit code is set to + * {@code Integer.MIN_VALUE}. + * @param expect the expected outcome + * @param exitCode the expected exit code + */ + protected void expect(Expect expect, int exitCode) { + this.expect = expect; + this.expectedExitCode = exitCode; + } + + /** + * Checks the exit code contained in a {@code Result} against the + * expected outcome and exit value + * @param result the result object + * @return the result object + * @throws TaskError if the exit code stored in the result object + * does not match the expected outcome and exit code. + */ + protected Result checkExit(Result result) throws TaskError { + switch (expect) { + case SUCCESS: + if (result.exitCode != 0) { + result.writeAll(); + throw new TaskError("Task " + name() + " failed: rc=" + result.exitCode); + } + break; + + case FAIL: + if (result.exitCode == 0) { + result.writeAll(); + throw new TaskError("Task " + name() + " succeeded unexpectedly"); + } + + if (expectedExitCode != Integer.MIN_VALUE + && result.exitCode != expectedExitCode) { + result.writeAll(); + throw new TaskError("Task " + name() + "failed with unexpected exit code " + + result.exitCode + ", expected " + expectedExitCode); + } + break; + } + return result; + } + + /** + * Sets an environment variable to be used by this task. + * @param name the name of the environment variable + * @param value the value for the environment variable + * @return this task object + * @throws IllegalStateException if the task mode is not {@code EXEC} + */ + public T envVar(String name, String value) { + if (mode != Mode.EXEC) + throw new IllegalStateException(); + envVars.put(name, value); + return (T) this; + } + + /** + * Redirects output from an output stream to a file. + * @param outputKind the name of the stream to be redirected. + * @param path the file + * @return this task object + * @throws IllegalStateException if the task mode is not {@code EXEC} + */ + public T redirect(OutputKind outputKind, String path) { + if (mode != Mode.EXEC) + throw new IllegalStateException(); + redirects.put(outputKind, path); + return (T) this; + } + + /** + * Redirects input to the process input stream from a file. + * @param path the file + * @return this task object + */ + public T redirectInput(String path) { + inputRedirect = path; + return (T)this; + } + + /** + * Calls a Java tool launcher with some arguments. + * @param tool the name of the tool to run + * @param arguments the arguments + * @return a Result object indicating the outcome of the task + * and the content of any output written to stdout or stderr. + * @throws TaskError if the outcome of the task is not as expected. + */ + protected Task.Result run(Tool tool, List arguments) { + List args = new ArrayList<>(); + args.add(JDKToolFinder.getJDKTool(tool.name).toString()); + args.addAll(arguments); + ProcessBuilder pb = getProcessBuilder(); + pb.command(args); + try { + System.out.println("Running " + pb.command().stream().map(s -> "\"" + s + "\"").collect(Collectors.joining(","))); + return runProcess(this, pb.start()); + } catch (IOException | InterruptedException e) { + throw new Error(e); + } + } + + /** + * Returns a {@code ProcessBuilder} initialized with any + * redirects and environment variables that have been set. + * @return a {@code ProcessBuilder} + */ + protected ProcessBuilder getProcessBuilder() { + if (mode != Mode.EXEC) + throw new IllegalStateException(); + ProcessBuilder pb = new ProcessBuilder(); + if (redirects.get(OutputKind.STDOUT) != null) + pb.redirectOutput(new File(redirects.get(OutputKind.STDOUT))); + if (redirects.get(OutputKind.STDERR) != null) + pb.redirectError(new File(redirects.get(OutputKind.STDERR))); + if (inputRedirect != null) + pb.redirectInput(new File(inputRedirect)); + pb.environment().putAll(envVars); + return pb; + } + + /** + * Collects the output from a process and saves it in a {@code Result}. + * @param t the task initiating the process + * @param p the process + * @return a Result object containing the output from the process and its + * exit value. + * @throws InterruptedException if the thread is interrupted + */ + protected Result runProcess(Task t, Process p) throws InterruptedException { + if (mode != Mode.EXEC) + throw new IllegalStateException(); + ProcessOutput sysOut = new ProcessOutput(p.getInputStream()).start(); + ProcessOutput sysErr = new ProcessOutput(p.getErrorStream()).start(); + sysOut.waitUntilDone(); + sysErr.waitUntilDone(); + int rc = p.waitFor(); + Map outputMap = new EnumMap<>(OutputKind.class); + outputMap.put(OutputKind.STDOUT, sysOut.getOutput()); + outputMap.put(OutputKind.STDERR, sysErr.getOutput()); + return checkExit(new Result(t, rc, outputMap)); + } + + /** + * Thread-friendly class to read the output from a process until the stream + * is exhausted. + */ + static class ProcessOutput implements Runnable { + ProcessOutput(InputStream from) { + in = new BufferedReader(new InputStreamReader(from)); + out = new StringBuilder(); + } + + ProcessOutput start() { + new Thread(this).start(); + return this; + } + + @Override + public void run() { + try { + String line; + while ((line = in.readLine()) != null) { + out.append(line).append(lineSeparator); + } + } catch (IOException e) { + } + synchronized (this) { + done = true; + notifyAll(); + } + } + + synchronized void waitUntilDone() throws InterruptedException { + boolean interrupted = false; + + // poll interrupted flag, while waiting for copy to complete + while (!(interrupted = Thread.interrupted()) && !done) + wait(1000); + + if (interrupted) + throw new InterruptedException(); + } + + String getOutput() { + return out.toString(); + } + + private final BufferedReader in; + private final StringBuilder out; + private boolean done; + } + + /** + * Utility class to simplify the handling of temporarily setting a + * new stream for System.out or System.err. + */ + static class StreamOutput { + // Functional interface to set a stream. + // Expected use: System::setOut, System::setErr + interface Initializer { + void set(PrintStream s); + } + + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + private final PrintStream ps = new PrintStream(baos); + private final PrintStream prev; + private final Initializer init; + + StreamOutput(PrintStream s, Initializer init) { + prev = s; + init.set(ps); + this.init = init; + } + + /** + * Closes the stream and returns the contents that were written to it. + * @return the contents that were written to it. + */ + String close() { + init.set(prev); + ps.close(); + return baos.toString(); + } + } + + /** + * Utility class to simplify the handling of creating an in-memory PrintWriter. + */ + static class WriterOutput { + private final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + + /** + * Closes the stream and returns the contents that were written to it. + * @return the contents that were written to it. + */ + String close() { + pw.close(); + return sw.toString(); + } + } + + protected enum Tool { + JAVA("java"), JAR("jar"); + public final String name; + private Tool(String name) { + this.name = name; + } + } +} --- /dev/null 2016-10-07 11:39:32.000000000 -0700 +++ new/test/lib/testlibrary/jdk/testlibrary/tasks/JavaTask.java 2016-10-07 11:39:32.000000000 -0700 @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.testlibrary.tasks; + +import java.util.ArrayList; +import java.util.Arrays; +import static java.util.Arrays.asList; +import static java.util.Collections.EMPTY_LIST; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import static java.util.stream.Collectors.toList; +import java.util.stream.Stream; + +/** + * A task to configure and run the Java launcher. + */ +public class JavaTask extends AbstractTask { + private String classpath; + private String modulepath; + private String className; + private String moduleName; + private List vmOptions; + private List classArgs; + private List addExports; + private List addModules; + private List standardOptions; + + /** + * Create a task to run the Java launcher, using {@code EXEC} mode. + */ + public JavaTask() { + super(Task.Mode.EXEC); + standardOptions = Stream.of("test.vm.opts", "test.java.opts") + .map(p -> System.getProperty(p)) + .filter(p -> p != null && !p.isEmpty()) + .map(o -> asList(o.split(" +"))) + .flatMap(l -> l.stream()).collect(toList()); + } + + /** + * Sets the classpath. + * @param classpath the classpath + * @return this task object + */ + public JavaTask classpath(String classpath) { + this.classpath = classpath; + return this; + } + + /** + * Sets the modulepath. + * @param modulepath the modulepath + * @return this task object + */ + public JavaTask modulepath(String modulepath) { + this.modulepath = modulepath; + return this; + } + + /** + * Sets the {@code --add-exports} option. + * @param addExports value for the option + * @return this task object + */ + public JavaTask addExports(String... addExports) { + this.addExports = Arrays.asList(addExports); + return this; + } + + /** + * Sets the {@code --add-modules} option. + * @param addModules value for the option + * @return this task object + */ + public JavaTask addModules(String... addModules) { + this.addModules = Arrays.asList(addModules); + return this; + } + + /** + * Sets the VM options. + * @param vmOptions the options + * @return this task object + */ + public JavaTask vmOptions(String... vmOptions) { + this.vmOptions = Arrays.asList(vmOptions); + return this; + } + + /** + * Sets the name of the class to be executed. + * @param className the name of the class + * @return this task object + */ + public JavaTask className(String className) { + this.className = className; + return this; + } + + /** + * Sets the name of the module which contains class to be executed. If empty, + * the main class is assumed to be in the unnamed module. + * @param moduleName the name of the module + * @return this task object + */ + public JavaTask moduleName(String moduleName) { + this.moduleName = moduleName; + return this; + } + + /** + * Sets the arguments for the class to be executed. + * @param classArgs the arguments + * @return this task object + */ + public JavaTask classArgs(String... classArgs) { + this.classArgs = Arrays.asList(classArgs); + return this; + } + + /** + * Sets that the standard VM and java options would not be passed + * to the new VM instance. If this method is not called, the default behavior + * is that the options will be passed to the new VM instance. + * + * @return this task object + */ + public JavaTask ignoreStandardOptions() { + standardOptions = EMPTY_LIST; + return this; + } + + /** + * Filters the standard VM and java options. + * @param filter a filter + * @return + */ + public JavaTask filterStandardOption(Function, List> filter) { + standardOptions = filter.apply(standardOptions); + return this; + } + + /** + * Filters the standard VM and java options by taking away a particular option + * and a specified number or parameters after it. + * + * @param option the option, such as {@code --limit-modules} + * @param valueCount number of parameters to remove after the option. + * @return this task object + */ + public JavaTask ignoreStandardOption(String option, int valueCount) { + return filterStandardOption(os -> { + List filtered = new ArrayList<>(); + for(int i = 0; i < os.size(); i++) { + if(os.get(i).equals(option)) + i += valueCount; + else + filtered.add(os.get(i)); + } + return filtered; + }); + } + + /** + * Filters the standard VM and java options so that there are no options which + * affects a set of resolvable modules or a set of accessible APIs. + * + * @return this task object + */ + public JavaTask ignoreStandardModuleOptions() { + moduleOptions.entrySet().stream() + .forEach(e -> ignoreStandardOption(e.getKey(), e.getValue())); + return this; + } + + /** + * {@inheritDoc} + * @return the name "java" + */ + @Override + public String name() { + return "java"; + } + + /** + * Calls the Java launcher with the arguments as currently configured. + * @return a Result object indicating the outcome of the task + * and the content of any output written to stdout or stderr. + * @throws TaskError if the outcome of the task is not as expected. + */ + @Override + public Task.Result run() { + List args = new ArrayList<>(standardOptions); + if (classpath != null) { + args.add("--class-path"); + args.add(classpath); + } + if (modulepath != null) { + args.add("--module-path"); + args.add(modulepath); + } + if (addExports != null) { + args.add("--add-exports"); + args.add(addExports.stream().collect(Collectors.joining(","))); + } + if (addModules != null) { + args.add("--add-modules"); + args.add(addModules.stream().collect(Collectors.joining(","))); + } + if (vmOptions != null) + args.addAll(vmOptions); + if (className != null) + if (moduleName != null) { + args.add("-m"); + args.add(moduleName + "/" + className); + } else + args.add(className); + if (classArgs != null) + args.addAll(classArgs); + return run(Tool.JAVA, args); + } + + //this is a list of options to ignore in ignoreStandardModuleOptions() + private static final Map moduleOptions = + Map.of("--limit-modules", 1, + "--upgrade-module-path", 1, + "--add-modules", 1, + "--add-reads", 1, + "--add-exports", 1, + "--patch-module", 1); +} --- /dev/null 2016-10-07 11:39:32.000000000 -0700 +++ new/test/lib/testlibrary/jdk/testlibrary/tasks/Task.java 2016-10-07 11:39:32.000000000 -0700 @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.testlibrary.tasks; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * The supertype for tasks. + * Complex operations are modeled by building and running a "Task" object. + * Tasks are typically configured in a fluent series of calls. + */ +public interface Task { + /** The platform line separator. */ + static final String lineSeparator = System.getProperty("line.separator"); + /** + * Returns the name of the task. + * @return the name of the task + */ + String name(); + + /** + * Executes the task as currently configured. + * @return a Result object containing the results of running the task + * @throws TaskError if the outcome of the task was not as expected + */ + Result run() throws TaskError; + + /** + * Exception thrown by {@code Task.run} when the outcome is not as + * expected. + */ + public static class TaskError extends Error { + /** + * Creates a TaskError object with the given message. + * @param message the message + */ + public TaskError(String message) { + super(message); + } + } + + /** + * An enum to indicate the mode a task should use it is when executed. + */ + public enum Mode { + /** + * The task should use the interface used by the command + * line launcher for the task. + * For example, for javac: com.sun.tools.javac.Main.compile + */ + CMDLINE, + /** + * The task should use a publicly defined API for the task. + * For example, for javac: javax.tools.JavaCompiler + */ + API, + /** + * The task should use the standard launcher for the task. + * For example, $JAVA_HOME/bin/javac + */ + EXEC + } + + /** + * An enum to indicate the expected success or failure of executing a task. + */ + public enum Expect { + /** It is expected that the task will complete successfully. */ + SUCCESS, + /** It is expected that the task will not complete successfully. */ + FAIL + } + + /** + * An enum to identify the streams that may be written by a {@code Task}. + */ + public enum OutputKind { + /** Identifies output written to {@code System.out} or {@code stdout}. */ + STDOUT, + /** Identifies output written to {@code System.err} or {@code stderr}. */ + STDERR, + /** Identifies output written to a stream provided directly to the task. */ + DIRECT + }; + + /** + * The results from running a {@link Task}. + * The results contain the exit code returned when the tool was invoked, + * and a map containing the output written to any streams during the + * execution of the tool. + * All tools support "stdout" and "stderr". + * Tools that take an explicit PrintWriter save output written to that + * stream as "main". + */ + public static class Result { + final Task task; + final int exitCode; + final Map outputMap; + final List command; + + Result(Task task, int exitCode, Map outputMap, + List command) { + this.task = task; + this.exitCode = exitCode; + this.outputMap = outputMap; + this.command = command; + } + + Result(Task task, int exitCode, Map outputMap) { + this(task, exitCode, outputMap, Collections.EMPTY_LIST); + } + + /** + * Returns the exit code. + * @return the exit code. + */ + public int getExitCode() { + return exitCode; + } + + /** + * Returns the exit code. + * @return the exit code. + */ + public List getCommand() { + return command; + } + + /** + * Returns the content of a specified stream. + * @param outputKind the kind of the selected stream + * @return the content that was written to that stream when the tool + * was executed. + */ + public String getOutput(OutputKind outputKind) { + return outputMap.get(outputKind); + } + + /** + * Returns the content of named streams as a list of lines. + * @param outputKinds the kinds of the selected streams + * @return the content that was written to the given streams when the tool + * was executed. + */ + public List getOutputLines(OutputKind... outputKinds) { + List result = new ArrayList<>(); + for (OutputKind outputKind : outputKinds) { + result.addAll(Arrays.asList(outputMap.get(outputKind).split(lineSeparator))); + } + return result; + } + + /** + * Writes the content of the specified stream to the log. + * @param kind the kind of the selected stream + * @return this Result object + */ + public Result write(OutputKind kind) { + String text = getOutput(kind); + if (text == null || text.isEmpty()) + System.out.println("[" + task.name() + ":" + kind + "]: empty"); + else { + System.out.println("[" + task.name() + ":" + kind + "]:"); + System.out.print(text); + } + return this; + } + + /** + * Writes the content of all streams with any content to the log. + * @return this Result object + */ + public Result writeAll() { + outputMap.forEach((name, text) -> { + if (!text.isEmpty()) { + System.out.println("[" + name + "]:"); + System.out.print(text); + } + }); + return this; + } + } +} +