Java Code Examples for jdk.test.lib.Asserts

The following examples show how to use jdk.test.lib.Asserts. 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
private static void checkThrowableEvents(List<RecordedEvent> events, String eventName,
    int excpectedEvents, Class<?> expectedClass, String expectedMessage) throws Exception {
    int count = 0;
    for(RecordedEvent event : events) {
        if (Events.isEventType(event, eventName)) {
            String message = Events.assertField(event, "message").getValue();
            if (expectedMessage.equals(message)) {
                RecordedThread t = event.getThread();
                String threadName = t.getJavaName();
                if (threadName != null && threadName.equals(Thread.currentThread().getName())) {
                    RecordedClass jc = event.getValue("thrownClass");
                    if (jc.getName().equals(expectedClass.getName())) {
                        count++;
                    }
                }
            }
        }
    }
    Asserts.assertEquals(count, excpectedEvents, "Wrong event count for type " + eventName);
}
 
Example 2
public static void main(String[] args) throws Exception {
    EventType t = EventType.getEventType(ExperimentalEvent.class);

    // @Experimental on event
    Experimental e = t.getAnnotation(Experimental.class);
    Asserts.assertTrue(e != null, "Expected @Experimental annotation on event");

    // @Experimental on annotation
    AnnotationElement a = Events.getAnnotationByName(t, ExperimentalAnnotation.class.getName());
    e = a.getAnnotation(Experimental.class);
    Asserts.assertTrue(e != null, "Expected @Experimental on annotation");

    // @Experimental on field
    a = Events.getAnnotation(t.getField("experimentalField"), Experimental.class);
    Asserts.assertTrue(e != null, "Expected @Experimental on field");
}
 
Example 3
private static long testRecording(FlightRecorderMXBean bean) throws Exception {
    System.out.println("A");
    long recId = bean.newRecording();
    System.out.println("B");
    bean.setPredefinedConfiguration(recId, "profile");
    System.out.println("C");
    bean.startRecording(recId);
    System.out.println("D");
    Asserts.assertTrue(bean.getRecordings().stream().anyMatch(r -> { return r.getId() == recId; }), "recId not found");
    System.out.println("E");
    bean.stopRecording(recId);

    final Path path = Paths.get(".", "rec" + recId + ".jfr");
    bean.copyTo(recId, path.toString());
    //EventSet events = EventSet.fromFile(path);
    return recId;
}
 
Example 4
Source Project: TencentKona-8   Source File: JcmdHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void waitUntilRunning(String name) throws Exception {
    long timeoutAt = System.currentTimeMillis() + 10000;
    while (true) {
        OutputAnalyzer output = jcmdCheck(name, false);
        try {
            // The expected output can look like this:
            // Recording 1: name=1 (running)
            output.shouldMatch("^Recording \\d+: name=" + name
                    + " .*\\W{1}running\\W{1}");
            return;
        } catch (RuntimeException e) {
            if (System.currentTimeMillis() > timeoutAt) {
                Asserts.fail("Recording not started: " + name);
            }
            Thread.sleep(100);
        }
    }
}
 
Example 5
public static void main(String[] args) throws Exception {
    EventType type = EventType.getEventType(CustomEvent.class);

    SettingDescriptor plain = Events.getSetting(type, "plain");
    Asserts.assertNull(plain.getDescription());

    SettingDescriptor annotatedType = Events.getSetting(type, "annotatedType");
    Asserts.assertEquals(annotatedType.getDescription(), AnnotatedSetting.DESCRIPTION);

    SettingDescriptor newName = Events.getSetting(type, "newName");
    Asserts.assertEquals(newName.getDescription(), CustomEvent.DESCRIPTION_OF_AN_ANNOTATED_METHOD);

    SettingDescriptor overridden = Events.getSetting(type, "overridden");
    Asserts.assertNull(overridden.getDescription());

    SettingDescriptor protectedBase = Events.getSetting(type, "protectedBase");
    Asserts.assertEquals(protectedBase.getDescription(), "Description of protected base");

    SettingDescriptor publicBase = Events.getSetting(type, "publicBase");
    Asserts.assertEquals(publicBase.getDescription(), AnnotatedSetting.DESCRIPTION);

    SettingDescriptor packageProtectedBase = Events.getSetting(type, "packageProtectedBase");
    Asserts.assertNull(packageProtectedBase.getDescription());

    CustomEvent.assertOnDisk((x, y) -> Objects.equals(x.getDescription(), y.getDescription()) ? 0 : 1);
}
 
Example 6
Source Project: TencentKona-8   Source File: TestGetId.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Map<Long, Recording> recordings = new HashMap<>();

    final int iterations = 100;
    for (int i = 0; i < iterations; ++i) {
        Recording newRecording = new Recording();
        System.out.println("created: " + newRecording.getId());
        Recording oldRecording = recordings.get(newRecording.getId());
        Asserts.assertNull(oldRecording, "Duplicate recording ID: " + newRecording.getId());
        recordings.put(newRecording.getId(), newRecording);

        if (i % 3 == 0) {
            Recording closeRecording = recordings.remove(recordings.keySet().iterator().next());
            Asserts.assertNotNull(closeRecording, "Could not find recording in map. Test error.");
            closeRecording.close();
            System.out.println("closed: " + closeRecording.getId());
        }
    }

    for (Recording r : recordings.values()) {
        r.close();
    }
}
 
Example 7
Source Project: TencentKona-8   Source File: RefStatEvent.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void verifyRefStatEvents(List<RecordedEvent> events, int gcId) {
    List<String> expectedTypes = Arrays.asList("Soft reference", "Weak reference", "Final reference", "Phantom reference");
    List<String> actualTypes = new ArrayList<>();
    try {
        for (RecordedEvent event : events) {
            if (!Events.isEventType(event, refStatsEventPath)) {
                continue;
            }
            Events.assertField(event, "count").atLeast(0L);
            if (Events.assertField(event, "gcId").isEqual(gcId)) {
                actualTypes.add(Events.assertField(event, "type").notEmpty().getValue());
            }
        }

        Asserts.assertEquals(actualTypes.size(), expectedTypes.size(), "Wrong number of refStat events");
        Asserts.assertTrue(expectedTypes.containsAll(actualTypes), "Found unknown refStat types");
        Asserts.assertTrue(actualTypes.containsAll(expectedTypes), "Missning refStat types");
    } catch (Exception e) {
        System.out.println("Expected refStatTypes: " + expectedTypes.stream().collect(Collectors.joining(", ")));
        System.out.println("Got refStatTypes: " + actualTypes.stream().collect(Collectors.joining(", ")));
        throw e;
    }
}
 
Example 8
public static void main(String[] args) throws Exception {
    String[] vmFlags = {"-Xmx128m", "-XX:MaxTenuringThreshold=0", "-Xloggc:testCMSGC.log", "-verbose:gc",
        "-XX:+UseConcMarkSweepGC", "-XX:+UnlockExperimentalVMOptions", "-XX:-UseFastUnorderedTimeStamps"};

    if (!ExecuteOOMApp.execute(EVENT_SETTINGS_FILE, JFR_FILE, vmFlags, BYTES_TO_ALLOCATE)) {
        System.out.println("OOM happened in the other thread(not test thread). Skip test.");
        // Skip test, process terminates due to the OOME error in the different thread
        return;
    }

    Optional<RecordedEvent> event = RecordingFile.readAllEvents(Paths.get(JFR_FILE)).stream().findFirst();
    if (event.isPresent()) {
        Asserts.assertEquals(EVENT_NAME, event.get().getEventType().getName(), "Wrong event type");
    } else {
        // No event received. Check if test did trigger the event.
        boolean isEventTriggered = fileContainsString("testCMSGC.log", "concurrent mode failure");
        System.out.println("isEventTriggered=" +isEventTriggered);
        Asserts.assertFalse(isEventTriggered, "Event found in log, but not in JFR");
    }
}
 
Example 9
public static void main(String[] args) throws Exception {
    EventType type = EventType.getEventType(CustomEvent.class);

    SettingDescriptor plain = Events.getSetting(type, "plain");
    Asserts.assertEquals(plain.getDefaultValue(), "plain");

    SettingDescriptor annotatedType = Events.getSetting(type, "annotatedType");
    Asserts.assertEquals(annotatedType.getDefaultValue(), AnnotatedSetting.DEFAULT_VALUE);

    SettingDescriptor newName = Events.getSetting(type, "newName");
    Asserts.assertEquals(newName.getDefaultValue(), AnnotatedSetting.DEFAULT_VALUE);

    SettingDescriptor overridden = Events.getSetting(type, "overridden");
    Asserts.assertEquals(overridden.getDefaultValue(), PlainSetting.DEFAULT_VALUE);

    CustomEvent.assertOnDisk((x, y) -> x.getName().compareTo(y.getName()));
}
 
Example 10
Source Project: TencentKona-8   Source File: TestEventTypes.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void assertSame(List<EventTypeInfo> infos, List<EventType> types) {
    List<Long> ids = new ArrayList<>();
    for (EventTypeInfo info : infos) {
        long id = info.getId();
        Asserts.assertFalse(ids.contains(id), "EventTypeInfo.id not unique:" + id);
        ids.add(id);
        boolean isFound = false;
        for (EventType type : types) {
            if (type.getId() == id) {
                assertSame(info, type);
                isFound = true;
                break;
            }
        }
        if (!isFound) {
            String msg = "No EventType for EventTypeInfo";
            System.out.println(msg + ": " + info);
            Asserts.fail(msg);
        }
    }
    Asserts.assertEquals(infos.size(), types.size(), "Number of EventTypeInfos != EventTypes");
}
 
Example 11
private static void assertFrame(RecordedFrame frame) {
    int bci = frame.getBytecodeIndex();
    int line = frame.getLineNumber();
    boolean javaFrame = frame.isJavaFrame();
    RecordedMethod method = frame.getMethod();
    String type = frame.getType();
    System.out.println("*** Frame Info ***");
    System.out.println("bci=" + bci);
    System.out.println("line=" + line);
    System.out.println("type=" + type);
    System.out.println("method=" + method);
    System.out.println("***");
    Asserts.assertTrue(javaFrame, "Only Java frame are currently supported");
    Asserts.assertGreaterThanOrEqual(bci, -1);
    Asserts.assertNotNull(method, "Method should not be null");
}
 
Example 12
public static void main(String[] args) throws Exception {
    String[] vmFlags = {"-XX:+UnlockExperimentalVMOptions", "-XX:-UseFastUnorderedTimeStamps",
        "-Xmx64m", "-Xmn60m", "-XX:-UseDynamicNumberOfGCThreads", "-XX:ParallelGCThreads=3",
        "-XX:MaxTenuringThreshold=0", "-verbose:gc", "-XX:+UseG1GC"};

    if (!ExecuteOOMApp.execute(EVENT_SETTINGS_FILE, JFR_FILE, vmFlags, BYTES_TO_ALLOCATE)) {
        System.out.println("OOM happened in the other thread(not test thread). Skip test.");
        // Skip test, process terminates due to the OOME error in the different thread
        return;
    }

    List<RecordedEvent> events = RecordingFile.readAllEvents(Paths.get(JFR_FILE));

    Events.hasEvents(events);
    for (RecordedEvent event : events) {
        long objectCount = Events.assertField(event, "evacuationFailed.objectCount").atLeast(1L).getValue();
        long smallestSize = Events.assertField(event, "evacuationFailed.smallestSize").atLeast(1L).getValue();
        long firstSize = Events.assertField(event, "evacuationFailed.firstSize").atLeast(smallestSize).getValue();
        long totalSize = Events.assertField(event, "evacuationFailed.totalSize").atLeast(firstSize).getValue();
        Asserts.assertLessThanOrEqual(smallestSize * objectCount, totalSize, "smallestSize * objectCount <= totalSize");
    }
}
 
Example 13
private static void verifyTimes(List<RecordedEvent> events) {
    RecordedEvent prev = null;
    for (RecordedEvent curr : events) {
        if (prev != null) {
            try {
                Asserts.assertGreaterThanOrEqual(curr.getStartTime(), prev.getStartTime(), "Wrong startTime");
                Asserts.assertGreaterThanOrEqual(curr.getEndTime(), prev.getEndTime(), "Wrong endTime");
                long commitPrev = Events.assertField(prev, "startTime").getValue();
                long commitCurr = Events.assertField(curr, "startTime").getValue();
                Asserts.assertGreaterThanOrEqual(commitCurr, commitPrev, "Wrong commitTime");
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
                System.out.println("Prev Event: " + prev);
                System.out.println("Curr Event: " + curr);
                throw e;
            }
        }
        prev = curr;
    }
}
 
Example 14
private static void validateString(ConstantPool constantPoolCTVM,
                                   ConstantTypes cpType,
                                   DummyClasses dummyClass,
                                   int cpi) {
    TestedCPEntry entry = cpType.getTestedCPEntry(dummyClass, cpi);
    if (entry == null) {
        return;
    }
    int index = cpi;
    String cached = "";
    int cpci = dummyClass.getCPCacheIndex(cpi);
    if (cpci != ConstantPoolTestsHelper.NO_CP_CACHE_PRESENT) {
        index = cpci;
        cached = "cached ";
    }
    Object constantInPool = CompilerToVMHelper.resolvePossiblyCachedConstantInPool(constantPoolCTVM, index);
    String stringToVerify = (String) constantInPool;
    String stringToRefer = entry.name;
    if (stringToRefer.equals("") && cpci != ConstantPoolTestsHelper.NO_CP_CACHE_PRESENT) {
        stringToRefer = null; // tested method returns null for cached empty strings
    }
    String msg = String.format("Wrong string accessed by %sconstant pool index %d", cached, index);
    Asserts.assertEQ(stringToRefer, stringToVerify, msg);
}
 
Example 15
private static void verifyEventType(EventType eventType) {
    System.out.println("Verifying event: " + eventType.getName());
    verifyDescription(eventType.getDescription());
    verifyLabel(eventType.getLabel());
    Asserts.assertNotEquals(eventType.getName(), null, "Name not allowed to be null");
    Asserts.assertTrue(eventType.getName().startsWith(EventNames.PREFIX), "OpenJDK events must start with " + EventNames.PREFIX);
    String name = eventType.getName().substring(EventNames.PREFIX.length());
    Asserts.assertFalse(isReservedKeyword(name),"Name must not be reserved keyword in the Java language (" + name + ")");
    checkCommonAbbreviations(name);
      char firstChar = name.charAt(0);
    Asserts.assertFalse(name.contains("ID"), "'ID' should not be used in name, consider using 'Id'");
    Asserts.assertTrue(Character.isAlphabetic(firstChar), "Name " + name + " must start with a character");
    Asserts.assertTrue(Character.isUpperCase(firstChar), "Name " + name + " must start with upper case letter");
    for (int i = 0; i < name.length(); i++) {
        char c = name.charAt(i);
        Asserts.assertTrue(Character.isAlphabetic(c) || Character.isDigit(c), "Name " + name + " must consists of characters or numbers, found '" + name.charAt(i) + "'");
    }
}
 
Example 16
Source Project: openjdk-jdk9   Source File: TestSmallHeap.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void verifySmallHeapSize(String gc, long expectedMaxHeap) throws Exception {
    long minMaxHeap = 4 * 1024 * 1024;
    LinkedList<String> vmOptions = new LinkedList<>();
    vmOptions.add(gc);
    vmOptions.add("-Xmx" + minMaxHeap);
    vmOptions.add("-XX:+PrintFlagsFinal");
    vmOptions.add(VerifyHeapSize.class.getName());

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(vmOptions.toArray(new String[0]));
    OutputAnalyzer analyzer = new OutputAnalyzer(pb.start());
    analyzer.shouldHaveExitValue(0);

    expectedMaxHeap = Math.max(expectedMaxHeap, minMaxHeap);
    long maxHeapSize = Long.parseLong(analyzer.firstMatch("MaxHeapSize.+=\\s+(\\d+)",1));
    long actualHeapSize = Long.parseLong(analyzer.firstMatch(VerifyHeapSize.actualMsg + "(\\d+)",1));
    Asserts.assertEQ(maxHeapSize, expectedMaxHeap);
    Asserts.assertLessThanOrEqual(actualHeapSize, maxHeapSize);
}
 
Example 17
public static void main(String[] args) throws Exception {
    WhiteBox.setWriteAllObjectSamples(true);

    try (Recording recording = new Recording()) {
        recording.enable(EventNames.OldObjectSample).withoutStackTrace().with("cutoff", "infinity");
        recording.start();

        addToTestField();

        recording.stop();

        List<RecordedEvent> events = Events.fromRecording(recording);
        Events.hasEvents(events);
        for (RecordedEvent e : events) {
            if (hasValidField(e)) {
                return;
            }
        }
        System.out.println(events);
        Asserts.fail("Could not find old object with field 'testField'");
    }
}
 
Example 18
private static void assertFrame(RecordedFrame frame) {
    int bci = frame.getBytecodeIndex();
    int line = frame.getLineNumber();
    boolean javaFrame = frame.isJavaFrame();
    RecordedMethod method = frame.getMethod();
    String type = frame.getType();
    System.out.println("*** Frame Info ***");
    System.out.println("bci=" + bci);
    System.out.println("line=" + line);
    System.out.println("type=" + type);
    System.out.println("method=" + method);
    System.out.println("***");
    Asserts.assertTrue(javaFrame, "Only Java frame are currently supported");
    Asserts.assertGreaterThanOrEqual(bci, -1);
    Asserts.assertNotNull(method, "Method should not be null");
}
 
Example 19
private static void verifyNativeEvents() throws Exception {
    Recording r = new Recording();
    r.enable(EventNames.JVMInformation);
    r.enable(EventNames.ThreadSleep);
    r.start();
    // Should trigger a sleep event even if we
    // have a low resolution clock
    Thread.sleep(200);
    r.stop();
    List<RecordedEvent> recordedEvents = Events.fromRecording(r);
    Events.hasEvents(recordedEvents);
    for (RecordedEvent re : recordedEvents) {
        Asserts.assertEquals(re.getDuration(), Duration.between(re.getStartTime(), re.getEndTime()));
        switch (re.getEventType().getName()) {
            case EventNames.JVMInformation:
                Asserts.assertTrue(re.getDuration().isZero());
                break;
            case EventNames.ThreadSleep:
                Asserts.assertTrue(!re.getDuration().isNegative() && !re.getDuration().isZero());
                break;
            default:
                Asserts.fail("Unexpected event: " + re);
                break;
        }
    }
}
 
Example 20
public static void main(String[] args) throws Throwable {
    Thread currentThread = Thread.currentThread();
    currentThread.setName(MY_THREAD_NAME);
    long expectedThreadId = currentThread.getId();

    Recording r = new Recording();
    r.start();
    SimpleEvent t = new SimpleEvent();
    t.commit();
    r.stop();
    List<RecordedEvent> events = Events.fromRecording(r);
    r.close();
    Events.hasEvents(events);
    RecordedEvent event = events.get(0);
    RecordedThread recordedThread = event.getThread();

    Asserts.assertNotNull(recordedThread);
    Asserts.assertEquals(recordedThread.getJavaName(), MY_THREAD_NAME);
    Asserts.assertEquals(recordedThread.getJavaThreadId(), expectedThreadId);
    Asserts.assertNotNull(recordedThread.getOSThreadId());
    Asserts.assertNotNull(recordedThread.getId());
    Asserts.assertEquals(recordedThread.getOSName(), MY_THREAD_NAME);
}
 
Example 21
Source Project: TencentKona-8   Source File: TestLabel.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Event
    EventType t = EventType.getEventType(LabelEvent.class);
    Asserts.assertEquals(t.getLabel(), "Event Label", "Incorrect label for event");

    // Field
    ValueDescriptor field = t.getField("labledField");
    Asserts.assertEquals(field.getLabel(), "Field Label", "Incorrect label for field");

    // Annotation
    AnnotationElement awl = Events.getAnnotationByName(t, AnnotionWithLabel.class.getName());
    Label label = awl.getAnnotation(Label.class);
    Asserts.assertEquals(label.value(), "Annotation Label", "Incorrect label for annotation");

    // Setting
    for (SettingDescriptor v: t.getSettingDescriptors()) {
        if (v.getName().equals("dummy")) {
            Label settingLabel = v.getAnnotation(Label.class);
            Asserts.assertEquals(settingLabel.value(), "Setting Label", "Incorrect label for setting");
        }
    }
}
 
Example 22
public static void main(String[] args) throws Throwable {
    ValueDescriptor vdSimple = new ValueDescriptor(String.class, "message");
    Asserts.assertNull(vdSimple.getAnnotation(Label.class), "Expected getAnnotation()==null");
    Asserts.assertEquals(0, vdSimple.getAnnotationElements().size(), "Expected getAnnotations().size() == 0");

    // Add labelA and verify we can read it back
    List<AnnotationElement> annos = new ArrayList<>();
    AnnotationElement labelA = new AnnotationElement(Label.class, "labelA");
    annos.add(labelA);
    System.out.println("labelA.getClass()" + labelA.getClass());
    ValueDescriptor vdComplex = new ValueDescriptor(String.class, "message", annos);

    final Label outLabel = vdComplex.getAnnotation(Label.class);
    Asserts.assertFalse(outLabel == null, "getLabel(Label.class) was null");
    System.out.println("outLabel.value() = " + outLabel.value());

    // Get labelA from getAnnotations() list
    Asserts.assertEquals(1, vdComplex.getAnnotationElements().size(), "Expected getAnnotations().size() == 1");
    final AnnotationElement outAnnotation = vdComplex.getAnnotationElements().get(0);
    Asserts.assertNotNull(outAnnotation, "outAnnotation was null");
    System.out.printf("Annotation: %s = %s%n", outAnnotation.getTypeName(), outAnnotation.getValue("value"));
    Asserts.assertEquals(outAnnotation, labelA, "Expected firstAnnotation == labelA");

}
 
Example 23
Source Project: openjdk-jdk8u   Source File: TestGetLabel.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventType type = EventType.getEventType(CustomEvent.class);

    SettingDescriptor plain = Events.getSetting(type, "plain");
    Asserts.assertNull(plain.getLabel());

    SettingDescriptor annotatedType = Events.getSetting(type, "annotatedType");
    Asserts.assertEquals(AnnotatedSetting.LABEL, annotatedType.getLabel());

    SettingDescriptor newName = Events.getSetting(type, "newName");
    Asserts.assertEquals(newName.getLabel(), "Annotated Method");

    SettingDescriptor overridden = Events.getSetting(type, "overridden");
    Asserts.assertNull(overridden.getLabel());

    SettingDescriptor protectedBase = Events.getSetting(type, "protectedBase");
    Asserts.assertEquals(protectedBase.getLabel(), "Protected Base");

    SettingDescriptor publicBase = Events.getSetting(type, "publicBase");
    Asserts.assertEquals(publicBase.getLabel(), AnnotatedSetting.LABEL);

    SettingDescriptor packageProtectedBase = Events.getSetting(type, "packageProtectedBase");
    Asserts.assertNull(packageProtectedBase.getLabel());

    CustomEvent.assertOnDisk((x, y) -> Objects.equals(x.getLabel(), y.getLabel()) ? 0 : 1);
}
 
Example 24
Source Project: TencentKona-8   Source File: GCEventAll.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void verifyPhaseEvents(List<GCHelper.GcBatch> batches) {
    for (GCHelper.GcBatch batch : batches) {
        for(RecordedEvent event : batch.getEvents()) {
            if (event.getEventType().getName().contains(GCHelper.pauseLevelEvent)) {
                Instant batchStartTime = batch.getEndEvent().getStartTime();
                Asserts.assertGreaterThanOrEqual(
                    event.getStartTime(), batchStartTime, "Phase startTime >= batch startTime. Event:" + event);

                // Duration for event "vm/gc/phases/pause" must be >= 1. Other phase event durations must be >= 0.
                Duration minDuration = Duration.ofNanos(GCHelper.event_phases_pause.equals(event.getEventType().getName()) ? 1 : 0);
                Duration duration = event.getDuration();
                Asserts.assertGreaterThanOrEqual(duration, minDuration, "Wrong duration. Event:" + event);
            }
        }
    }
}
 
Example 25
public static void main(String[] args) throws Exception {
    Recording r = new Recording();
    final String eventPath = EventNames.OSInformation;
    r.enable(eventPath);
    r.start();
    r.stop();

    Path dir = FileHelper.createLongDir(Paths.get("."));
    Path path = Paths.get(dir.toString(), "my.jfr");
    r.dump(path);
    r.close();

    Asserts.assertTrue(Files.exists(path), "Recording file does not exist: " + path);
    List<RecordedEvent> events = RecordingFile.readAllEvents(path);
    Asserts.assertFalse(events.isEmpty(), "No events found");
    String foundEventPath = events.get(0).getEventType().getName();
    System.out.printf("Found event: %s%n", foundEventPath);
    Asserts.assertEquals(foundEventPath, eventPath, "Wrong event");
}
 
Example 26
private void verifyAbortsCount(AbortType abortType) throws Throwable {
    AbortProvoker provoker = abortType.provoker();

    OutputAnalyzer outputAnalyzer = RTMTestBase.executeRTMTest(
            provoker,
            "-XX:+PrintPreciseRTMLockingStatistics",
            AbortProvoker.class.getName(),
            abortType.toString());

    outputAnalyzer.shouldHaveExitValue(0);

    List<RTMLockingStatistics> statistics = RTMLockingStatistics.fromString(
            provoker.getMethodWithLockName(),outputAnalyzer.getOutput());

    Asserts.assertGT(statistics.size(), 0, "VM output should contain one "
            + "rtm locking statistics entry for method "
            + provoker.getMethodWithLockName());

    RTMLockingStatistics lock = statistics.get(0);

    Asserts.assertGT(lock.getTotalAborts(), 0L,
            "RTM locking statistics should contain non zero total aborts "
            + "count");

    Asserts.assertGT(lock.getAborts(abortType), 0L, String.format(
            "RTM locking statistics should contain non zero aborts count "
            + "for abort reason %s", abortType));
}
 
Example 27
private static void verifyHeapSummary(List<RecordedEvent> events, int gcId, String when) {
    for (RecordedEvent event : events) {
        if (!Events.isEventType(event, EventNames.GCHeapSummary)) {
            continue;
        }
        if (gcId == (int)Events.assertField(event, "gcId").getValue() &&
                when.equals(Events.assertField(event, "when").getValue())) {
            System.out.printf("Found " + EventNames.GCHeapSummary + " for id=%d, when=%s%n", gcId, when);
            return;
        }
    }
    Asserts.fail(String.format("No " + EventNames.GCHeapSummary + " for id=%d, when=%s", gcId, when));
}
 
Example 28
private static ProcessBuilder prepareTestCase(int testCase) throws Exception {
    ProcessBuilder pb;

    Asserts.assertTrue(0 < testCase && testCase < 6, "testCase should be from 1 to 5");

    addVMParam("-showversion");
    addVMOptionsToCheck("MinHeapFreeRatio", "SurvivorRatio", "NewRatio");

    if (testCase < 5) {
        addVMParam("-XX:Flags=flags_file", "-XX:-PrintVMOptions");
        addProperty("shared.property", "command_line_before");
        addProperty("clb", "unique_command_line_before");
        addVMParam("-XX:MinHeapFreeRatio=7");
    }

    if (testCase < 4) {
        addVMOptionsFile(getAbsolutePathFromSource(VM_OPTION_FILE_1));
    }

    if (testCase < 3) {
        addVMParam("-XX:MinHeapFreeRatio=9", "-XX:-PrintVMOptions");
        addProperty("shared.property", "command_line_after");
        addProperty("cla", "unique_command_line_after");
    }

    /* Create ProcessBuilder after all setup is done to update environment variables */
    pb = createProcessBuilder();

    if (testCase < 2) {
        updateEnvironment(pb, JAVA_OPTIONS, "-Dshared.property=somevalue -Djo=unique_java_options "
                + "-XX:MinHeapFreeRatio=18 -Dshared.property=java_options -XX:MinHeapFreeRatio=11 -XX:+PrintVMOptions");
    }

    if (testCase < 6) {
        updateEnvironment(pb, JAVA_TOOL_OPTIONS, "-Dshared.property=qwerty -Djto=unique_java_tool_options "
                + "-XX:MinHeapFreeRatio=15 -Dshared.property=java_tool_options -XX:MinHeapFreeRatio=6 -XX:+PrintVMOptions");
    }

    return pb;
}
 
Example 29
Source Project: openjdk-jdk9   Source File: TestWBGC.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {
    obj = new Object();
    Asserts.assertFalse(wb.isObjectInOldGen(obj));
    wb.youngGC();
    wb.youngGC();
    // 2 young GC is needed to promote object into OldGen
    Asserts.assertTrue(wb.isObjectInOldGen(obj));
}
 
Example 30
Source Project: TencentKona-8   Source File: TestPrintJSON.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws Throwable {

        Path recordingFile = ExecuteHelper.createProfilingRecording().toAbsolutePath();

        OutputAnalyzer output = ExecuteHelper.jfr("print", "--json", "--stack-depth", "999", recordingFile.toString());
        String json = output.getStdout();

        // Parse JSON using Nashorn
        String statement = "var jsonObject = " + json;
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("nashorn");
        engine.eval(statement);
        JSObject o = (JSObject) engine.get("jsonObject");
        JSObject recording = (JSObject) o.getMember("recording");
        JSObject jsonEvents = (JSObject) recording.getMember("events");

        List<RecordedEvent> events = RecordingFile.readAllEvents(recordingFile);
        Collections.sort(events, (e1, e2) -> e1.getEndTime().compareTo(e2.getEndTime()));
        // Verify events are equal
        Iterator<RecordedEvent> it = events.iterator();

        for (Object jsonEvent : jsonEvents.values()) {
            RecordedEvent recordedEvent = it.next();
            String typeName = recordedEvent.getEventType().getName();
            Asserts.assertEquals(typeName, ((JSObject) jsonEvent).getMember("type").toString());
            assertEquals(jsonEvent, recordedEvent);
        }
        Asserts.assertFalse(events.size() != jsonEvents.values().size(), "Incorrect number of events");
    }