jdk.testlibrary.ProcessTools Java Examples

The following examples show how to use jdk.testlibrary.ProcessTools. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NestedActions.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void runJava(String[] args) {
    if (args == null || args.length < 3) {
        throw new IllegalArgumentException("wrong parameters");
    }

    List<String> cmds = new ArrayList<>();
    cmds.add(JAVA);
    StringBuilder sb = new StringBuilder();
    cmds.add("-classpath");
    for (int i=2; i<args.length; i++) {
        sb.append(args[i]).append(PS);
    }
    cmds.add(sb.toString());
    if (JAVA_OPTS != null && !JAVA_OPTS.isEmpty()) {
        Collections.addAll(cmds, JAVA_OPTS.trim().split("\\s+"));
    }
    cmds.add("-Djava.security.manager");
    cmds.add("-Djava.security.policy=" + TEST_SOURCES + FS + args[1]);
    cmds.add(args[0]);
    try {
        ProcessTools.executeCommand(cmds.toArray(new String[cmds.size()]))
                .shouldHaveExitValue(0);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: Events.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static Path makeCopy(Recording recording) throws IOException {
    Path p = recording.getDestination();
    int pid = 0;
    try {
        pid = ProcessTools.getProcessId();
    } catch (Exception e) {
        //do nothing, let's use 0
    }

    if (p == null) {
        File directory = new File(".");
        // FIXME: Must come up with a way to give human-readable name
        // this will at least not clash when running parallel.
        p = new File(directory.getAbsolutePath(), "recording-" + recording.getId() + "-pid" + pid + ".jfr").toPath();
        recording.dump(p);
    }
    return p;
}
 
Example #3
Source File: RunUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs a test in a separate JVM.
 * command line like:
 * {test_jdk}/bin/java {defaultopts} -cp {test.class.path} {testopts} main
 *
 * {defaultopts} are the default java options set by the framework.
 * Default GC options in {defaultopts} may be removed.
 * This is used when the test specifies its own GC options.
 *
 * @param main Name of the main class.
 * @param clearGcOpts true if the default GC options should be removed.
 * @param testOpts java options specified by the test.
 */
private static void runTest(String main, boolean clearGcOpts, String... testOpts)
            throws Throwable {
    List<String> opts = new ArrayList<>();
    opts.add(JDKToolFinder.getJDKTool("java"));
    opts.addAll(Arrays.asList(Utils.getTestJavaOpts()));
    opts.add("-cp");
    opts.add(System.getProperty("test.class.path", "test.class.path"));
    opts.add("-Xlog:gc*=debug");

    if (clearGcOpts) {
        opts = Utils.removeGcOpts(opts);
    }
    opts.addAll(Arrays.asList(testOpts));
    opts.add(main);

    OutputAnalyzer output = ProcessTools.executeProcess(opts.toArray(new String[0]));
    output.shouldHaveExitValue(0);
    if (output.getStdout().indexOf(successMessage) < 0) {
        throw new Exception("output missing '" + successMessage + "'");
    }
}
 
Example #4
Source File: PremainClassTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] a) throws Exception {
    String testArgs = String.format(
            "-javaagent:%s/Agent.jar -classpath %s DummyMain",
            System.getProperty("test.src"),
            System.getProperty("test.classes", "."));

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
            Utils.addTestJavaOpts(testArgs.split("\\s+")));
    System.out.println("testjvm.cmd:" + Utils.getCommandLine(pb));

    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    System.out.println("testjvm.stdout:" + output.getStdout());
    System.out.println("testjvm.stderr:" + output.getStderr());

    output.shouldHaveExitValue(0);
    output.stdoutShouldContain("premain running");
    output.stdoutShouldContain("Hello from DummyMain!");
}
 
Example #5
Source File: NoPremainAgentTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] a) throws Exception {
    String testArgs = String.format(
            "-javaagent:NoPremainAgent.jar -classpath %s DummyMain",
            System.getProperty("test.classes", "."));

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
            Utils.addTestJavaOpts(testArgs.split("\\s+")));
    System.out.println("testjvm.cmd:" + Utils.getCommandLine(pb));

    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    System.out.println("testjvm.stdout:" + output.getStdout());
    System.out.println("testjvm.stderr:" + output.getStderr());

    output.stderrShouldContain("java.lang.NoSuchMethodException");
    if (0 == output.getExitValue()) {
        throw new RuntimeException("Expected error but got exit value 0");
    }
}
 
Example #6
Source File: BadHandshakeTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static Process launch(String address, String class_name) throws Exception {
    String[] args = VMConnection.insertDebuggeeVMOptions(new String[] {
        "-agentlib:jdwp=transport=dt_socket" +
        ",server=y" + ",suspend=y" + ",address=" + address,
        class_name
    });

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args);

    final AtomicBoolean success = new AtomicBoolean();
    Process p = ProcessTools.startProcess(
        class_name,
        pb,
        (line) -> {
            // The first thing that will get read is
            //    Listening for transport dt_socket at address: xxxxx
            // which shows the debuggee is ready to accept connections.
            success.set(line.contains("Listening for transport dt_socket at address:"));
            return true;
        },
        Integer.MAX_VALUE,
        TimeUnit.MILLISECONDS
    );

    return success.get() ? p : null;
}
 
Example #7
Source File: IllegalAccessTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs the test to execute the given test action. The VM is run with the
 * given VM options and the output checked to see that it matches the
 * expected result.
 */
OutputAnalyzer run(String action, Result expectedResult, String... vmopts)
    throws Exception
{
    Stream<String> s1 = Stream.of(vmopts);
    Stream<String> s2 = Stream.of("-p", MODULE_PATH, "--add-modules=m",
            "-cp", TEST_CLASSES, "TryAccess", action);
    String[] opts = Stream.concat(s1, s2).toArray(String[]::new);
    OutputAnalyzer outputAnalyzer = ProcessTools
            .executeTestJava(opts)
            .outputTo(System.out)
            .errorTo(System.out);
    if (expectedResult != null)
        checkResult(expectedResult, outputAnalyzer);
    return outputAnalyzer;
}
 
Example #8
Source File: JMXStartStopTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run the "jcmd" command
 * @param target The target application name (or PID)
 * @param c {@linkplain Consumer} instance; may be null
 * @param command Command with parameters; space separated string
 * @throws IOException
 * @throws InterruptedException
 */
private static void jcmd(String target, final Consumer<String> c, String ... command) throws IOException, InterruptedException {
    dbg_print("[jcmd] " + (command.length > 0 ? command[0] : "list"));

    JDKToolLauncher l = JDKToolLauncher.createUsingTestJDK("jcmd");
    l.addToolArg(target);
    for(String cmd : command) {
        l.addToolArg(cmd);
    }
    Process p = ProcessTools.startProcess(
        "jcmd",
        new ProcessBuilder(l.getCommand()),
        c
    );

    p.waitFor();
    dbg_print("[jcmd] --------");
}
 
Example #9
Source File: JMXStartStopTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run the "jcmd" command
 * @param target The target application name (or PID)
 * @param c {@linkplain Consumer} instance; may be null
 * @param command Command with parameters; space separated string
 * @throws IOException
 * @throws InterruptedException
 */
private static void jcmd(String target, final Consumer<String> c, String ... command) throws IOException, InterruptedException {
    dbg_print("[jcmd] " + (command.length > 0 ? command[0] : "list"));

    JDKToolLauncher l = JDKToolLauncher.createUsingTestJDK("jcmd");
    l.addToolArg(target);
    for(String cmd : command) {
        l.addToolArg(cmd);
    }
    Process p = ProcessTools.startProcess(
        "jcmd",
        new ProcessBuilder(l.getCommand()),
        c
    );

    p.waitFor();
    dbg_print("[jcmd] --------");
}
 
Example #10
Source File: BasicTests.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs the actual tests in nested class TestMain.
 * The reason for running the tests in a separate process
 * is that we need to modify the class path.
 */
private static void runTests(int pid) throws Throwable {
    final String sep = File.separator;

    // Need to add jdk/lib/tools.jar to classpath.
    String classpath =
        System.getProperty("test.class.path", "") + File.pathSeparator +
        System.getProperty("test.jdk", ".") + sep + "lib" + sep + "tools.jar";
    String testClassDir = System.getProperty("test.classes", "") + sep;

    // Argumenta : -classpath cp BasicTests$TestMain pid agent badagent redefineagent
    String[] args = {
        "-classpath",
        classpath,
        "BasicTests$TestMain",
        Integer.toString(pid),
        testClassDir + "Agent.jar",
        testClassDir + "BadAgent.jar",
        testClassDir + "RedefineAgent.jar" };
    OutputAnalyzer output = ProcessTools.executeTestJvm(args);
    output.shouldHaveExitValue(0);
}
 
Example #11
Source File: RunUtil.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs a test in a separate JVM.
 * command line like:
 * {test_jdk}/bin/java {defaultopts} -cp {test.class.path} {testopts} main
 *
 * {defaultopts} are the default java options set by the framework.
 * Default GC options in {defaultopts} may be removed.
 * This is used when the test specifies its own GC options.
 *
 * @param main Name of the main class.
 * @param clearGcOpts true if the default GC options should be removed.
 * @param testOpts java options specified by the test.
 */
private static void runTest(String main, boolean clearGcOpts, String... testOpts)
            throws Throwable {
    List<String> opts = new ArrayList<>();
    opts.add(JDKToolFinder.getJDKTool("java"));
    opts.addAll(Arrays.asList(Utils.getTestJavaOpts()));
    opts.add("-cp");
    opts.add(System.getProperty("test.class.path", "test.class.path"));
    opts.add("-XX:+PrintGCDetails");

    if (clearGcOpts) {
        opts = Utils.removeGcOpts(opts);
    }
    opts.addAll(Arrays.asList(testOpts));
    opts.add(main);

    OutputAnalyzer output = ProcessTools.executeProcess(opts.toArray(new String[0]));
    output.shouldHaveExitValue(0);
    if (output.getStdout().indexOf(successMessage) < 0) {
        throw new Exception("output missing '" + successMessage + "'");
    }
}
 
Example #12
Source File: RunnerUtil.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Will stop the running Application.
 * First tries to shutdown nicely by connecting to the shut down port.
 * If that fails, the process will be killed hard with stopProcess().
 *
 * If the nice shutdown fails, then an Exception is thrown and the test should fail.
 *
 * @param port The shut down port.
 * @param processThread The process to stop.
 */
public static void stopApplication(int port, ProcessThread processThread) throws Throwable {
    if (processThread == null) {
        System.out.println("RunnerUtil.stopApplication ignored since proc is null");
        return;
    }
    try {
        System.out.println("RunnerUtil.stopApplication waiting to for shutdown");
        OutputAnalyzer output = ProcessTools.executeTestJvm(
                "-classpath",
                System.getProperty("test.class.path", "."),
                "Shutdown",
                Integer.toString(port));
        // Verify that both the Shutdown command and the Application finished ok.
        output.shouldHaveExitValue(0);
        processThread.joinAndThrow();
        processThread.getOutput().shouldHaveExitValue(0);
    } catch (Throwable t) {
        System.out.println("RunnerUtil.stopApplication failed. Will kill it hard: " + t);
        processThread.stopProcess();
        throw t;
    }
}
 
Example #13
Source File: ZeroArgPremainAgentTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] a) throws Exception {
    String testArgs = String.format(
            "-javaagent:ZeroArgPremainAgent.jar -classpath %s DummyMain",
            System.getProperty("test.classes", "."));

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
            Utils.addTestJavaOpts(testArgs.split("\\s+")));
    System.out.println("testjvm.cmd:" + Utils.getCommandLine(pb));

    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    System.out.println("testjvm.stdout:" + output.getStdout());
    System.out.println("testjvm.stderr:" + output.getStderr());

    output.stderrShouldContain("java.lang.NoSuchMethodException");
    if (0 == output.getExitValue()) {
        throw new RuntimeException("Expected error but got exit value 0");
    }
}
 
Example #14
Source File: JstatdTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse pid from jps output
 */
private String parsePid(String tool, OutputAnalyzer output) throws Exception {
    String[] lines = output.getOutput().split(Utils.NEW_LINE);
    String pid = null;
    int count = 0;
    String processName = tool;
    if (tool == "rmiregistry") {
        processName = "registryimpl";
    }

    Pattern toolInJpsPattern =
            Pattern.compile("^\\d+\\s{1}" + processName + "\\s{1}.*-dparent\\.pid\\." + ProcessTools.getProcessId() + ".*");
    for (String line : lines) {
        if (toolInJpsPattern.matcher(line.toLowerCase()).matches()) {
            pid = line.split(" ")[0];
            count++;
        }
    }
    if (count > 1) {
        throw new Exception("Expected one " + tool
                + " process, got " + count + ". Test will be canceled.");
    }

    return pid;
}
 
Example #15
Source File: ExclusiveBind.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static ProcessBuilder prepareLauncher(String address, boolean suspend, String class_name) throws Exception {
    List<String> args = new ArrayList<>();
    for(String dbgOption : VMConnection.getDebuggeeVMOptions().split(" ")) {
        args.add(dbgOption);
    }
    String lib = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=";
    if (suspend) {
        lib += "y";
    } else {
        lib += "n";
    }
    lib += ",address=" + address;

    args.add(lib);
    args.add(class_name);

    return ProcessTools.createJavaProcessBuilder(args.toArray(new String[args.size()]));
}
 
Example #16
Source File: JMXStartStopTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public synchronized void start() throws InterruptedException, IOException, TimeoutException {
    if (started.compareAndSet(false, true)) {
        try {
            p = ProcessTools.startProcess(
                "JMXStartStopDoSomething",
                pb,
                (line) -> {
                    if (line.toLowerCase().startsWith("pid:")) {
                        pid = Integer.parseInt(line.split("\\:")[1]);
                    }
                    return line.equals("main enter");
                },
                5,
                TimeUnit.SECONDS
            );
        } catch (TimeoutException e) {
            p.destroy();
            p.waitFor();
            throw e;
        }
    }
}
 
Example #17
Source File: JMXStartStopTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public synchronized void start() throws InterruptedException, IOException, TimeoutException {
    if (started.compareAndSet(false, true)) {
        try {
            p = ProcessTools.startProcess(
                "JMXStartStopDoSomething",
                pb,
                (line) -> {
                    if (line.toLowerCase().startsWith("pid:")) {
                        pid = Integer.parseInt(line.split("\\:")[1]);
                    }
                    return line.equals("main enter");
                },
                5,
                TimeUnit.SECONDS
            );
        } catch (TimeoutException e) {
            p.destroy();
            p.waitFor();
            throw e;
        }
    }
}
 
Example #18
Source File: BasicTests.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs the actual tests in nested class TestMain.
 * The reason for running the tests in a separate process
 * is that we need to modify the class path.
 */
private static void runTests(int pid) throws Throwable {
    final String sep = File.separator;

    // Need to add jdk/lib/tools.jar to classpath.
    String classpath =
        System.getProperty("test.class.path", "") + File.pathSeparator +
        System.getProperty("test.jdk", ".") + sep + "lib" + sep + "tools.jar";
    String testClassDir = System.getProperty("test.classes", "") + sep;

    // Argumenta : -classpath cp BasicTests$TestMain pid agent badagent redefineagent
    String[] args = {
        "-classpath",
        classpath,
        "BasicTests$TestMain",
        Integer.toString(pid),
        testClassDir + "Agent.jar",
        testClassDir + "BadAgent.jar",
        testClassDir + "RedefineAgent.jar" };
    OutputAnalyzer output = ProcessTools.executeTestJvm(args);
    output.shouldHaveExitValue(0);
}
 
Example #19
Source File: ProviderTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs the actual tests in the nested class TestMain.
 * We need to run the tests in a separate process,
 * because we need to add to the classpath.
 */
private static void runTests() throws Throwable {
    final String sep = File.separator;
    String testClassPath = System.getProperty("test.class.path", "");
    String testClasses = System.getProperty("test.classes", "") + sep;
    String jdkLib = System.getProperty("test.jdk", ".") + sep + "lib" + sep;

    // Need to add SimpleProvider.jar and tools.jar to classpath.
    String classpath =
            testClassPath + File.pathSeparator +
            testClasses + "SimpleProvider.jar" + File.pathSeparator +
            jdkLib + "tools.jar";

    String[] args = {
            "-classpath",
            classpath,
            "ProviderTest$TestMain" };
    OutputAnalyzer output = ProcessTools.executeTestJvm(args);
    output.shouldHaveExitValue(0);
}
 
Example #20
Source File: JstatdTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Depending on test settings command line can look like:
 *
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy -p port
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy -n serverName
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy -p port -n serverName
 */
private String[] getJstatdCmd() throws Exception {
    JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jstatd");
    launcher.addVMArg("-XX:+UsePerfData");
    String testSrc = System.getProperty("test.src");
    File policy = new File(testSrc, "all.policy");
    assertTrue(policy.exists() && policy.isFile(),
            "Security policy " + policy.getAbsolutePath() + " does not exist or not a file");
    launcher.addVMArg("-Djava.security.policy=" + policy.getAbsolutePath());
    // -Dparent.pid.<pid> will help to identify jstad process started by this test
    launcher.addVMArg("-Dparent.pid." + ProcessTools.getProcessId());
    if (port != null) {
        launcher.addToolArg("-p");
        launcher.addToolArg(port);
    }
    if (serverName != null) {
        launcher.addToolArg("-n");
        launcher.addToolArg(serverName);
    }

    String[] cmd = launcher.getCommand();
    log("Start jstatd", cmd);
    return cmd;
}
 
Example #21
Source File: TestJpsJarRelative.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    String testJdk = System.getProperty("test.jdk", "?");
    String testSrc = System.getProperty("test.src", "?");
    File jar = JpsHelper.buildJar("JpsBase");

    List<String> cmd = new ArrayList<>();
    cmd.addAll(JpsHelper.getVmArgs());
    cmd.add("-Dtest.jdk=" + testJdk);
    cmd.add("-Dtest.src=" + testSrc);
    cmd.add("-jar");
    cmd.add("." + File.separator + jar.getName());
    cmd.add("monkey");

    ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(cmd.toArray(new String[cmd.size()]));
    OutputAnalyzer output = new OutputAnalyzer(processBuilder.start());
    System.out.println(output.getOutput());
    output.shouldHaveExitValue(0);
}
 
Example #22
Source File: TestJpsJarRelative.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    String testJdk = System.getProperty("test.jdk", "?");
    String testSrc = System.getProperty("test.src", "?");
    File jar = JpsHelper.buildJar("JpsBase");

    List<String> cmd = new ArrayList<>();
    cmd.addAll(JpsHelper.getVmArgs());
    cmd.add("-Dtest.jdk=" + testJdk);
    cmd.add("-Dtest.src=" + testSrc);
    cmd.add("-jar");
    cmd.add("." + File.separator + jar.getName());
    cmd.add("monkey");

    ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(cmd.toArray(new String[cmd.size()]));
    OutputAnalyzer output = new OutputAnalyzer(processBuilder.start());
    System.out.println(output.getOutput());
    output.shouldHaveExitValue(0);
}
 
Example #23
Source File: TestJpsJar.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    String testJdk = System.getProperty("test.jdk", "?");
    String testSrc = System.getProperty("test.src", "?");
    File jar = JpsHelper.buildJar("JpsBase");

    List<String> cmd = new ArrayList<>();
    cmd.addAll(JpsHelper.getVmArgs());
    cmd.add("-Dtest.jdk=" + testJdk);
    cmd.add("-Dtest.src=" + testSrc);
    cmd.add("-jar");
    cmd.add(jar.getAbsolutePath());
    cmd.add("monkey");

    ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(cmd.toArray(new String[cmd.size()]));
    OutputAnalyzer output = new OutputAnalyzer(processBuilder.start());
    System.out.println(output.getOutput());
    output.shouldHaveExitValue(0);
}
 
Example #24
Source File: BadHandshakeTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static Process launch(String address, String class_name) throws Exception {
    String[] args = VMConnection.insertDebuggeeVMOptions(new String[] {
        "-agentlib:jdwp=transport=dt_socket" +
        ",server=y" + ",suspend=y" + ",address=" + address,
        class_name
    });

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args);

    final AtomicBoolean success = new AtomicBoolean();
    Process p = ProcessTools.startProcess(
        class_name,
        pb,
        (line) -> {
            // The first thing that will get read is
            //    Listening for transport dt_socket at address: xxxxx
            // which shows the debuggee is ready to accept connections.
            success.set(line.contains("Listening for transport dt_socket at address:"));
            return true;
        },
        1500,
        TimeUnit.MILLISECONDS
    );

    return success.get() ? p : null;
}
 
Example #25
Source File: RunnerUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Will stop the running Application.
 * First tries to shutdown nicely by connecting to the shut down port.
 * If that fails, the process will be killed hard with stopProcess().
 *
 * If the nice shutdown fails, then an Exception is thrown and the test should fail.
 *
 * @param port The shut down port.
 * @param processThread The process to stop.
 */
public static void stopApplication(int port, ProcessThread processThread) throws Throwable {
    if (processThread == null) {
        System.out.println("RunnerUtil.stopApplication ignored since proc is null");
        return;
    }
    try {
        System.out.println("RunnerUtil.stopApplication waiting to for shutdown");
        OutputAnalyzer output = ProcessTools.executeTestJvm(
                "-classpath",
                System.getProperty("test.class.path", "."),
                "Shutdown",
                Integer.toString(port));
        // Verify that both the Shutdown command and the Application finished ok.
        output.shouldHaveExitValue(0);
        processThread.joinAndThrow();
        processThread.getOutput().shouldHaveExitValue(0);
    } catch (Throwable t) {
        System.out.println("RunnerUtil.stopApplication failed. Will kill it hard: " + t);
        processThread.stopProcess();
        throw t;
    }
}
 
Example #26
Source File: BasicJStackTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static OutputAnalyzer jstack(String... toolArgs) throws Exception {
    JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jstack");
    launcher.addVMArg("-XX:+UsePerfData");
    if (toolArgs != null) {
        for (String toolArg : toolArgs) {
            launcher.addToolArg(toolArg);
        }
    }
    launcher.addToolArg(Long.toString(ProcessTools.getProcessId()));

    processBuilder.command(launcher.getCommand());
    System.out.println(Arrays.toString(processBuilder.command().toArray()).replace(",", ""));
    OutputAnalyzer output = ProcessTools.executeProcess(processBuilder);
    System.out.println(output.getOutput());

    return output;
}
 
Example #27
Source File: JMXStartStopTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run the "jcmd" command
 * @param target The target application name (or PID)
 * @param c {@linkplain Consumer} instance; may be null
 * @param command Command with parameters; space separated string
 * @throws IOException
 * @throws InterruptedException
 */
private static void jcmd(String target, final Consumer<String> c, String ... command) throws IOException, InterruptedException {
    dbg_print("[jcmd] " + (command.length > 0 ? command[0] : "list"));

    JDKToolLauncher l = JDKToolLauncher.createUsingTestJDK("jcmd");
    l.addToolArg(target);
    for(String cmd : command) {
        l.addToolArg(cmd);
    }
    Process p = ProcessTools.startProcess(
        "jcmd",
        new ProcessBuilder(l.getCommand()),
        c
    );

    p.waitFor();
    dbg_print("[jcmd] --------");
}
 
Example #28
Source File: JstatdTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Depending on test settings command line can look like:
 *
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy -p port
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy -n serverName
 * jstatd -J-XX:+UsePerfData -J-Djava.security.policy=all.policy -p port -n serverName
 */
private String[] getJstatdCmd() throws Exception {
    JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jstatd");
    launcher.addVMArg("-XX:+UsePerfData");
    String testSrc = System.getProperty("test.src");
    File policy = new File(testSrc, "all.policy");
    assertTrue(policy.exists() && policy.isFile(),
            "Security policy " + policy.getAbsolutePath() + " does not exist or not a file");
    launcher.addVMArg("-Djava.security.policy=" + policy.getAbsolutePath());
    // -Dparent.pid.<pid> will help to identify jstad process started by this test
    launcher.addVMArg("-Dparent.pid." + ProcessTools.getProcessId());
    if (port != null) {
        launcher.addToolArg("-p");
        launcher.addToolArg(port);
    }
    if (serverName != null) {
        launcher.addToolArg("-n");
        launcher.addToolArg(serverName);
    }

    String[] cmd = launcher.getCommand();
    log("Start jstatd", cmd);
    return cmd;
}
 
Example #29
Source File: BadHandshakeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static Process launch(String address, String class_name) throws Exception {
    String[] args = VMConnection.insertDebuggeeVMOptions(new String[] {
        "-agentlib:jdwp=transport=dt_socket" +
        ",server=y" + ",suspend=y" + ",address=" + address,
        class_name
    });

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args);

    final AtomicBoolean success = new AtomicBoolean();
    Process p = ProcessTools.startProcess(
        class_name,
        pb,
        (line) -> {
            // The first thing that will get read is
            //    Listening for transport dt_socket at address: xxxxx
            // which shows the debuggee is ready to accept connections.
            success.set(line.contains("Listening for transport dt_socket at address:"));
            return true;
        },
        Integer.MAX_VALUE,
        TimeUnit.MILLISECONDS
    );

    return success.get() ? p : null;
}
 
Example #30
Source File: ZeroArgPremainAgentTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] a) throws Exception {
    String testArgs = String.format(
            "-javaagent:ZeroArgPremainAgent.jar -classpath %s DummyMain",
            System.getProperty("test.classes", "."));

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
            Utils.addTestJavaOpts(testArgs.split("\\s+")));
    System.out.println("testjvm.cmd:" + Utils.getCommandLine(pb));

    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    System.out.println("testjvm.stdout:" + output.getStdout());
    System.out.println("testjvm.stderr:" + output.getStderr());

    output.stderrShouldContain("java.lang.NoSuchMethodException");
    if (0 == output.getExitValue()) {
        throw new RuntimeException("Expected error but got exit value 0");
    }
}