Java Code Examples for jdk.test.lib.Asserts#assertNull()

The following examples show how to use jdk.test.lib.Asserts#assertNull() . 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: TestGetLabel.java    From openjdk-jdk8u with 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 2
Source File: TestTimeDuration.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 {
    Recording r = new Recording();
    final Duration duration = Duration.ofMillis(30000);

    r.setDuration(duration);
    Asserts.assertNull(r.getStartTime(), "getStartTime() not null before start");
    Asserts.assertNull(r.getStopTime(), "getStopTime() not null before start");

    final Instant beforeStart = Instant.now();
    r.start();
    final Instant afterStart = Instant.now();

    Asserts.assertNotNull(r.getStartTime(), "getStartTime() null after start()");
    Asserts.assertGreaterThanOrEqual(r.getStartTime(), beforeStart, "getStartTime() < beforeStart");
    Asserts.assertLessThanOrEqual(r.getStartTime(), afterStart, "getStartTime() > afterStart");

    Asserts.assertNotNull(r.getStopTime(), "getStopTime() null after start with duration");
    Asserts.assertGreaterThanOrEqual(r.getStopTime(), beforeStart.plus(duration), "getStopTime() < beforeStart + duration");
    Asserts.assertLessThanOrEqual(r.getStopTime(), afterStart.plus(duration), "getStopTime() > afterStart + duration");

    r.close();
}
 
Example 3
Source File: TestGetId.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 {
    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 4
Source File: TestCreateConfigFromReader.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void testOkConfig() throws Exception {
    File settingsFile = new File(DIR, "settings.jfc");
    if(!settingsFile.exists()) throw new RuntimeException("File " + settingsFile.getAbsolutePath() +  " not found ");

        FileReader reader = new FileReader(settingsFile);

        Configuration config = Configuration.create(reader);
        Map<String, String> settings = config.getSettings();

        Asserts.assertEquals(4, settings.size(), "Settings size differes from the expected size");
        String[] keys = {"enabled", "stackTrace", "threshold", "custom"};
        String[] vals = {"true", "true", "1 ms", "5"};
        for(int i=0; i<keys.length; ++i) {
            String fullKey = EventNames.JavaMonitorWait + "#" + keys[i];
            Asserts.assertEquals(vals[i], settings.get(fullKey), "Settings value differs from the expected: " + keys[i]);
        }
        Asserts.assertEquals(null, settings.get("doesNotExists"), "Error getting on-existent setting");

        Asserts.assertEquals("Oracle", config.getProvider(), "Configuration provider differs from the expected");
        Asserts.assertEquals("TestSettings", config.getLabel(), "Configuration label differs from the expected");
        Asserts.assertEquals("SampleConfiguration", config.getDescription(), "Configuration description differs from the expected");
        Asserts.assertNull(config.getName(), "Name should be null if created from reader");
}
 
Example 5
Source File: TestGetAnnotation.java    From TencentKona-8 with 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 annotatedType = Events.getSetting(type, "annotatedType");
    Label al = annotatedType.getAnnotation(Label.class);
    Asserts.assertNull(al); // we should not inherit annotation from type

    Description ad = annotatedType.getAnnotation(Description.class);
    Asserts.assertNull(ad); // we should not inherit annotation from type

    Timestamp at = annotatedType.getAnnotation(Timestamp.class);
    Asserts.assertNull(at); // we should not inherit annotation from type

    SettingDescriptor newName = Events.getSetting(type, "newName");
    Label nl = newName.getAnnotation(Label.class);
    Asserts.assertEquals(nl.value(), "Annotated Method");

    Description nd = newName.getAnnotation(Description.class);
    Asserts.assertEquals(nd.value(), "Description of an annotated method");

    Timespan nt = newName.getAnnotation(Timespan.class);
    Asserts.assertEquals(nt.value(), Timespan.NANOSECONDS);
}
 
Example 6
Source File: TestConstructor.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 {
    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 7
Source File: TestTimeDuration.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 {
    Recording r = new Recording();
    final Duration duration = Duration.ofMillis(30000);

    r.setDuration(duration);
    Asserts.assertNull(r.getStartTime(), "getStartTime() not null before start");
    Asserts.assertNull(r.getStopTime(), "getStopTime() not null before start");

    final Instant beforeStart = Instant.now();
    r.start();
    final Instant afterStart = Instant.now();

    Asserts.assertNotNull(r.getStartTime(), "getStartTime() null after start()");
    Asserts.assertGreaterThanOrEqual(r.getStartTime(), beforeStart, "getStartTime() < beforeStart");
    Asserts.assertLessThanOrEqual(r.getStartTime(), afterStart, "getStartTime() > afterStart");

    Asserts.assertNotNull(r.getStopTime(), "getStopTime() null after start with duration");
    Asserts.assertGreaterThanOrEqual(r.getStopTime(), beforeStart.plus(duration), "getStopTime() < beforeStart + duration");
    Asserts.assertLessThanOrEqual(r.getStopTime(), afterStart.plus(duration), "getStopTime() > afterStart + duration");

    r.close();
}
 
Example 8
Source File: GetClassInitializerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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 9
Source File: TestGetId.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 {
    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 10
Source File: ResolveMethodTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(TestCase tcase) throws NoSuchMethodException {
    System.out.println(tcase);
    HotSpotResolvedJavaMethod metaspaceMethod = CTVMUtilities
            .getResolvedMethod(tcase.holder,
                    tcase.holder.getDeclaredMethod(tcase.methodName));
    HotSpotResolvedObjectType holderMetaspace = CompilerToVMHelper
            .lookupType(Utils.toJVMTypeSignature(tcase.holder),
                    getClass(), /* resolve = */ true);
    HotSpotResolvedObjectType callerMetaspace = CompilerToVMHelper
            .lookupType(Utils.toJVMTypeSignature(tcase.caller),
                    getClass(), /* resolve = */ true);
    HotSpotResolvedObjectType receiverMetaspace = CompilerToVMHelper
            .lookupType(Utils.toJVMTypeSignature(tcase.receiver),
                    getClass(), /* resolve = */ true);

    // Can only resolve methods on a linked class so force initialization
    receiverMetaspace.initialize();
    HotSpotResolvedJavaMethod resolvedMetaspaceMethod
            = CompilerToVMHelper.resolveMethod(receiverMetaspace,
                    metaspaceMethod, callerMetaspace);
    if (tcase.isPositive) {
        Asserts.assertNotNull(resolvedMetaspaceMethod,
                "Unexpected null resolved method value for "
                        + tcase.methodName);
        Asserts.assertEQ(metaspaceMethod.getName(), tcase.methodName,
                "Reflection and c2vm method names doesn't match");
    } else {
        Asserts.assertNull(resolvedMetaspaceMethod,
                "Method unexpectedly resolved");
    }
}
 
Example 11
Source File: LookupTypeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(TestCase tcase) {
    System.out.println(tcase);
    HotSpotResolvedObjectType metaspaceKlass;
    try {
        metaspaceKlass = CompilerToVMHelper.lookupType(tcase.className,
                tcase.accessing, tcase.resolve);
    } catch (Throwable t) {
        Asserts.assertNotNull(tcase.expectedException,
                "Assumed no exception, but got " + t);
        Asserts.assertFalse(tcase.isPositive,
                "Got unexpected exception " + t);
        Asserts.assertEQ(t.getClass(), tcase.expectedException,
                "Unexpected exception");
        // passed
        return;
    }
    if (tcase.expectedException != null) {
        throw new AssertionError("Expected exception was not thrown: "
                + tcase.expectedException.getName());
    }
    if (tcase.isPositive) {
        Asserts.assertNotNull(metaspaceKlass,
                "Unexpected null metaspace klass");
        Asserts.assertEQ(metaspaceKlass.getName(), tcase.className,
                "Got unexpected resolved class name");
    } else {
        Asserts.assertNull(metaspaceKlass, "Unexpected metaspace klass");
    }
}
 
Example 12
Source File: TestClassLoadEvent.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Recording recording = new Recording();
    recording.enable(EVENT_NAME).withThreshold(Duration.ofMillis(0));
    TestClassLoader cl = new TestClassLoader();
    recording.start();
    cl.loadClass(TEST_CLASS_NAME);
    recording.stop();

    List<RecordedEvent> events = Events.fromRecording(recording);
    boolean isLoaded = false;
    for (RecordedEvent event : events) {
        RecordedClass loadedClass = event.getValue("loadedClass");
        if (SEARCH_CLASS_NAME.equals(loadedClass.getName())) {
            System.out.println(event);
            //neither package nor module events are available at 8
            //Events.assertClassPackage(loadedClass, SEARCH_PACKAGE_NAME);
            //Events.assertClassModule(loadedClass, SEARCH_MODULE_NAME);
            RecordedClassLoader initiatingClassLoader = event.getValue("initiatingClassLoader");
            Asserts.assertEquals(cl.getClass().getName(), initiatingClassLoader.getType().getName(),
                "Expected type " + cl.getClass().getName() + ", got type " + initiatingClassLoader.getType().getName());
            RecordedClassLoader definingClassLoader = loadedClass.getClassLoader();
            Asserts.assertEquals(BOOT_CLASS_LOADER_NAME, definingClassLoader.getName(),
                "Expected boot loader to be the defining class loader");
            Asserts.assertNull(definingClassLoader.getType(), "boot loader should not have a type");
            isLoaded = true;
        }
    }
    Asserts.assertTrue(isLoaded, "No class load event found for class " + SEARCH_CLASS_NAME);
}
 
Example 13
Source File: TestDestToDiskFalse.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
    final Path dest = Paths.get(".", "my.jfr");
    Recording r = new Recording();
    SimpleEventHelper.enable(r, true);
    r.setToDisk(false);
    r.setDestination(dest);
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set destination");
    r.start();
    SimpleEventHelper.createEvent(0);
    r.stop();

    // setToDisk(false) should not effect setDestination.
    // We should still get a file when the recording stops.
    Asserts.assertTrue(Files.exists(dest), "No recording file: " + dest);
    System.out.printf("File size=%d, getSize()=%d%n", Files.size(dest), r.getSize());
    Asserts.assertNotEquals(Files.size(dest), 0L, "File length 0. Should at least be some bytes");

    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No event found");
    System.out.printf("Found event %s%n", events.get(0).getEventType().getName());

    assertEquals(r.getSize(), 0L, "getSize() should return 0, chunks should have been released at stop");
    // getDestination() should return null after recording have been written to file.
    Asserts.assertNull(r.getDestination(), "getDestination() should return null after file created");

    r.close();
}
 
Example 14
Source File: GetNextStackFrameTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Walks through whole stack and checks that every frame could be found
 * while going down the stack till the end
 */
private void walkThrough() {
    // Check that we would get a frame 4 starting from the topmost frame
    HotSpotStackFrameReference nextStackFrame = checkNextFrameFor(
            null /* topmost frame */,
            new ResolvedJavaMethod[] {FRAME4_METHOD},
            FRAME4_METHOD, 0);
    // Check that we would get a frame 3 starting from frame 4 when we try
    // to search one of the next two frames
    nextStackFrame = checkNextFrameFor(nextStackFrame,
            new ResolvedJavaMethod[] {FRAME3_METHOD,
                    FRAME2_METHOD},
            FRAME3_METHOD, 0);
    // Check that we would get a frame 1
    nextStackFrame = checkNextFrameFor(nextStackFrame,
            new ResolvedJavaMethod[] {FRAME1_METHOD},
            FRAME1_METHOD, 0);
    // Check that we would skip (RECURSION_AMOUNT - 1) methods and find a
    // recursionFrame starting from frame 1
    nextStackFrame = checkNextFrameFor(nextStackFrame,
            new ResolvedJavaMethod[] {REC_FRAME_METHOD},
            REC_FRAME_METHOD, RECURSION_AMOUNT - 1);
    // Check that we would get a Thread::run method frame;
    nextStackFrame = checkNextFrameFor(nextStackFrame,
            new ResolvedJavaMethod[] {RUN_METHOD},
            RUN_METHOD, 0);
    // Check that there are no more frames after thread's run method
    nextStackFrame = CompilerToVMHelper.getNextStackFrame(nextStackFrame,
            null /* any */, 0);
    Asserts.assertNull(nextStackFrame,
            "Found stack frame after Thread::run");
}
 
Example 15
Source File: TestRTMLockingThreshold.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void verifyLockingThreshold(int lockingThreshold,
        boolean useStackLock) throws Throwable {
    CompilableTest test = new Test();

    int abortThreshold = Math.max(lockingThreshold / 2,
            TestRTMLockingThreshold.MIN_ABORT_THRESHOLD);

    OutputAnalyzer outputAnalyzer = RTMTestBase.executeRTMTest(
            test,
            "-XX:CompileThreshold=1",
            CommandLineOptionTest.prepareBooleanFlag("UseRTMForStackLocks",
                    useStackLock),
            "-XX:+UseRTMDeopt",
            "-XX:RTMTotalCountIncrRate=1",
            "-XX:RTMRetryCount=0",
            CommandLineOptionTest.prepareNumericFlag("RTMAbortThreshold",
                    abortThreshold),
            CommandLineOptionTest.prepareNumericFlag("RTMLockingThreshold",
                    lockingThreshold),
            "-XX:RTMAbortRatio=100",
            "-XX:+PrintPreciseRTMLockingStatistics",
            Test.class.getName(),
            Boolean.toString(!useStackLock),
            Integer.toString(lockingThreshold)
    );

    outputAnalyzer.shouldHaveExitValue(0);

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

    Asserts.assertEQ(statistics.size(), 2, "VM output should contain two "
            + "RTM locking statistics entries.");

    /**
     * If RTMLockingThreshold==0, then we have to make at least 1 call.
     */
    long expectedValue = lockingThreshold;
    if (expectedValue == 0) {
        expectedValue++;
    }

    RTMLockingStatistics statBeforeDeopt = null;
    for (RTMLockingStatistics s : statistics) {
        if (s.getTotalLocks() == expectedValue) {
            Asserts.assertNull(statBeforeDeopt,
                    "Only one statistics entry should contain aborts");
            statBeforeDeopt = s;
        }
    }

    Asserts.assertNotNull(statBeforeDeopt, "There should be exactly one "
            + "statistics entry corresponding to ProfileRTM state.");
}
 
Example 16
Source File: TestThreadParkEvent.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
static RecordedEvent testPark(Consumer<Blocker> parkOperation, Thread.State threadState) throws Exception {

        final CountDownLatch stop = new CountDownLatch(1);
        final Blocker blocker = new Blocker();
        TestThread parkThread = new TestThread(new Runnable() {
            public void run() {
                while (stop.getCount() > 0) {
                    parkOperation.accept(blocker);
                }
            }
        });

        Recording recording = new Recording();
        recording.enable(EVENT_NAME).withThreshold(Duration.ofMillis(THRESHOLD_MILLIS));
        try {
            recording.start();
            parkThread.start();
            ThreadMXBeanTool.waitUntilBlockingOnObject(parkThread, threadState, blocker);
            // sleep so we know the event is recorded
            Thread.sleep(2 * THRESHOLD_MILLIS);
        } finally {
            stop.countDown();
            LockSupport.unpark(parkThread);
            parkThread.join();
            recording.stop();
        }
        List<RecordedEvent> events = Events.fromRecording(recording);
        Events.hasEvents(events);
        RecordedEvent foundEvent = null;
        for (RecordedEvent event : events) {
            System.out.println("Event:" + event);
            String klassName = Events.assertField(event, "parkedClass.name").notNull().getValue();
            if (klassName.equals(blocker.getClass().getName().replace('.', '/'))) {
                Asserts.assertNull(foundEvent , "Found more than 1 event");
                Events.assertField(event, "address").notEqual(0L);
                Events.assertEventThread(event, parkThread);
                foundEvent = event;
            }
        }
        Asserts.assertNotNull(foundEvent, "Correct event not found");
        return foundEvent;
    }
 
Example 17
Source File: TestOwnCommit.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Throwable {
   Recording r = new Recording();
    r.enable(MyEvent.class);

    r.start();

    MyEvent event = new MyEvent();
    event.begin();
    event.begin = 10;
    event.duration = Instant.now();
    MyEvent.startTime = 20;
    event.shouldCommit = "shouldCommit";
    MyEvent.set = 30;
    event.end();
    event.commit();

    // Verify that our methods have not been removed by transformation.
    int id = 0;
    event.begin(++id);
    Asserts.assertEquals(id, staticTestValue, "EventWithBegin failed to set value");
    event.end(++id);
    Asserts.assertEquals(id, staticTestValue, "EventWithEnd failed to set value");
    event.commit(++id);
    Asserts.assertEquals(id, staticTestValue, "EventWithCommit failed to set value");
    event.shouldCommit(++id);
    Asserts.assertEquals(id, staticTestValue, "EventWithShouldCommit failed to set value");
    event.set(++id);
    Asserts.assertEquals(id, staticTestValue, "EventWithSet failed to set value");

    r.stop();

    Iterator<RecordedEvent> it = Events.fromRecording(r).iterator();
    Asserts.assertTrue(it.hasNext(), "No events");
    RecordedEvent recordedEvent = it.next();
    Asserts.assertTrue(Events.isEventType(recordedEvent, MyEvent.class.getName()));
    Events.assertField(recordedEvent, "begin").equal(10L);
    Events.assertField(recordedEvent, "shouldCommit").equal("shouldCommit");
    Events.assertField(recordedEvent, "startTime");
    Events.assertField(recordedEvent, "duration");
    Asserts.assertNull(recordedEvent.getEventType().getField("set")); // static not supported
    Asserts.assertFalse(it.hasNext(), "More than 1 event");

    r.close();
}
 
Example 18
Source File: DrbgParametersSpec.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte[] p, np1, np2;

        // Capability
        Asserts.assertTrue(PR_AND_RESEED.supportsPredictionResistance());
        Asserts.assertTrue(PR_AND_RESEED.supportsReseeding());
        Asserts.assertFalse(RESEED_ONLY.supportsPredictionResistance());
        Asserts.assertTrue(RESEED_ONLY.supportsReseeding());
        Asserts.assertFalse(NONE.supportsPredictionResistance());
        Asserts.assertFalse(NONE.supportsReseeding());

        // Instantiation
        p = "Instantiation".getBytes();
        DrbgParameters.Instantiation ins = DrbgParameters
                .instantiation(192, RESEED_ONLY, p);
        Asserts.assertTrue(ins.getStrength() == 192);
        Asserts.assertTrue(ins.getCapability() == RESEED_ONLY);
        np1 = ins.getPersonalizationString();
        np2 = ins.getPersonalizationString();
        // Getter outputs have same content but not the same object
        Asserts.assertTrue(Arrays.equals(np1, p));
        Asserts.assertTrue(Arrays.equals(np2, p));
        Asserts.assertNE(np1, np2);
        // Changes to original input has no affect on object
        p[0] = 'X';
        np2 = ins.getPersonalizationString();
        Asserts.assertTrue(Arrays.equals(np1, np2));

        ins = DrbgParameters.instantiation(-1, NONE, null);
        Asserts.assertNull(ins.getPersonalizationString());

        iae(() -> DrbgParameters.instantiation(-2, NONE, null));
        npe(() -> DrbgParameters.instantiation(-1, null, null));

        // NextBytes
        p = "NextBytes".getBytes();
        DrbgParameters.NextBytes nb = DrbgParameters
                .nextBytes(192, true, p);
        Asserts.assertTrue(nb.getStrength() == 192);
        Asserts.assertTrue(nb.getPredictionResistance());
        np1 = nb.getAdditionalInput();
        np2 = nb.getAdditionalInput();
        // Getter outputs have same content but not the same object
        Asserts.assertTrue(Arrays.equals(np1, p));
        Asserts.assertTrue(Arrays.equals(np2, p));
        Asserts.assertNE(np1, np2);
        // Changes to original input has no affect on object
        p[0] = 'X';
        np2 = nb.getAdditionalInput();
        Asserts.assertTrue(Arrays.equals(np1, np2));

        iae(() -> DrbgParameters.nextBytes(-2, false, null));

        // Reseed
        p = "Reseed".getBytes();
        DrbgParameters.Reseed rs = DrbgParameters
                .reseed(true, p);
        Asserts.assertTrue(rs.getPredictionResistance());
        np1 = rs.getAdditionalInput();
        np2 = rs.getAdditionalInput();
        // Getter outputs have same content but not the same object
        Asserts.assertTrue(Arrays.equals(np1, p));
        Asserts.assertTrue(Arrays.equals(np2, p));
        Asserts.assertNE(np1, np2);
        // Changes to original input has no affect on object
        p[0] = 'X';
        np2 = rs.getAdditionalInput();
        Asserts.assertTrue(Arrays.equals(np1, np2));
    }
 
Example 19
Source File: TestThreadParkEvent.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
static RecordedEvent testPark(Consumer<Blocker> parkOperation, Thread.State threadState) throws Exception {

        final CountDownLatch stop = new CountDownLatch(1);
        final Blocker blocker = new Blocker();
        TestThread parkThread = new TestThread(new Runnable() {
            public void run() {
                while (stop.getCount() > 0) {
                    parkOperation.accept(blocker);
                }
            }
        });

        Recording recording = new Recording();
        recording.enable(EVENT_NAME).withThreshold(Duration.ofMillis(THRESHOLD_MILLIS));
        try {
            recording.start();
            parkThread.start();
            ThreadMXBeanTool.waitUntilBlockingOnObject(parkThread, threadState, blocker);
            // sleep so we know the event is recorded
            Thread.sleep(2 * THRESHOLD_MILLIS);
        } finally {
            stop.countDown();
            LockSupport.unpark(parkThread);
            parkThread.join();
            recording.stop();
        }
        List<RecordedEvent> events = Events.fromRecording(recording);
        Events.hasEvents(events);
        RecordedEvent foundEvent = null;
        for (RecordedEvent event : events) {
            System.out.println("Event:" + event);
            String klassName = Events.assertField(event, "parkedClass.name").notNull().getValue();
            if (klassName.equals(blocker.getClass().getName().replace('.', '/'))) {
                Asserts.assertNull(foundEvent , "Found more than 1 event");
                Events.assertField(event, "address").notEqual(0L);
                Events.assertEventThread(event, parkThread);
                foundEvent = event;
            }
        }
        Asserts.assertNotNull(foundEvent, "Correct event not found");
        return foundEvent;
    }
 
Example 20
Source File: TestDestInvalid.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Recording r = new Recording();
    r.enable(EventNames.OSInformation);
    r.setToDisk(true);

    Asserts.assertNull(r.getDestination(), "dest not null by default");

    // Set destination to empty path (same as curr dir, not a file)
    verifyException(()->{r.setDestination(Paths.get(""));}, "No exception for setDestination(\"\")", IOException.class);
    System.out.println("1 destination: " + r.getDestination());
    Asserts.assertNull(r.getDestination(), "default dest not null after failed setDest");

    // Set dest to a valid path. This should be kept when a new setDest fails.
    Path dest = Paths.get(".", "my.jfr");
    r.setDestination(dest);
    System.out.println("2 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Null is allowed for setDestination()
    r.setDestination(null);
    System.out.println("3 destination: " + r.getDestination());
    Asserts.assertNull(r.getDestination(), "dest not null after setDest(null)");

    // Reset dest to correct value and make ssure it is not overwritten
    r.setDestination(dest);
    System.out.println("4 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Set destination to an existing dir. Old dest is saved.
    verifyException(()->{r.setDestination(Paths.get("."));}, "No exception for setDestination(.)", IOException.class);
    System.out.println("5 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Set destination to a non-existing dir. Old dest is saved.
    verifyException(()->{r.setDestination(Paths.get(".", "missingdir", "my.jfr"));}, "No exception for setDestination(dirNotExists)", IOException.class);
    System.out.println("6 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Verify that it works with the old setDest value.
    r.start();
    r.stop();
    r.close();
    Asserts.assertTrue(Files.exists(dest), "No recording file: " + dest);
    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No event found");
    System.out.printf("Found event %s in %s%n", events.get(0).getEventType().getName(), dest.toString());
}