Java Code Examples for jdk.test.lib.process.ProcessTools#executeProcess()

The following examples show how to use jdk.test.lib.process.ProcessTools#executeProcess() . 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: TestInstanceKlassSize.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static OutputAnalyzer jcmd(Long pid,
                                   String... toolArgs) throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder();
    JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jcmd");
    launcher.addToolArg(Long.toString(pid));
    if (toolArgs != null) {
        for (String toolArg : toolArgs) {
            launcher.addToolArg(toolArg);
        }
    }

    processBuilder.command(launcher.getCommand());
    System.out.println(
        processBuilder.command().stream().collect(Collectors.joining(" ")));
    return ProcessTools.executeProcess(processBuilder);
}
 
Example 2
Source File: TestDumpOnExit.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void testDumponExit(Supplier<Path> p,String... args) throws Exception, IOException {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, args);
    OutputAnalyzer output = ProcessTools.executeProcess(pb);
    System.out.println(output.getOutput());
    output.shouldHaveExitValue(0);
    Path dump = p.get();
    Asserts.assertTrue(Files.isRegularFile(dump), "No recording dumped " + dump);
    System.out.println("Dumped recording size=" + Files.size(dump));
    Asserts.assertFalse(RecordingFile.readAllEvents(dump).isEmpty(), "No events in dump");
}
 
Example 3
Source File: Utils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Searches for a jvm pid in the output from "jcmd -l".
 *
 * Example output from jcmd is:
 * 12498 sun.tools.jcmd.JCmd -l
 * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 *
 * @param key A regular expression to search for.
 * @return The found pid, or -1 if not found.
 * @throws Exception If multiple matching jvms are found.
 */
public static int tryFindJvmPid(String key) throws Throwable {
    OutputAnalyzer output = null;
    try {
        JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
        jcmdLauncher.addToolArg("-l");
        output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
        output.shouldHaveExitValue(0);

        // Search for a line starting with numbers (pid), follwed by the key.
        Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
        Matcher matcher = pattern.matcher(output.getStdout());

        int pid = -1;
        if (matcher.find()) {
            pid = Integer.parseInt(matcher.group(1));
            System.out.println("findJvmPid.pid: " + pid);
            if (matcher.find()) {
                throw new Exception("Found multiple JVM pids for key: " + key);
            }
        }
        return pid;
    } catch (Throwable t) {
        System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
        throw t;
    }
}
 
Example 4
Source File: Driver8015436.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {
    OutputAnalyzer oa;
    try {
        oa = ProcessTools.executeProcess(ProcessTools.createJavaProcessBuilder(
                /* add test vm options */ true, Test8015436.class.getName()));
    } catch (Exception ex) {
        throw new Error("TESTBUG: exception while running child process: " + ex, ex);
    }
    oa.shouldHaveExitValue(0);
    oa.shouldContain(Test8015436.SOME_MTD_INVOKED);
    oa.shouldContain(Test8015436.DEFAULT_MTD_INVOKED_DIRECTLY);
    oa.shouldContain(Test8015436.DEFAULT_MTD_INVOKED_MH);
}
 
Example 5
Source File: AppExecutorHelper.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Executes an application with enabled JFR and writes collected events
 * to the given output file.
 * Which events to track and other parameters are taken from the setting .jfc file.
 *
 * @param setting JFR settings file(optional)
 * @param jfrFilename JFR resulting recording filename(optional)
 * @param additionalVMFlags additional VM flags passed to the java(optional)
 * @param className name of the class to execute
 * @param classArguments arguments passed to the class(optional)
 * @return output analyzer for executed application
 */
public static OutputAnalyzer executeAndRecord(String settings, String jfrFilename, String[] additionalVmFlags,
                                              String className, String... classArguments) throws Exception {
    List<String> arguments = new ArrayList<>();
    String baseStartFlightRecording = "-XX:StartFlightRecording";
    String additionalStartFlightRecording = "";

    if (additionalVmFlags != null) {
        Collections.addAll(arguments, additionalVmFlags);
    }

    if (settings != null & jfrFilename != null) {
        additionalStartFlightRecording = String.format("=settings=%s,filename=%s", settings, jfrFilename);
    } else if (settings != null) {
        additionalStartFlightRecording = String.format("=settings=%s", settings);
    } else if (jfrFilename != null) {
        additionalStartFlightRecording = String.format("=filename=%s", jfrFilename);
    }
    arguments.add(baseStartFlightRecording + additionalStartFlightRecording);

    arguments.add(className);
    if (classArguments.length > 0) {
        Collections.addAll(arguments, classArguments);
    }

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, arguments.toArray(new String[0]));
    return ProcessTools.executeProcess(pb);
}
 
Example 6
Source File: TestShutdownEvent.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void runSubtest(int subTestIndex) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true,
                            "-XX:+LogJFR",
                            "-XX:-CreateMinidumpOnCrash",
                            "-XX:StartFlightRecording=filename=./dumped.jfr,dumponexit=true,settings=default",
                            "jdk.jfr.event.runtime.TestShutdownEvent$TestMain",
                            String.valueOf(subTestIndex));
    OutputAnalyzer output = ProcessTools.executeProcess(pb);
    System.out.println(output.getOutput());
    int exitCode = output.getExitValue();
    System.out.println("Exit code: " + exitCode);

    String recordingName = output.firstMatch("emergency jfr file: (.*.jfr)", 1);
    if (recordingName == null) {
        recordingName = "./dumped.jfr";
    }

    List<RecordedEvent> events = RecordingFile.readAllEvents(Paths.get(recordingName));
    List<RecordedEvent> filteredEvents = events.stream()
        .filter(e -> e.getEventType().getName().equals(EventNames.Shutdown))
        .sorted(Comparator.comparing(RecordedEvent::getStartTime))
        .collect(Collectors.toList());

    Asserts.assertEquals(filteredEvents.size(), 1);
    RecordedEvent event = filteredEvents.get(0);
    subTests[subTestIndex].verifyEvents(event, exitCode);
}
 
Example 7
Source File: TestDefaultMethods.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void createAnotherToAttach(
                        String[] instanceKlassNames,
                        long lingeredAppPid) throws Exception {

    String[] toolArgs = {
        "--add-modules=jdk.hotspot.agent",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.debugger=ALL-UNNAMED",
        "TestDefaultMethods",
        Long.toString(lingeredAppPid)
    };

    // Start a new process to attach to the lingered app
    ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(toolArgs);
    OutputAnalyzer SAOutput = ProcessTools.executeProcess(processBuilder);
    SAOutput.shouldHaveExitValue(0);
    System.out.println(SAOutput.getOutput());

    SAOutput.shouldContain(
        "Default method: hasScript in instance klass: " + instanceKlassNames[1]);
    SAOutput.shouldContain(
        "No default methods in " + instanceKlassNames[0]);
    SAOutput.shouldContain(
        "Method: hasScript in instance klass: " + instanceKlassNames[0]);
    SAOutput.shouldContain(
        "No default methods in " + instanceKlassNames[2]);
}
 
Example 8
Source File: TestGCYoungGenerationConfigurationEventWithMinAndMaxSize.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String[] jvm_args = {"-XX:+UnlockExperimentalVMOptions",
                         "-XX:-UseFastUnorderedTimeStamps",
                         "-XX:NewSize=12m",
                         "-cp",
                         System.getProperty("java.class.path"),
                         "-XX:MaxNewSize=16m",
                         "-Xms32m",
                         "-Xmx64m",
                         Tester.class.getName()};
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(jvm_args);
    OutputAnalyzer analyzer = ProcessTools.executeProcess(pb);
    analyzer.shouldHaveExitValue(0);
}
 
Example 9
Source File: JcmdExecutor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException {
    List<String> commandLine = createCommandLine(cmd);

    try {
        System.out.printf("Executing command '%s'%n", commandLine);
        OutputAnalyzer output = ProcessTools.executeProcess(new ProcessBuilder(commandLine));
        System.out.printf("Command returned with exit code %d%n", output.getExitValue());

        return output;
    } catch (Exception e) {
        String message = String.format("Caught exception while executing '%s'", commandLine);
        throw new CommandExecutorException(message, e);
    }
}
 
Example 10
Source File: TestStartDuration.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void testDurationInRange(String duration, Duration durationString, boolean wait) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true,
        "-XX:StartFlightRecording=name=TestStartDuration,duration=" + duration, TestValues.class.getName(),
        durationString.toString(), wait ? "wait" : "");
    OutputAnalyzer out = ProcessTools.executeProcess(pb);

    out.shouldHaveExitValue(0);
}
 
Example 11
Source File: TestDumpOnExit.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void testDumponExit(Supplier<Path> p,String... args) throws Exception, IOException {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, args);
    OutputAnalyzer output = ProcessTools.executeProcess(pb);
    System.out.println(output.getOutput());
    output.shouldHaveExitValue(0);
    Path dump = p.get();
    Asserts.assertTrue(Files.isRegularFile(dump), "No recording dumped " + dump);
    System.out.println("Dumped recording size=" + Files.size(dump));
    Asserts.assertFalse(RecordingFile.readAllEvents(dump).isEmpty(), "No events in dump");
}
 
Example 12
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Searches for a jvm pid in the output from "jcmd -l".
 *
 * Example output from jcmd is:
 * 12498 sun.tools.jcmd.JCmd -l
 * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
 *
 * @param key A regular expression to search for.
 * @return The found pid, or -1 if not found.
 * @throws Exception If multiple matching jvms are found.
 */
public static int tryFindJvmPid(String key) throws Throwable {
    OutputAnalyzer output = null;
    try {
        JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
        jcmdLauncher.addToolArg("-l");
        output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
        output.shouldHaveExitValue(0);

        // Search for a line starting with numbers (pid), follwed by the key.
        Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
        Matcher matcher = pattern.matcher(output.getStdout());

        int pid = -1;
        if (matcher.find()) {
            pid = Integer.parseInt(matcher.group(1));
            System.out.println("findJvmPid.pid: " + pid);
            if (matcher.find()) {
                throw new Exception("Found multiple JVM pids for key: " + key);
            }
        }
        return pid;
    } catch (Throwable t) {
        System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
        throw t;
    }
}
 
Example 13
Source File: JcmdExecutor.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected OutputAnalyzer executeImpl(String cmd) throws CommandExecutorException {
    List<String> commandLine = createCommandLine(cmd);

    try {
        System.out.printf("Executing command '%s'%n", commandLine);
        OutputAnalyzer output = ProcessTools.executeProcess(new ProcessBuilder(commandLine));
        System.out.printf("Command returned with exit code %d%n", output.getExitValue());

        return output;
    } catch (Exception e) {
        String message = String.format("Caught exception while executing '%s'", commandLine);
        throw new CommandExecutorException(message, e);
    }
}
 
Example 14
Source File: AppExecutorHelper.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Executes an application with enabled JFR and writes collected events
 * to the given output file.
 * Which events to track and other parameters are taken from the setting .jfc file.
 *
 * @param setting JFR settings file(optional)
 * @param jfrFilename JFR resulting recording filename(optional)
 * @param additionalVMFlags additional VM flags passed to the java(optional)
 * @param className name of the class to execute
 * @param classArguments arguments passed to the class(optional)
 * @return output analyzer for executed application
 */
public static OutputAnalyzer executeAndRecord(String settings, String jfrFilename, String[] additionalVmFlags,
                                              String className, String... classArguments) throws Exception {
    List<String> arguments = new ArrayList<>();
    String baseStartFlightRecording = "-XX:StartFlightRecording";
    String additionalStartFlightRecording = "";

    if (additionalVmFlags != null) {
        Collections.addAll(arguments, additionalVmFlags);
    }

    if (settings != null & jfrFilename != null) {
        additionalStartFlightRecording = String.format("=settings=%s,filename=%s", settings, jfrFilename);
    } else if (settings != null) {
        additionalStartFlightRecording = String.format("=settings=%s", settings);
    } else if (jfrFilename != null) {
        additionalStartFlightRecording = String.format("=filename=%s", jfrFilename);
    }
    arguments.add(baseStartFlightRecording + additionalStartFlightRecording);

    arguments.add(className);
    if (classArguments.length > 0) {
        Collections.addAll(arguments, classArguments);
    }

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, arguments.toArray(new String[0]));
    return ProcessTools.executeProcess(pb);
}
 
Example 15
Source File: JInfoTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static OutputAnalyzer jinfo(String... toolArgs) throws Exception {
    JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jinfo");
    if (toolArgs != null) {
        for (String toolArg : toolArgs) {
            launcher.addToolArg(toolArg);
        }
    }

    processBuilder.command(launcher.getCommand());
    OutputAnalyzer output = ProcessTools.executeProcess(processBuilder);

    return output;
}
 
Example 16
Source File: TestNative.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String lib = System.getProperty("test.nativepath");
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, "-Djava.library.path=" + lib, "jdk.jfr.event.sampling.TestNative$Test");

    OutputAnalyzer output = ProcessTools.executeProcess(pb);
    output.shouldHaveExitValue(0);
    output.stdoutShouldNotContain("No native samples found");
}
 
Example 17
Source File: TestCpoolForInvokeDynamic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void createAnotherToAttach(
                        String[] instanceKlassNames,
                        long lingeredAppPid) throws Exception {

    String[] toolArgs = {
        "--add-modules=jdk.hotspot.agent",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.debugger=ALL-UNNAMED",
        "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.ui.classbrowser=ALL-UNNAMED",
        "TestCpoolForInvokeDynamic",
        Long.toString(lingeredAppPid)
    };

    // Start a new process to attach to the lingered app
    ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(toolArgs);
    OutputAnalyzer SAOutput = ProcessTools.executeProcess(processBuilder);
    SAOutput.shouldHaveExitValue(0);
    System.out.println(SAOutput.getOutput());

    SAOutput.shouldContain("invokedynamic");
    SAOutput.shouldContain("Name and Type");
    SAOutput.shouldContain("run:()Ljava.lang.Runnable");
    SAOutput.shouldContain("compare:()LTestComparator");
    SAOutput.shouldNotContain("Corrupted constant pool");
}
 
Example 18
Source File: TestStartDuration.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void testDurationJavaVersion(String duration, boolean inRange) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true,
        "-XX:StartFlightRecording=name=TestStartDuration,duration=" + duration, "-version");
    OutputAnalyzer out = ProcessTools.executeProcess(pb);

    if (inRange) {
        out.shouldHaveExitValue(0);
    } else {
        out.shouldContain("Could not start recording, duration must be at least 1 second.");
        out.shouldHaveExitValue(1);
    }
}
 
Example 19
Source File: SASymbolTableTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void run(boolean useArchive) throws Exception {
    String flag = useArchive ? "auto" : "off";

    try {
        // (1) Launch the attachee process
        System.out.println("Starting LingeredApp");
        List<String> vmOpts = Arrays.asList(
                "-XX:+UnlockDiagnosticVMOptions",
                "-XX:SharedArchiveFile=" + jsaName,
                "-Xshare:" + flag,
                "-showversion");                // so we can see "sharing" in the output

        theApp = LingeredApp.startApp(vmOpts);

        // (2) Launch the agent process
        long pid = theApp.getPid();
        System.out.println("Attaching agent to " + pid );
        ProcessBuilder tool = ProcessTools.createJavaProcessBuilder(
                "--add-modules=jdk.hotspot.agent",
                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.memory=ALL-UNNAMED",
                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.runtime=ALL-UNNAMED",
                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.tools=ALL-UNNAMED",
                "SASymbolTableTestAgent",
                Long.toString(pid));
        OutputAnalyzer output = ProcessTools.executeProcess(tool);
        System.out.println("STDOUT[");
        System.out.println(output.getOutput());
        if (output.getStdout().contains("connected too early")) {
            System.out.println("SymbolTable not created by VM - test skipped");
            return;
        }
        System.out.println("]");
        System.out.println("STDERR[");
        System.out.print(output.getStderr());
        System.out.println("]");
        output.shouldHaveExitValue(0);
    } catch (Exception ex) {
        throw new RuntimeException("Test ERROR " + ex, ex);
    } finally {
        LingeredApp.stopApp(theApp);
    }
}
 
Example 20
Source File: SecurityTools.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static OutputAnalyzer jarsigner(List<String> args)
        throws Exception {
    return ProcessTools.executeProcess(
            getProcessBuilder("jarsigner", args));
}