Example usage for org.apache.commons.lang.mutable MutableInt getValue

List of usage examples for org.apache.commons.lang.mutable MutableInt getValue

Introduction

In this page you can find the example usage for org.apache.commons.lang.mutable MutableInt getValue.

Prototype

public Object getValue() 

Source Link

Document

Gets the value as a Integer instance.

Usage

From source file:com.topekalabs.bigmachine.lib.app.SimpleContinuationTest.java

@Test
public void simpleTest() {
    MutableInt context = new MutableInt();
    Continuation c = Continuation.startWith(new SimpleContinuationRunnable(), context);

    Assert.assertEquals("The value of the context was not set properly", SimpleContinuationRunnable.FIRST_VALUE,
            context.getValue());

    Continuation.continueWith(c, context);

    Assert.assertEquals("The value of the context was not set properly",
            SimpleContinuationRunnable.SECOND_VALUE, context.getValue());
}

From source file:com.topekalabs.bigmachine.lib.app.ContinuationSerializationTest.java

@Test
public void simpleSerializationTest() throws Exception {
    MutableInt context = new MutableInt();
    Continuation c = Continuation.startWith(new SimpleContinuationRunnable(), context);
    logger.debug("Is serializable: {}", c.isSerializable());

    Assert.assertEquals("The value of the context was not set properly", SimpleContinuationRunnable.FIRST_VALUE,
            context.getValue());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(c);//from   w w  w  .j a  v a  2  s .  co m
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    c = (Continuation) ois.readObject();
    ois.close();

    Continuation.continueWith(c, context);

    Assert.assertEquals("The value of the context was not set properly",
            SimpleContinuationRunnable.SECOND_VALUE, context.getValue());
}

From source file:io.cloudslang.lang.tools.build.tester.parallel.services.TestCaseEventDispatchServiceTest.java

@Test
public void notifyListenersAllEventTypes() throws InterruptedException {
    final MutableInt mutableInt = new MutableInt(0);
    final MutableBoolean mutableBoolean = new MutableBoolean(false);
    final String failureMessage = "message";
    final RuntimeException ex = new RuntimeException("ex");

    ISlangTestCaseEventListener listenerIncrement = new ISlangTestCaseEventListener() {
        @Override//from   w w w .j  av a 2s.  c  o m
        public synchronized void onEvent(SlangTestCaseEvent event) {
            mutableInt.increment();
            Object value = mutableInt.getValue();
            if (value.equals(1)) {
                assertEquals(BeginSlangTestCaseEvent.class, event.getClass());
            } else if (value.equals(2)) {
                assertEquals(FailedSlangTestCaseEvent.class, event.getClass());
                assertEquals(failureMessage, ((FailedSlangTestCaseEvent) event).getFailureReason());
                assertEquals(ex, ((FailedSlangTestCaseEvent) event).getFailureException());
            } else if (value.equals(3)) {
                assertEquals(PassedSlangTestCaseEvent.class, event.getClass());
            } else if (value.equals(4)) {
                assertEquals(SkippedSlangTestCaseEvent.class, event.getClass());
            } else if (value.equals(5)) {
                assertEquals(SlangTestCaseEvent.class, event.getClass());
                mutableBoolean.setValue(true);
            }
        }
    };

    TestCaseEventDispatchService localTestCaseEventDispatchService = new TestCaseEventDispatchService();
    localTestCaseEventDispatchService.initializeListeners();
    localTestCaseEventDispatchService.registerListener(listenerIncrement);

    SlangTestCase testCase = new SlangTestCase("name", null, null, null, null, null, null, null, null);
    localTestCaseEventDispatchService.notifyListeners(new BeginSlangTestCaseEvent(testCase));
    localTestCaseEventDispatchService
            .notifyListeners(new FailedSlangTestCaseEvent(testCase, failureMessage, ex));
    localTestCaseEventDispatchService.notifyListeners(new PassedSlangTestCaseEvent(testCase));
    localTestCaseEventDispatchService.notifyListeners(new SkippedSlangTestCaseEvent(testCase));
    localTestCaseEventDispatchService.notifyListeners(new SlangTestCaseEvent(testCase));

    while (mutableBoolean.isFalse()) {
        Thread.sleep(50);
    }
    // Checks that all listeners are called, order is not important
    assertEquals(5, mutableInt.getValue());
}

From source file:com.evolveum.midpoint.testing.longtest.TestLdap.java

private void assertOpenDjAccountShadows(int expected, boolean raw, Task task, OperationResult result)
        throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
        SecurityViolationException {/* w  w w .jav a2  s.com*/
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID,
            new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), prismContext);

    final MutableInt count = new MutableInt(0);
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            count.increment();
            display("Found", shadow);
            return true;
        }
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
    assertEquals("Unexpected number of search results (raw=" + raw + ")", expected, count.getValue());
}

From source file:com.evolveum.midpoint.testing.longtest.TestLdap.java

@Test
public void test800BigLdapSearch() throws Exception {
    final String TEST_NAME = "test800BigLdapSearch";
    TestUtil.displayTestTile(this, TEST_NAME);

    // GIVEN//  w w w  .  j  av  a  2  s . c  o m

    loadEntries("a");

    Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME);
    task.setOwner(getUser(USER_ADMINISTRATOR_OID));
    OperationResult result = task.getResult();

    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID,
            new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), prismContext);

    final MutableInt count = new MutableInt(0);
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            count.increment();
            display("Found", shadow);
            return true;
        }
    };

    // WHEN
    TestUtil.displayWhen(TEST_NAME);
    modelService.searchObjectsIterative(ShadowType.class, query, handler, null, task, result);

    // THEN
    TestUtil.displayThen(TEST_NAME);
    result.computeStatus();
    TestUtil.assertSuccess(result);

    // THEN
    TestUtil.displayThen(TEST_NAME);

    assertEquals("Unexpected number of search results", NUM_LDAP_ENTRIES + 8, count.getValue());
}

From source file:io.cloudslang.lang.tools.build.tester.parallel.services.TestCaseEventDispatchServiceTest.java

@Test
public void notifyListenersSuccess() throws InterruptedException {
    final MutableInt mutableInt = new MutableInt(0);
    final MutableBoolean mutableBoolean = new MutableBoolean(false);

    ISlangTestCaseEventListener listenerIncrement = new ISlangTestCaseEventListener() {
        @Override// w  w  w . j  ava2 s.co  m
        public void onEvent(SlangTestCaseEvent event) {
            mutableInt.increment();
        }
    };

    ISlangTestCaseEventListener listenerIncrementTwice = new ISlangTestCaseEventListener() {
        @Override
        public void onEvent(SlangTestCaseEvent event) {
            mutableInt.add(2);
            mutableBoolean.setValue(true);
        }
    };

    TestCaseEventDispatchService localTestCaseEventDispatchService = new TestCaseEventDispatchService();
    localTestCaseEventDispatchService.initializeListeners();
    localTestCaseEventDispatchService.registerListener(listenerIncrement);
    localTestCaseEventDispatchService.registerListener(listenerIncrementTwice);

    localTestCaseEventDispatchService.notifyListeners(
            new SlangTestCaseEvent(new SlangTestCase("name", null, null, null, null, null, null, null, null)));

    while (mutableBoolean.isFalse()) {
        Thread.sleep(50);
    }
    // Checks that all listeners are called, order is not important
    assertEquals(3, mutableInt.getValue());
}

From source file:com.hp.alm.ali.idea.rest.TroubleShootServiceTest.java

@Test
public void testNotification() throws IOException {
    File file = File.createTempFile("trouble", "");
    troubleShootService.start(file);/*  w ww. j a  va2  s . c om*/

    final MessageBusConnection connection = getProject().getMessageBus().connect();
    final MutableInt times = new MutableInt(0);

    connection.subscribe(Notifications.TOPIC, new Notifications() {
        @Override
        public void notify(@NotNull Notification notification) {
            Assert.assertEquals("HP ALM Integration", notification.getGroupId());
            Assert.assertEquals("Troubleshooting mode is on and all REST communication is being tracked.",
                    notification.getTitle());
            Assert.assertEquals(NotificationType.INFORMATION, notification.getType());
            times.add(1);
        }

        @Override
        public void register(@NotNull String groupDisplayName,
                @NotNull NotificationDisplayType defaultDisplayType) {
        }

        @Override
        public void register(@NotNull String groupDisplayName,
                @NotNull NotificationDisplayType defaultDisplayType, boolean shouldLog) {
        }

        // needed for 13, adapter class not defined in 12.1.1
        public void register(@NotNull String groupDisplayName,
                @NotNull NotificationDisplayType defaultDisplayType, boolean shouldLog,
                boolean shouldReadAloud) {
        }
    });

    troubleShootService._setNotificationDelay(60000);
    for (int i = 0; i < 100; i++) {
        troubleShootService.request(getProject(), "GET", new MyInputData("<foo/>"), "defects/{0}", "0");
    }
    testApplication.waitForBackgroundActivityToFinish();
    // only 1 notification due to notification delay
    Assert.assertEquals(1, times.getValue());

    troubleShootService._setNotificationDelay(0);
    for (int i = 0; i < 100; i++) {
        troubleShootService.request(getProject(), "GET", new MyInputData("<foo/>"), "defects/{0}", "0");
    }
    testApplication.waitForBackgroundActivityToFinish();
    // additional 10 notifications
    Assert.assertEquals(11, times.getValue());

    connection.disconnect();
    troubleShootService.stop();
}

From source file:com.evolveum.midpoint.model.intest.sync.TestImportRecon.java

private void assertDummyAccountShadows(int expected, boolean raw, Task task, OperationResult result)
        throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
        SecurityViolationException {//from   w  ww. j a v  a 2 s. co m
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID,
            new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext);

    final MutableInt count = new MutableInt(0);
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            count.increment();
            display("Found", shadow);
            return true;
        }
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
    assertEquals("Unexpected number of search results (raw=" + raw + ")", expected, count.getValue());
}

From source file:org.alfresco.repo.attributes.AttributeServiceTest.java

/**
 * Checks that {@link AttributeService#getAttributes(AttributeQueryCallback, Serializable...) AttributeService.getAttributes}
 * works.  This includes coverage of <a href=https://issues.alfresco.com/jira/browse/MNT-9112>MNT-9112</a>.
 *//*from   ww w.  ja v a 2s.com*/
public void testGetAttributes() throws Exception {
    attributeService.setAttribute(VALUE_AAA_STRING, KEY_AAA);
    attributeService.setAttribute(VALUE_AAB_STRING, KEY_AAB);
    attributeService.setAttribute(VALUE_AAC_STRING, KEY_AAC);

    final List<Serializable> results = new ArrayList<Serializable>();
    final MutableInt counter = new MutableInt();
    final MutableInt max = new MutableInt(3);
    AttributeQueryCallback callback = new AttributeQueryCallback() {
        @Override
        public boolean handleAttribute(Long id, Serializable value, Serializable[] keys) {
            counter.increment();
            results.add(value);
            if (counter.intValue() == max.intValue()) {
                return false;
            } else {
                return true;
            }
        }
    };

    counter.setValue(0);
    max.setValue(3);
    results.clear();
    attributeService.getAttributes(callback, KEY_A);
    assertEquals(3, results.size());
    assertEquals(3, counter.getValue());

    counter.setValue(0);
    max.setValue(2);
    results.clear();
    attributeService.getAttributes(callback, KEY_A);
    assertEquals(2, results.size());
    assertEquals(2, counter.getValue());
}

From source file:org.apache.bookkeeper.replication.AuditorLedgerCheckerTest.java

@Test
public void testTriggerAuditorWithNoPendingAuditTask() throws Exception {
    // wait for a second so that the initial periodic check finishes
    Thread.sleep(1000);//from  w  w  w  .jav  a 2s . c o  m
    int lostBookieRecoveryDelayConfValue = baseConf.getLostBookieRecoveryDelay();
    Auditor auditorBookiesAuditor = getAuditorBookiesAuditor();
    Future<?> auditTask = auditorBookiesAuditor.getAuditTask();
    int lostBookieRecoveryDelayBeforeChange = auditorBookiesAuditor.getLostBookieRecoveryDelayBeforeChange();
    Assert.assertEquals("auditTask is supposed to be null", null, auditTask);
    Assert.assertEquals(
            "lostBookieRecoveryDelayBeforeChange of Auditor should be equal to BaseConf's lostBookieRecoveryDelay",
            lostBookieRecoveryDelayConfValue, lostBookieRecoveryDelayBeforeChange);

    @Cleanup("shutdown")
    OrderedScheduler scheduler = OrderedScheduler.newSchedulerBuilder().name("test-scheduler").numThreads(1)
            .build();
    @Cleanup
    MetadataClientDriver driver = MetadataDrivers
            .getClientDriver(URI.create(baseClientConf.getMetadataServiceUri()));
    driver.initialize(baseClientConf, scheduler, NullStatsLogger.INSTANCE, Optional.of(zkc));

    // there is no easy way to validate if the Auditor has executed Audit process (Auditor.startAudit),
    // without shuttingdown Bookie. To test if by resetting LostBookieRecoveryDelay it does Auditing
    // even when there is no pending AuditTask, following approach is needed.

    // Here we are creating few ledgers ledgermetadata with non-existing bookies as its ensemble.
    // When Auditor does audit it recognizes these ledgers as underreplicated and mark them as
    // under-replicated, since these bookies are not available.
    int numofledgers = 5;
    Random rand = new Random();
    for (int i = 0; i < numofledgers; i++) {
        LedgerMetadata metadata = new LedgerMetadata(3, 2, 2, DigestType.CRC32, "passwd".getBytes());
        ArrayList<BookieSocketAddress> ensemble = new ArrayList<BookieSocketAddress>();
        ensemble.add(new BookieSocketAddress("99.99.99.99:9999"));
        ensemble.add(new BookieSocketAddress("11.11.11.11:1111"));
        ensemble.add(new BookieSocketAddress("88.88.88.88:8888"));
        metadata.addEnsemble(0, ensemble);

        MutableInt ledgerCreateRC = new MutableInt(-1);
        CountDownLatch latch = new CountDownLatch(1);
        long ledgerId = (Math.abs(rand.nextLong())) % 100000000;

        try (LedgerManager lm = driver.getLedgerManagerFactory().newLedgerManager()) {
            lm.createLedgerMetadata(ledgerId, metadata, (rc, result) -> {
                ledgerCreateRC.setValue(rc);
                latch.countDown();
            });
        }

        Assert.assertTrue("Ledger creation should complete within 2 secs",
                latch.await(2000, TimeUnit.MILLISECONDS));
        Assert.assertEquals("LedgerCreate should succeed and return OK rc value", BKException.Code.OK,
                ledgerCreateRC.getValue());
        ledgerList.add(ledgerId);
    }

    final CountDownLatch underReplicaLatch = registerUrLedgerWatcher(ledgerList.size());
    urLedgerMgr.setLostBookieRecoveryDelay(lostBookieRecoveryDelayBeforeChange);
    assertTrue("Audit should be triggered and created ledgers should be marked as underreplicated",
            underReplicaLatch.await(2, TimeUnit.SECONDS));
    assertEquals("All the ledgers should be marked as underreplicated", ledgerList.size(), urLedgerList.size());

    auditTask = auditorBookiesAuditor.getAuditTask();
    Assert.assertEquals("auditTask is supposed to be null", null, auditTask);
    Assert.assertEquals(
            "lostBookieRecoveryDelayBeforeChange of Auditor should be equal to BaseConf's lostBookieRecoveryDelay",
            lostBookieRecoveryDelayBeforeChange,
            auditorBookiesAuditor.getLostBookieRecoveryDelayBeforeChange());
}