Java Code Examples for jdk.test.lib.Utils

The following examples show how to use jdk.test.lib.Utils. These examples are extracted from open source projects. 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
public static void runTest(Verify.BinaryMethod method) {
    Random rnd = Utils.getRandomInstance();
    for (int i = 0; i < 50000; ++i) {
        int x = Integer.MAX_VALUE - 10;
        int y = Integer.MAX_VALUE - 10 + rnd.nextInt(5);

        int c = rnd.nextInt() / 2;
        int d = rnd.nextInt() / 2;

        int a = catchingExact(x, y, method);

        if (a != 36) {
            throw new RuntimeException("a != 36 : " + a);
        }

        int b = nonExact(c, d, method);
        int n = exact(c, d, method);


        if (n != b) {
            throw new RuntimeException("n != b : " + n + " != " + b);
        }
    }
}
 
Example 2
private void runSanityCorrectTest(CompileCodeTestCase testCase) {
    System.out.println(testCase);
    Executable aMethod = testCase.executable;
    // to generate ciTypeFlow
    testCase.invoke(Utils.getNullValues(aMethod.getParameterTypes()));
    int bci = testCase.bci;
    HotSpotResolvedJavaMethod method = CTVMUtilities
            .getResolvedMethod(aMethod);
    for (int i = 0; i < SOME_REPEAT_VALUE; ++i) {
        int wbCompileID = getWBCompileID(testCase);
        int id = CompilerToVMHelper.allocateCompileId(method, bci);
        Asserts.assertNE(id, 0, testCase + " : zero compile id");
        Asserts.assertGT(id, wbCompileID, testCase
                + " : allocated 'compile id' not  greater than existed");
        Asserts.assertTrue(ids.add(wbCompileID), testCase
                + " : vm compilation allocated existing id " + id);
        Asserts.assertTrue(ids.add(id), testCase
                + " : allocateCompileId returned existing id " + id);
    }
}
 
Example 3
Source Project: openjdk-jdk9   Source File: PolynomialRoot.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String [] args)
 {
   if (System.getProperty("os.arch").equals("x86") ||
      System.getProperty("os.arch").equals("amd64") ||
      System.getProperty("os.arch").equals("x86_64")){
     final long t0=System.currentTimeMillis();
     final double eps=1e-6;
     //checkRoots();
     final Random r = Utils.getRandomInstance();
     printSpecialValues();

     final int n_tests=100000;
     //testRoots(2,n_tests,r,eps);
     //testRoots(3,n_tests,r,eps);
     testRoots(4,n_tests,r,eps);
     final long t1=System.currentTimeMillis();
     System.err.println("PolynomialRoot.main: "+n_tests+" tests OK done in "+(t1-t0)+" milliseconds. ver=$Id: PolynomialRoot.java,v 1.105 2012/08/18 00:00:05 mal Exp $");
     System.out.println("PASSED");
  } else {
    System.out.println("PASS test for non-x86");
  }
}
 
Example 4
private void runTest(TestCase tcase) {
    System.out.println(tcase);
    String className = tcase.holder.getName();
    HotSpotResolvedObjectType resolvedClazz = CompilerToVMHelper
            .lookupType(Utils.toJVMTypeSignature(tcase.holder),
                    getClass(), /* resolve = */ true);
    HotSpotResolvedJavaMethod initializer = CompilerToVMHelper
            .getClassInitializer(resolvedClazz);
    if (tcase.isPositive) {
        Asserts.assertNotNull(initializer, "Couldn't get initializer for "
                + className);
        Asserts.assertEQ(initializer.getName(), "<clinit>",
                "Unexpected initializer name for " + className);
    } else {
        Asserts.assertNull(initializer, "Unexpected: found initializer for "
                + className);
    }
}
 
Example 5
public static void main(String[] args) throws Exception {
    Recording recording = new Recording();
    recording.enable(EVENT_NAME);
    recording.start();

    // Provoke compilation
    Method mtd = TestCompilerPhase.class.getDeclaredMethod(METHOD_NAME, new Class[0]);
    WhiteBox WB = WhiteBox.getWhiteBox();
    if (!WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_FULL_OPTIMIZATION)) {
        WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_SIMPLE);
    }
    Utils.waitForCondition(() -> WB.isMethodCompiled(mtd));
    dummyMethod();

    recording.stop();

    List<RecordedEvent> events = Events.fromRecording(recording);
    Events.hasEvents(events);
    for (RecordedEvent event : events) {
        System.out.println("Event:" + event);
        Events.assertField(event, "phase").notEmpty();
        Events.assertField(event, "compileId").atLeast(0);
        Events.assertField(event, "phaseLevel").atLeast((short)0).atMost((short)4);
        Events.assertEventThread(event);
    }
}
 
Example 6
/**
 * Build a docker image that contains JDK under test.
 * The jdk will be placed under the "/jdk/" folder inside the docker file system.
 *
 * @param imageName     name of the image to be created, including version tag
 * @param dockerfile    name of the dockerfile residing in the test source;
 *                      we check for a platform specific dockerfile as well
 *                      and use this one in case it exists
 * @param buildDirName  name of the docker build/staging directory, which will
 *                      be created in the jtreg's scratch folder
 * @throws Exception
 */
public static void
    buildJdkDockerImage(String imageName, String dockerfile, String buildDirName)
        throws Exception {

    Path buildDir = Paths.get(".", buildDirName);
    if (Files.exists(buildDir)) {
        throw new RuntimeException("The docker build directory already exists: " + buildDir);
    }
    // check for the existance of a platform specific docker file as well
    String platformSpecificDockerfile = dockerfile + "-" + Platform.getOsArch();
    if (Files.exists(Paths.get(Utils.TEST_SRC, platformSpecificDockerfile))) {
      dockerfile = platformSpecificDockerfile;
    }

    Path jdkSrcDir = Paths.get(Utils.TEST_JDK);
    Path jdkDstDir = buildDir.resolve("jdk");

    Files.createDirectories(jdkDstDir);

    // Copy JDK-under-test tree to the docker build directory.
    // This step is required for building a docker image.
    Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir));
    buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir);
}
 
Example 7
/**
 * Run Java inside the docker image with specified parameters and options.
 *
 * @param DockerRunOptions optins for running docker
 *
 * @return output of the run command
 * @throws Exception
 */
public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Exception {
    ArrayList<String> cmd = new ArrayList<>();

    cmd.add("docker");
    cmd.add("run");
    if (opts.tty)
        cmd.add("--tty=true");
    if (opts.removeContainerAfterUse)
        cmd.add("--rm");

    cmd.addAll(opts.dockerOpts);
    cmd.add(opts.imageNameAndTag);
    cmd.add(opts.command);

    cmd.addAll(opts.javaOpts);
    if (opts.appendTestJavaOptions) {
        Collections.addAll(cmd, Utils.getTestJavaOpts());
    }

    cmd.add(opts.classToRun);
    cmd.addAll(opts.classParams);

    return execute(cmd);
}
 
Example 8
Source Project: openjdk-jdk9   Source File: MultiCommand.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a test containing multiple random commands
 *
 * @param validOnly shows that all commands should be valid
 * @return test instance to run
 */
public static AbstractTestBase generateRandomTest(boolean validOnly) {
    CommandGenerator cmdGen = new CommandGenerator();
    List<Command> commands = cmdGen.generateCommands();
    List<CompileCommand> testCases = new ArrayList<>();
    for (Command cmd : commands) {
        if (validOnly && cmd == Command.NONEXISTENT) {
            // replace with a valid command
            cmd = Command.EXCLUDE;
        }
        Executable exec = Utils.getRandomElement(METHODS).first;
        MethodDescriptor md;
        if (validOnly) {
            md = AbstractTestBase.getValidMethodDescriptor(exec);
        } else {
            md = AbstractTestBase.METHOD_GEN.generateRandomDescriptor(exec);
        }
        CompileCommand cc = cmdGen.generateCompileCommand(cmd, md, null);
        testCases.add(cc);
    }
    return new MultiCommand(testCases);
}
 
Example 9
public static void runTest(Verify.BinaryMethod method) {
    Random rnd = Utils.getRandomInstance();
    for (int i = 0; i < 50000; ++i) {
        int x = Integer.MAX_VALUE - 10;
        int y = Integer.MAX_VALUE - 10 + rnd.nextInt(5);

        int c = rnd.nextInt() / 10;
        int d = rnd.nextInt(9);

        int a = catchingExact(x, y, method);

        if (a != 36) {
            throw new RuntimeException("a != 36 : " + a);
        }

        int b = nonExact(c, d, method);
        int n = exact(c, d, method);


        if (n != b) {
            throw new RuntimeException("n != b : " + n + " != " + b);
        }
    }
}
 
Example 10
Source Project: openjdk-jdk8u   Source File: TestPrint.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {

        OutputAnalyzer output = ExecuteHelper.jfr("print");
        output.shouldContain("missing file");

        output = ExecuteHelper.jfr("print", "missing.jfr");
        output.shouldContain("could not find file ");

        Path file = Utils.createTempFile("faked-print-file",  ".jfr");
        FileWriter fw = new FileWriter(file.toFile());
        fw.write('d');
        fw.close();
        output = ExecuteHelper.jfr("print", "--wrongOption", file.toAbsolutePath().toString());
        output.shouldContain("unknown option");
        Files.delete(file);
    }
 
Example 11
Source Project: openjdk-jdk9   Source File: ProcessTools.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create ProcessBuilder using the java launcher from the jdk to be tested,
 * and with any platform specific arguments prepended.
 *
 * @param addTestVmAndJavaOptions If true, adds test.vm.opts and test.java.opts
 *        to the java arguments.
 * @param command Arguments to pass to the java command.
 * @return The ProcessBuilder instance representing the java command.
 */
public static ProcessBuilder createJavaProcessBuilder(boolean addTestVmAndJavaOptions, String... command) throws Exception {
    String javapath = JDKToolFinder.getJDKTool("java");

    ArrayList<String> args = new ArrayList<>();
    args.add(javapath);
    Collections.addAll(args, getPlatformSpecificVMArgs());

    args.add("-cp");
    args.add(System.getProperty("java.class.path"));

    if (addTestVmAndJavaOptions) {
        Collections.addAll(args, Utils.getTestJavaOpts());
    }

    Collections.addAll(args, command);

    // Reporting
    StringBuilder cmdLine = new StringBuilder();
    for (String cmd : args)
        cmdLine.append(cmd).append(' ');
    System.out.println("Command line: [" + cmdLine.toString() + "]");

    return new ProcessBuilder(args.toArray(new String[args.size()]));
}
 
Example 12
private static Path createBrokenMetadata(Path valid) throws Exception {
    try {
        Path broken = Utils.createTempFile("broken-metadata", ".jfr");
        Files.delete(broken);
        Files.copy(valid, broken);
        RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw");
        raf.seek(METADATA_OFFSET);
        long metadataOffset = raf.readLong();
        raf.seek(metadataOffset);
        raf.writeLong(Long.MAX_VALUE);
        raf.writeLong(Long.MAX_VALUE);
        raf.close();
        return broken;
    } catch (IOException ioe) {
        throw new Exception("Could not produce a broken EventSet from file " + valid, ioe);
    }
}
 
Example 13
public static void main(String... args) throws Exception {
    Configuration defaultConfig = Configuration.getConfiguration("default");
    // Memory
    Recording inMemory = new Recording(defaultConfig);
    inMemory.setToDisk(false);

    inMemory.start();

    Path memoryFile = Utils.createTempFile("start-stop-memory-recording", ".jfr");
    inMemory.dump(memoryFile);
    assertValid(memoryFile, "Not a valid memory file.");
    inMemory.stop();
    inMemory.close();
    // Disk
    Recording toDisk = new Recording(defaultConfig);
    toDisk.setToDisk(true);

    toDisk.start();
    toDisk.stop();
    Path diskFile = Utils.createTempFile("start-stop-disk-recording", ".jfr");
    toDisk.dump(diskFile);
    assertValid(diskFile, "Not a valid disk file.");
    toDisk.close();
}
 
Example 14
public static void main(String[] args) throws Exception {
    Recording recording = new Recording();
    recording.enable(EVENT_NAME);
    recording.start();

    // Provoke compilation
    Method mtd = TestCompilerPhase.class.getDeclaredMethod(METHOD_NAME, new Class[0]);
    WhiteBox WB = WhiteBox.getWhiteBox();
    if (!WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_FULL_OPTIMIZATION)) {
        WB.enqueueMethodForCompilation(mtd, COMP_LEVEL_SIMPLE);
    }
    Utils.waitForCondition(() -> WB.isMethodCompiled(mtd));
    dummyMethod();

    recording.stop();

    List<RecordedEvent> events = Events.fromRecording(recording);
    Events.hasEvents(events);
    for (RecordedEvent event : events) {
        System.out.println("Event:" + event);
        Events.assertField(event, "phase").notEmpty();
        Events.assertField(event, "compileId").atLeast(0);
        Events.assertField(event, "phaseLevel").atLeast((short)0).atMost((short)4);
        Events.assertEventThread(event);
    }
}
 
Example 15
/**
 * Build a docker image that contains JDK under test.
 * The jdk will be placed under the "/jdk/" folder inside the docker file system.
 *
 * @param imageName     name of the image to be created, including version tag
 * @param dockerfile    name of the dockerfile residing in the test source;
 *                      we check for a platform specific dockerfile as well
 *                      and use this one in case it exists
 * @param buildDirName  name of the docker build/staging directory, which will
 *                      be created in the jtreg's scratch folder
 * @throws Exception
 */
public static void
    buildJdkDockerImage(String imageName, String dockerfile, String buildDirName)
        throws Exception {

    Path buildDir = Paths.get(".", buildDirName);
    if (Files.exists(buildDir)) {
        throw new RuntimeException("The docker build directory already exists: " + buildDir);
    }
    // check for the existance of a platform specific docker file as well
    String platformSpecificDockerfile = dockerfile + "-" + Platform.getOsArch();
    if (Files.exists(Paths.get(Utils.TEST_SRC, platformSpecificDockerfile))) {
      dockerfile = platformSpecificDockerfile;
    }

    Path jdkSrcDir = Paths.get(Utils.TEST_JDK);
    Path jdkDstDir = buildDir.resolve("jdk");

    Files.createDirectories(jdkDstDir);

    // Copy JDK-under-test tree to the docker build directory.
    // This step is required for building a docker image.
    Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir));
    buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir);
}
 
Example 16
/**
 * Run Java inside the docker image with specified parameters and options.
 *
 * @param DockerRunOptions optins for running docker
 *
 * @return output of the run command
 * @throws Exception
 */
public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Exception {
    ArrayList<String> cmd = new ArrayList<>();

    cmd.add("docker");
    cmd.add("run");
    if (opts.tty)
        cmd.add("--tty=true");
    if (opts.removeContainerAfterUse)
        cmd.add("--rm");

    cmd.addAll(opts.dockerOpts);
    cmd.add(opts.imageNameAndTag);
    cmd.add(opts.command);

    cmd.addAll(opts.javaOpts);
    if (opts.appendTestJavaOptions) {
        Collections.addAll(cmd, Utils.getTestJavaOpts());
    }

    cmd.add(opts.classToRun);
    cmd.addAll(opts.classParams);

    return execute(cmd);
}
 
Example 17
Source Project: openjdk-jdk8u   Source File: ProcessTools.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create ProcessBuilder using the java launcher from the jdk to be tested,
 * and with any platform specific arguments prepended.
 *
 * @param addTestVmAndJavaOptions If true, adds test.vm.opts and test.java.opts
 *        to the java arguments.
 * @param command Arguments to pass to the java command.
 * @return The ProcessBuilder instance representing the java command.
 */
public static ProcessBuilder createJavaProcessBuilder(boolean addTestVmAndJavaOptions, String... command) {
    String javapath = JDKToolFinder.getJDKTool("java");

    ArrayList<String> args = new ArrayList<>();
    args.add(javapath);

    args.add("-cp");
    args.add(System.getProperty("java.class.path"));

    if (addTestVmAndJavaOptions) {
        Collections.addAll(args, Utils.getTestJavaOpts());
    }

    Collections.addAll(args, command);

    // Reporting
    StringBuilder cmdLine = new StringBuilder();
    for (String cmd : args)
        cmdLine.append(cmd).append(' ');
    System.out.println("Command line: [" + cmdLine.toString() + "]");

    return new ProcessBuilder(args.toArray(new String[args.size()]));
}
 
Example 18
public static void main(String[] args) throws Throwable {
    List<String> options = new ArrayList<>();
    Collections.addAll(options, Utils.getTestJavaOpts());
    Collections.addAll(options,
            "-XX:+UseG1GC",
            "-Xmx20m",
            "-Xmn10m",
            "-Xlog:gc=info",
            "-XX:G1HeapRegionSize=1m"
    );

    options.add(Alloc.class.getName());

    // According to https://bugs.openjdk.java.net/browse/JDK-8146009 failure happens not every time.
    // Will try to reproduce this failure.
    for (int iteration = 0; iteration < 40; ++iteration) {
        startVM(options);
    }
}
 
Example 19
private static void run(int heapSize, int regionSize, int threads, double humongousSize, int timeout)
        throws Exception {
    ArrayList<String> options = new ArrayList<>();
    Collections.addAll(options, Utils.getTestJavaOpts());
    Collections.addAll(options,
            "-Xlog:gc=debug",
            "-Xmx" + heapSize + "m",
            "-XX:+UseG1GC",
            "-XX:G1HeapRegionSize=" + regionSize + "m",
            "-Dtimeout=" + timeout,
            "-Dthreads=" + threads,
            "-Dhumongoussize=" + humongousSize,
            "-Dregionsize=" + regionSize,
            TestStressG1HumongousImpl.class.getName()
    );
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(options.toArray(new String[options.size()]));
    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    output.shouldHaveExitValue(0);
}
 
Example 20
private static OutputAnalyzer runTest(String subset) throws Exception {
    ArrayList<String> vmOpts = new ArrayList();

    Collections.addAll(vmOpts, Utils.getFilteredTestJavaOpts("-Xlog.*"));
    Collections.addAll(vmOpts, new String[] {"-XX:+UnlockDiagnosticVMOptions",
                                             "-XX:+VerifyBeforeGC",
                                             "-XX:+VerifyAfterGC",
                                             "-Xlog:gc+verify=debug",
                                             "-XX:VerifySubSet="+subset,
                                             RunSystemGC.class.getName()});
    ProcessBuilder pb =
        ProcessTools.createJavaProcessBuilder(vmOpts.toArray(new String[vmOpts.size()]));
    OutputAnalyzer output = new OutputAnalyzer(pb.start());

    System.out.println("Output:\n" + output.getOutput());
    return output;
}
 
Example 21
private static OutputAnalyzer runTest(boolean verifySilently) throws Exception {
  ArrayList<String> vmOpts = new ArrayList();

  Collections.addAll(vmOpts, Utils.getFilteredTestJavaOpts("-Xlog.*"));
  Collections.addAll(vmOpts, new String[] {"-XX:+UnlockDiagnosticVMOptions",
                                           "-XX:+VerifyDuringStartup",
                                           "-XX:+VerifyBeforeGC",
                                           "-XX:+VerifyAfterGC",
                                           (verifySilently ? "-Xlog:gc":"-Xlog:gc+verify=debug"),
                                           RunSystemGC.class.getName()});
  ProcessBuilder pb =
    ProcessTools.createJavaProcessBuilder(vmOpts.toArray(new String[vmOpts.size()]));
  OutputAnalyzer output = new OutputAnalyzer(pb.start());

  System.out.println("Output:\n" + output.getOutput());
  return output;
}
 
Example 22
public static void main(String args[]) throws Exception {
    LinkedList<String> options = new LinkedList<>(
            Arrays.asList(Utils.getFilteredTestJavaOpts("(-Xm[nsx][^ ]+)|"
                            + "(-XX:(Max)?((New)|"
                            + "(Heap))((Size)|"
                            + "(Ratio))=[^ ]+)"))
    );

    // Test NewSize and MaxNewSize
    testNewSizeFlags(20 * M, 10 * M, 30 * M, 40 * M, options, false);
    testNewSizeFlags(10 * M, 20 * M, 30 * M, 80 * M, options, false);
    testNewSizeFlags(-1, 20 * M, 30 * M, 40 * M, options, false);
    testNewSizeFlags(10 * M, -1, 30 * M, 40 * M, options, false);
    testNewSizeFlags(20 * M, 20 * M, 30 * M, 40 * M, options, false);
    testNewSizeFlags(20 * M, 30 * M, 40 * M, 50 * M, options, false);
    testNewSizeFlags(30 * M, 100 * M, 150 * M, 200 * M, options, false);
    testNewSizeFlags(20 * M, 30 * M, 128 * M, 128 * M, options, false);

    // Test -Xmn
    testXmnFlags(0, 30 * M, 40 * M, options, true);
    testXmnFlags(20 * M, 30 * M, 40 * M, options, false);
    testXmnFlags(50 * M, 70 * M, 100 * M, options, false);
}
 
Example 23
Source Project: openjdk-jdk9   Source File: TestPrintMdo.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main (String... args) throws Exception {

        LingeredApp app = null;

        if (!Platform.shouldSAAttach()) {
            System.out.println(
               "SA attach not expected to work - test skipped.");
            return;
        }

        try {
            List<String> vmArgs = new ArrayList<String>();
            vmArgs.add("-XX:+ProfileInterpreter");
            vmArgs.addAll(Utils.getVmOptions());

            app = LingeredApp.startApp(vmArgs);
            System.out.println ("Started LingeredApp with pid " + app.getPid());
            startClhsdbForPrintMdo(app.getPid());
            verifyPrintMdoOutput();
        } finally {
            LingeredApp.stopApp(app);
        }
    }
 
Example 24
/**
 * Verifies that the original output meets expectations
 * depending on the test mode. It compares the output of second execution
 * to original one.
 * @param orig original output
 * @param cmdLine command line arguments
 * @throws Throwable - Throws an exception in case test failure.
 */
public void verify(String orig, String[] cmdLine) {
    String output;
    OutputAnalyzer oa;
    try {
        oa = ProcessTools.executeTestJvm(cmdLine);
    } catch (Throwable t) {
        throw new Error("TESTBUG: Unexpedted exception during jvm execution.", t);
    }
    oa.shouldHaveExitValue(0);
    try {
        output = Utils.fileAsString(name()).trim();
    } catch (IOException ioe) {
        throw new Error("TESTBUG: Problem during IO operation with file: " + name(), ioe);
    }
    if (!isOutputExpected(orig, output)) {
        System.err.println("Initial output: " + orig);
        System.err.println("Second run output: " + output);
        throw new AssertionError("Unexpected random number sequence for mode: " + this.name());
    }
}
 
Example 25
protected void runTest() {
    int iterationsCount
            = Integer.getInteger("jdk.test.lib.iterations", 1);
    MemoryPoolMXBean bean = btype.getMemoryPool();
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
            addNotificationListener(this, null, null);
    for (int i = 0; i < iterationsCount; i++) {
        CodeCacheUtils.hitUsageThreshold(bean, btype);
    }
    Asserts.assertTrue(
            Utils.waitForCondition(
                    () -> (CodeCacheUtils.isCodeHeapPredictable(btype) ?
                            (counter == iterationsCount) : (counter >= iterationsCount)),
                    WAIT_TIME),
            "Couldn't receive expected notifications count");
    try {
        ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
                removeNotificationListener(this);
    } catch (ListenerNotFoundException ex) {
        throw new AssertionError("Can't remove notification listener", ex);
    }
    System.out.printf("INFO: Scenario finished successfully for %s%n",
            bean.getName());
}
 
Example 26
Source Project: openjdk-jdk9   Source File: CiReplayBase.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void remove(String item) {
    File toDelete = new File(item);
    toDelete.delete();
    if (Platform.isWindows()) {
        Utils.waitForCondition(() -> !toDelete.exists());
    }
}
 
Example 27
Source Project: TencentKona-8   Source File: ExecuteHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static Path createProfilingRecording() throws Exception {
    Path file = Utils.createTempFile("profiling-recording", ".jfr");
    // Create a recording with some data
    try (Recording r = new Recording(Configuration.getConfiguration("profile"))) {
        r.start();

        // Allocation event
        array = new Object[1000000];
        array = null;

        // Class loading event etc
        provokeClassLoading();

        // GC events
        System.gc();

        // ExecutionSample
        long t = System.currentTimeMillis();
        while (System.currentTimeMillis() - t < 50) {
            // do nothing
        }

        // Other periodic events, i.e CPU load
        Thread.sleep(1000);

        r.stop();
        r.dump(file);
    }

    return file;
}
 
Example 28
private static void recordAndVerify(boolean disk, boolean background,  int[] shouldExist, int[] shouldNotExist) throws Exception {
    StringJoiner sb  = new StringJoiner("-");
    for (int i = 0; i <shouldExist.length; i++) {
        sb.add(Integer.toString(shouldExist[i]));
    }
    System.out.println("Verifying recordings: disk=" + disk + " background=" + background);
    System.out.println("Should exist: " + Arrays.toString(shouldExist));
    System.out.println("Should not exist: " + Arrays.toString(shouldNotExist));

    Path p = Utils.createTempFile(sb.toString(), ".jfr");
    System.out.println("Filename: " + p);
    try (Recording r = new Recording()) {
        r.start();
        r.stop();
        r.dump(p);
        try (RecordingFile f = new RecordingFile(p)) {
            List<EventType> types = f.readEventTypes();
            for (int i = 0; i< shouldExist.length; i++) {
                assertHasEventType(types, "Event" + shouldExist[i]);
            }
            for (int i = 0; i< shouldNotExist.length; i++) {
                assertMissingEventType(types, "Event" + shouldNotExist[i]);
            }
        }
    }
    System.out.println();
    System.out.println();
}
 
Example 29
@Override
public void test() {
    Scenario.Builder builder = Scenario.getBuilder();
    // Add some commands with directives file
    for (int i = 0; i < AMOUNT; i++) {
        Executable exec = Utils.getRandomElement(METHODS).first;
        MethodDescriptor methodDescriptor = getValidMethodDescriptor(exec);
        Command command = cmdGen.generateCommand();
        if (command == Command.NONEXISTENT) {
            // skip invalid command
            command = Command.COMPILEONLY;
        }
        CompileCommand compileCommand = new CompileCommand(command,
                methodDescriptor, cmdGen.generateCompiler(),
                Scenario.Type.DIRECTIVE);
        compileCommand.print();
        builder.add(compileCommand);
    }
    // clear the stack
    builder.add(new JcmdCommand(Command.NONEXISTENT, null, null,
            Scenario.Type.JCMD, Scenario.JcmdType.CLEAR));
    // print all directives after the clear
    builder.add(new JcmdCommand(Command.NONEXISTENT, null, null,
            Scenario.Type.JCMD, Scenario.JcmdType.PRINT));
    Scenario scenario = builder.build();
    scenario.execute();
}
 
Example 30
private static Path postEventAndDumpToFile() throws Throwable {
    Recording r = new Recording();
    r.start();
    TestEvent t = new TestEvent();
    t.commit();
    r.stop();
    Path path = Utils.createTempFile("event-thread", ".jfr");
    System.out.println("Created path: " + path);
    r.dump(path);
    r.close();
    return path;
}