Example usage for org.apache.commons.lang3.mutable MutableBoolean booleanValue

List of usage examples for org.apache.commons.lang3.mutable MutableBoolean booleanValue

Introduction

In this page you can find the example usage for org.apache.commons.lang3.mutable MutableBoolean booleanValue.

Prototype

public boolean booleanValue() 

Source Link

Document

Returns the value of this MutableBoolean as a boolean.

Usage

From source file:org.apache.bookkeeper.bookie.BookieWriteToJournalTest.java

/**
 * test that Bookie calls correctly Journal.logAddEntry about "ackBeforeSync" parameter.
 *///from   w  ww .j  a  va  2s.com
@Test
public void testJournalLogAddEntryCalledCorrectly() throws Exception {

    File journalDir = tempDir.newFolder();
    Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(journalDir));
    File ledgerDir = tempDir.newFolder();
    Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(ledgerDir));
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();
    conf.setJournalDirName(journalDir.getPath()).setLedgerDirNames(new String[] { ledgerDir.getPath() })
            .setMetadataServiceUri(null);
    BookieSocketAddress bookieAddress = Bookie.getBookieAddress(conf);
    CountDownLatch journalJoinLatch = new CountDownLatch(1);
    Journal journal = mock(Journal.class);
    MutableBoolean effectiveAckBeforeSync = new MutableBoolean(false);
    doAnswer((Answer) (InvocationOnMock iom) -> {
        ByteBuf entry = iom.getArgument(0);
        long ledgerId = entry.getLong(entry.readerIndex() + 0);
        long entryId = entry.getLong(entry.readerIndex() + 8);
        boolean ackBeforeSync = iom.getArgument(1);
        WriteCallback callback = iom.getArgument(2);
        Object ctx = iom.getArgument(3);

        effectiveAckBeforeSync.setValue(ackBeforeSync);
        callback.writeComplete(BKException.Code.OK, ledgerId, entryId, bookieAddress, ctx);
        return null;
    }).when(journal).logAddEntry(any(ByteBuf.class), anyBoolean(), any(WriteCallback.class), any());

    // bookie will continue to work as soon as the journal thread is alive
    doAnswer((Answer) (InvocationOnMock iom) -> {
        journalJoinLatch.await();
        return null;
    }).when(journal).joinThread();

    whenNew(Journal.class).withAnyArguments().thenReturn(journal);

    Bookie b = new Bookie(conf);
    b.start();

    long ledgerId = 1;
    long entryId = 0;
    Object expectedCtx = "foo";
    byte[] masterKey = new byte[64];
    for (boolean ackBeforeSync : new boolean[] { true, false }) {
        CountDownLatch latch = new CountDownLatch(1);
        final ByteBuf data = buildEntry(ledgerId, entryId, -1);
        final long expectedEntryId = entryId;
        b.addEntry(data, ackBeforeSync,
                (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> {
                    assertSame(expectedCtx, ctx);
                    assertEquals(ledgerId, ledgerId1);
                    assertEquals(expectedEntryId, entryId1);
                    latch.countDown();
                }, expectedCtx, masterKey);
        latch.await(30, TimeUnit.SECONDS);
        assertEquals(ackBeforeSync, effectiveAckBeforeSync.booleanValue());
        entryId++;
    }
    // let bookie exit main thread
    journalJoinLatch.countDown();
    b.shutdown();
}

From source file:org.apache.flink.streaming.connectors.kinesis.internals.KinesisDataFetcherTest.java

@Test
public void testPeriodicWatermark() {
    final MutableLong clock = new MutableLong();
    final MutableBoolean isTemporaryIdle = new MutableBoolean();
    final List<Watermark> watermarks = new ArrayList<>();

    String fakeStream1 = "fakeStream1";
    StreamShardHandle shardHandle = new StreamShardHandle(fakeStream1,
            new Shard().withShardId(KinesisShardIdGenerator.generateFromShardOrder(0)));

    TestSourceContext<String> sourceContext = new TestSourceContext<String>() {
        @Override/*w ww  .j  a  va2 s.  c  o m*/
        public void emitWatermark(Watermark mark) {
            watermarks.add(mark);
        }

        @Override
        public void markAsTemporarilyIdle() {
            isTemporaryIdle.setTrue();
        }
    };

    HashMap<String, String> subscribedStreamsToLastSeenShardIdsUnderTest = new HashMap<>();

    final KinesisDataFetcher<String> fetcher = new TestableKinesisDataFetcher<String>(
            Collections.singletonList(fakeStream1), sourceContext, new java.util.Properties(),
            new KinesisDeserializationSchemaWrapper<>(
                    new org.apache.flink.streaming.util.serialization.SimpleStringSchema()),
            1, 1, new AtomicReference<>(), new LinkedList<>(), subscribedStreamsToLastSeenShardIdsUnderTest,
            FakeKinesisBehavioursFactory.nonReshardedStreamsBehaviour(new HashMap<>())) {

        @Override
        protected long getCurrentTimeMillis() {
            return clock.getValue();
        }
    };
    Whitebox.setInternalState(fetcher, "periodicWatermarkAssigner", watermarkAssigner);

    SequenceNumber seq = new SequenceNumber("fakeSequenceNumber");
    // register shards to subsequently emit records
    int shardIndex = fetcher.registerNewSubscribedShardState(new KinesisStreamShardState(
            KinesisDataFetcher.convertToStreamShardMetadata(shardHandle), shardHandle, seq));

    StreamRecord<String> record1 = new StreamRecord<>(String.valueOf(Long.MIN_VALUE), Long.MIN_VALUE);
    fetcher.emitRecordAndUpdateState(record1.getValue(), record1.getTimestamp(), shardIndex, seq);
    Assert.assertEquals(record1, sourceContext.getCollectedOutputs().poll());

    fetcher.emitWatermark();
    Assert.assertTrue("potential watermark equals previous watermark", watermarks.isEmpty());

    StreamRecord<String> record2 = new StreamRecord<>(String.valueOf(1), 1);
    fetcher.emitRecordAndUpdateState(record2.getValue(), record2.getTimestamp(), shardIndex, seq);
    Assert.assertEquals(record2, sourceContext.getCollectedOutputs().poll());

    fetcher.emitWatermark();
    Assert.assertFalse("watermark advanced", watermarks.isEmpty());
    Assert.assertEquals(new Watermark(record2.getTimestamp()), watermarks.remove(0));
    Assert.assertFalse("not idle", isTemporaryIdle.booleanValue());

    // test idle timeout
    long idleTimeout = 10;
    // advance clock idleTimeout
    clock.add(idleTimeout + 1);
    fetcher.emitWatermark();
    Assert.assertFalse("not idle", isTemporaryIdle.booleanValue());
    Assert.assertTrue("not idle, no new watermark", watermarks.isEmpty());

    // activate idle timeout
    Whitebox.setInternalState(fetcher, "shardIdleIntervalMillis", idleTimeout);
    fetcher.emitWatermark();
    Assert.assertTrue("idle", isTemporaryIdle.booleanValue());
    Assert.assertTrue("idle, no watermark", watermarks.isEmpty());
}

From source file:org.apache.hyracks.maven.license.LicenseMojo.java

private void addDependencyToLicenseMap(MavenProject depProject, List<Pair<String, String>> depLicenses,
        String depLocation) {//from   w  w  w. j  a  va  2 s  . co  m
    final String depGav = toGav(depProject);
    getLog().debug("adding " + depGav + ", location: " + depLocation);
    final MutableBoolean usedMetric = new MutableBoolean(false);
    if (depLicenses.size() > 1) {
        Collections.sort(depLicenses, (o1, o2) -> {
            final int metric1 = getLicenseMetric(o1.getLeft());
            final int metric2 = getLicenseMetric(o2.getLeft());
            usedMetric.setValue(usedMetric.booleanValue() || metric1 != LicenseSpec.UNDEFINED_LICENSE_METRIC
                    || metric2 != LicenseSpec.UNDEFINED_LICENSE_METRIC);
            return Integer.compare(metric1, metric2);
        });
        if (usedMetric.booleanValue()) {
            getLog().info("Multiple licenses for " + depGav + ": " + depLicenses + "; taking lowest metric: "
                    + depLicenses.get(0));
        } else {
            getLog().warn("Multiple licenses for " + depGav + ": " + depLicenses + "; taking first listed: "
                    + depLicenses.get(0));
        }
    } else if (depLicenses.isEmpty()) {
        getLog().info("no license defined in model for " + depGav);
        depLicenses.add(new ImmutablePair<>("MISSING_LICENSE", null));
    }
    Pair<String, String> key = depLicenses.get(0);
    String licenseUrl = key.getLeft();
    final String displayName = key.getRight();
    if (!urlToLicenseMap.containsKey(licenseUrl)) {
        // assuming we've not already mapped it, annotate the URL with artifact info, if not an actual URL
        try {
            getLog().debug("- URL: " + new URL(licenseUrl));
            // life is good
        } catch (MalformedURLException e) {
            // we encounter this a lot.  Log a warning, and use an annotated key
            final String fakeLicenseUrl = depGav.replaceAll(":", "--") + "_" + licenseUrl;
            getLog().info(
                    "- URL for " + depGav + " is malformed: " + licenseUrl + "; using: " + fakeLicenseUrl);
            licenseUrl = fakeLicenseUrl;
        }
    }
    addProject(new Project(depProject, depLocation, depProject.getArtifact().getFile()),
            new LicenseSpec(licenseUrl, displayName), true);
}

From source file:org.apache.mahout.cf.taste.impl.model.file.FileDataModelTest.java

@Test
public void testRefresh() throws Exception {
    final MutableBoolean initialized = new MutableBoolean(false);
    Runnable initializer = new Runnable() {
        @Override/*from w w  w . j a v a2  s .c o m*/
        public void run() {
            try {
                model.getNumUsers();
                initialized.setValue(true);
            } catch (TasteException te) {
                // oops
            }
        }
    };
    new Thread(initializer).start();
    Thread.sleep(1000L); // wait a second for thread to start and call getNumUsers()
    model.getNumUsers(); // should block
    assertTrue(initialized.booleanValue());
    assertEquals(4, model.getNumUsers());
}

From source file:org.lockss.scheduler.TaskRunner.java

void runSteps(MutableBoolean continueStepping, LockssWatchdog wdog) {
    StepTask task = runningTask;// w w  w .j a v  a2  s  .com
    Deadline until = runningDeadline;
    boolean overOk = task.isOverrunAllowed();
    long timeDelta = 0;
    long statsStartTime = TimeBase.nowMs();
    long statsUpdateTime = statsStartTime + statsUpdateInterval;

    task.setStarted();
    task.setStepping(true);
    try {
        // step until reach deadline, or told to stop
        while (continueStepping.booleanValue() && !until.expired()) {
            // MUST check this first, as it's possible chunks will still exist
            // for an already-finished task.
            if (task.isFinished()) {
                break;
            }
            if (log.isDebug3())
                log.debug3("taskStep: " + task);
            // tk - step size?
            task.step(0);
            if (wdog != null) {
                wdog.pokeWDog();
            }
            timeDelta = (long) (TimeBase.msSince(statsStartTime) * (1.0 - backgroundLoadFactor));
            task.setUnaccountedTime(timeDelta);

            if (task.isFinished()) {
                task.setFinished();
                break;
            }
            if (!overOk && (task.getTimeUsed() > task.origEst)) {
                throw new SchedService.Overrun("task not finished within estimate");
            }
            //    Thread.yield();
            if (TimeBase.nowMs() > statsUpdateTime) {
                totalTime += timeDelta;
                task.updateStats();
                statsStartTime = TimeBase.nowMs();
                statsUpdateTime = statsStartTime + statsUpdateInterval;
            }
        }
        if (!task.isFinished() && task.isExpired()) {
            if (log.isDebug())
                log.debug("Expired: " + task);
            throw new SchedService.Timeout("task not finished before deadline");
        }
    } catch (Exception e) {
        // tk - should this catch all Throwable?
        task.e = e;
        task.setFinished();
    }
    totalTime += timeDelta;
    task.updateStats();
    task.setStepping(false);

    if (runningChunk != null) {
        if (runningChunk.getFinish().expired() || task.isFinished()) {
            removeChunk(runningChunk);
        }
    } else if (task.isFinished()) {
        removeTask(task);
    }
}

From source file:org.lockss.servlet.BatchAuConfig.java

private void chooseSets(Verb verb) throws IOException {
    this.verb = verb;

    // Begin page
    Page page = newPage();/*from w w  w . j  ava2s .  c o  m*/
    addJavaScript(page);
    layoutErrorBlock(page);

    // Prepare sets
    Collection titleSets = pluginMgr.getTitleSets();
    if (titleSets.isEmpty()) {
        ServletUtil.layoutExplanationBlock(page, "No titlesets are defined.");
    } else {
        String grayAction = CurrentConfig.getParam(PARAM_GREY_TITLESET_ACTION, DEFAULT_GREY_TITLESET_ACTION);
        boolean doGray = "All".equalsIgnoreCase(grayAction)
                || (verb == VERB_ADD && "Add".equalsIgnoreCase(grayAction));
        MutableBoolean isAnySelectable = new MutableBoolean(false);
        MutableInt buttonNumber = new MutableInt(submitButtonNumber);
        Composite chooseSets = ServletUtil.makeChooseSets(this, remoteApi, titleSets.iterator(), verb,
                KEY_TITLE_SET, doGray, isAnySelectable, "Select AUs", ACTION_SELECT_AUS, buttonNumber, 10);
        submitButtonNumber = buttonNumber.intValue();

        if (isAnySelectable.booleanValue()) {
            // Display set chooser
            ServletUtil.layoutExplanationBlock(page,
                    "Select one or more collections of AUs to " + verb.word + ", then click \"Select AUs\".");
            ServletUtil.layoutChooseSets(srvURL(myServletDescr()), page, chooseSets, ACTION_TAG, KEY_VERB,
                    verb);
        } else {
            // Set chooser not needed
            String msg = "All AUs in all predefined collections of AUs " + "already exist on this LOCKSS box.";
            ServletUtil.layoutExplanationBlock(page, msg);
        }
    }
    endPage(page);
}

From source file:org.lockss.servlet.ServletUtil.java

public static Composite makeChooseSets(LockssServlet servlet, RemoteApi remoteApi, Iterator titleSetIterator,
        Verb verb, String checkboxGroup, boolean doGray, MutableBoolean isAnySelectable, String submitText,
        String submitAction, MutableInt buttonNumber, int atLeast) {
    int actualRows = 0;
    isAnySelectable.setValue(false);//from ww  w .  j  av a2s.c o m
    Composite topRow;

    // Create table
    Table tbl = new Table(CHOOSESETS_TABLE_BORDER, CHOOSESETS_TABLE_ATTRIBUTES);

    // Create top row
    tbl.newRow();
    topRow = tbl.row();
    tbl.newCell(CHOOSESETS_BUTTONROW_ATTRIBUTES);
    tbl.add(submitButton(servlet, buttonNumber, submitText, submitAction));

    // Iterate over title sets
    while (titleSetIterator.hasNext()) {
        TitleSet set = (TitleSet) titleSetIterator.next();
        if (verb.isTsAppropriateFor(set)) {
            int numOk = verb.countAusInSetForVerb(remoteApi, set);
            if (numOk > 0 || doGray) {
                ++actualRows;
                tbl.newRow();
                tbl.newCell(CHOOSESETS_CHECKBOX_ATTRIBUTES);
                if (numOk > 0) {
                    isAnySelectable.setValue(true);
                    tbl.add(checkbox(servlet, checkboxGroup, set.getId(), false));
                }
                tbl.newCell(CHOOSESETS_CELL_ATTRIBUTES);
                String txt = encodeText(set.getName()) + " (" + numOk + ")";
                tbl.add(numOk > 0 ? txt : gray(txt));
            }
        }
    }

    if (isAnySelectable.booleanValue()) {
        // Remove top row if unneeded
        if (actualRows < atLeast) {
            topRow.reset();
        }

        // Add bottom row
        tbl.newRow();
        tbl.newCell(CHOOSESETS_BUTTONROW_ATTRIBUTES);
        tbl.add(submitButton(servlet, buttonNumber, submitText, submitAction));
    }

    return tbl;
}

From source file:org.lockss.util.CXSerializer.java

/**
 * <p>Deserializes an object from the given file, and overwrites the
 * input file in XStream format if the original file was in Castor
 * format (when this serializer is in XSTREAM_OVERWIRTE_MODE).</p>
 * <p>See {@link ObjectSerializer#deserialize(File)} for a
 * description of this method's specification.</p>
 * @param inputFile {@inheritDoc}//from   ww  w  . ja v  a 2s  .  co m
 * @throws SerializationException.FileNotFound {@inheritDoc}
 * @throws SerializationException              {@inheritDoc}
 * @throws InterruptedIOException              {@inheritDoc}
 */
public Object deserialize(File inputFile) throws SerializationException, InterruptedIOException {
    // Open reader
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(inputFile));
    } catch (FileNotFoundException fnfe) {
        throw new SerializationException.FileNotFound(fnfe);
    }

    // Local variables
    MutableBoolean wasCastor = new MutableBoolean(false);
    Object ret = null;

    // Deserialize
    try {
        ret = deserialize(reader, wasCastor);
    } catch (SerializationException se) {
        // must close reader to unlock inputFile
        // because failDeserialize manipulates it
        IOUtil.safeClose(reader);
        throw failDeserialize(se, inputFile);
    } catch (InterruptedIOException iioe) {
        // must close reader to unlock inputFile
        // because failDeserialize manipulates it
        IOUtil.safeClose(reader);
        throw failDeserialize(iioe, inputFile);
    } finally {
        IOUtil.safeClose(reader);
    }

    // Overwrite
    if (getCompatibilityMode() == XSTREAM_OVERWRITE_MODE && wasCastor.booleanValue()) {
        boolean shouldThrow = CurrentConfig.getBooleanParam(PARAM_FAILED_OVERWRITE_THROWS,
                DEFAULT_FAILED_OVERWRITE_THROWS);
        try {
            serialize(inputFile, ret);
        } catch (SerializationException se) {
            logger.debug("Overwrite failed", se);
            if (shouldThrow) {
                throw failDeserialize(se, inputFile);
            }
        } catch (InterruptedIOException iioe) {
            logger.debug("Overwrite interrupted", iioe);
            if (shouldThrow) {
                throw failDeserialize(iioe, inputFile);
            }
        } catch (RuntimeException re) {
            logger.debug("Overwrite caused runtime exception", re);
            if (shouldThrow) {
                throw re;
            }
        }
    }

    return ret;
}

From source file:org.onosproject.store.ecmap.MapDbPersistentStore.java

private void putInternal(K key, V value, Timestamp timestamp) {
    byte[] keyBytes = serializer.encode(key);
    byte[] removedBytes = tombstones.get(keyBytes);

    Timestamp removed = removedBytes == null ? null : serializer.decode(removedBytes);
    if (removed != null && removed.isNewerThan(timestamp)) {
        return;/* w ww.  ja  v a  2 s .c om*/
    }

    final MutableBoolean updated = new MutableBoolean(false);

    items.compute(keyBytes, (k, existingBytes) -> {
        Timestamped<V> existing = existingBytes == null ? null : serializer.decode(existingBytes);
        if (existing != null && existing.isNewerThan(timestamp)) {
            updated.setFalse();
            return existingBytes;
        } else {
            updated.setTrue();
            return serializer.encode(new Timestamped<>(value, timestamp));
        }
    });

    boolean success = updated.booleanValue();

    if (success && removed != null) {
        tombstones.remove(keyBytes, removedBytes);
    }

    database.commit();
}

From source file:org.onosproject.store.ecmap.MapDbPersistentStore.java

private void removeInternal(K key, Timestamp timestamp) {
    byte[] keyBytes = serializer.encode(key);

    final MutableBoolean updated = new MutableBoolean(false);

    items.compute(keyBytes, (k, existingBytes) -> {
        Timestamp existing = existingBytes == null ? null : serializer.decode(existingBytes);
        if (existing != null && existing.isNewerThan(timestamp)) {
            updated.setFalse();/*  w  w  w .j  ava2  s  . com*/
            return existingBytes;
        } else {
            updated.setTrue();
            // remove from items map
            return null;
        }
    });

    if (!updated.booleanValue()) {
        return;
    }

    byte[] timestampBytes = serializer.encode(timestamp);
    byte[] removedBytes = tombstones.get(keyBytes);

    Timestamp removedTimestamp = removedBytes == null ? null : serializer.decode(removedBytes);
    if (removedTimestamp == null) {
        tombstones.putIfAbsent(keyBytes, timestampBytes);
    } else if (timestamp.isNewerThan(removedTimestamp)) {
        tombstones.replace(keyBytes, removedBytes, timestampBytes);
    }

    database.commit();
}