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

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

Introduction

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

Prototype

@Override
public void setValue(final Boolean value) 

Source Link

Document

Sets the value from any Boolean instance.

Usage

From source file:org.apache.asterix.external.classad.AttributeReference.java

@Override
public boolean privateEvaluate(EvalState state, Value val, ExprTreeHolder sig) throws HyracksDataException {
    ExprTreeHolder tree = objectPool.mutableExprPool.get();
    ExprTreeHolder exprSig = objectPool.mutableExprPool.get();
    ClassAd curAd = objectPool.classAdPool.get();
    curAd.copyFrom(state.getCurAd());// w w  w . ja  v a2  s . co m
    MutableBoolean rval = objectPool.boolPool.get();
    rval.setValue(true);

    switch (findExpr(state, tree, exprSig, true)) {
    case EVAL_FAIL:
        rval.setValue(false);
        break;
    case EVAL_ERROR:
        val.setErrorValue();
        break;
    case EVAL_UNDEF:
        val.setUndefinedValue();
        break;
    case EVAL_OK: {
        if (state.getDepthRemaining() <= 0) {
            val.setErrorValue();
            state.getCurAd().setValue(curAd);
            return false;
        }
        state.decrementDepth();
        rval.setValue(tree.publicEvaluate(state, val));
        state.incrementDepth();
        break;
    }
    default:
        throw new HyracksDataException("ClassAd:  Should not reach here");
    }
    AttributeReference newAttrRef = objectPool.attrRefPool.get();
    newAttrRef.setValue(exprSig, attributeStr, absolute);
    sig.setInnerTree(newAttrRef);
    state.getCurAd().setValue(curAd);
    return rval.booleanValue();
}

From source file:org.apache.asterix.external.classad.FunctionCall.java

@Override
public boolean privateEvaluate(EvalState state, Value value, ExprTreeHolder tree) throws HyracksDataException {
    FunctionCall tmpSig = objectPool.funcPool.get();
    Value tmpVal = objectPool.valuePool.get();
    ExprTreeHolder argSig = objectPool.mutableExprPool.get();
    MutableBoolean rval = objectPool.boolPool.get();
    if (!privateEvaluate(state, value)) {
        return false;
    }//from   w  w  w.  j a va 2  s .  c o  m
    tmpSig.functionName.set(functionName.get());
    rval.setValue(true);
    for (ExprTree i : arguments.getExprList()) {
        rval.setValue(i.publicEvaluate(state, tmpVal, argSig));
        if (rval.booleanValue()) {
            tmpSig.arguments.add(argSig.getInnerTree());
        }
    }
    tree.setInnerTree(tmpSig);
    return rval.booleanValue();
}

From source file:org.apache.asterix.external.classad.object.pool.MutableBooleanPool.java

@Override
protected void reset(MutableBoolean obj) {
    obj.setValue(false);
}

From source file:org.apache.asterix.metadata.entities.Dataset.java

/**
 * Drop this dataset//from   w  w  w  .  ja  v  a  2 s  .c  o m
 *
 * @param metadataProvider
 *            metadata provider that can be used to get metadata info and runtimes
 * @param mdTxnCtx
 *            the transaction context
 * @param jobsToExecute
 *            a list of jobs to be executed as part of the drop operation
 * @param bActiveTxn
 *            whether the metadata transaction is ongoing
 * @param progress
 *            a mutable progress state used for error handling during the drop operation
 * @param hcc
 *            a client connection to hyracks master for job execution
 * @throws Exception
 *             if an error occur during the drop process or if the dataset can't be dropped for any reason
 */
public void drop(MetadataProvider metadataProvider, MutableObject<MetadataTransactionContext> mdTxnCtx,
        List<JobSpecification> jobsToExecute, MutableBoolean bActiveTxn, MutableObject<ProgressState> progress,
        IHyracksClientConnection hcc) throws Exception {
    Map<FeedConnectionId, Pair<JobSpecification, Boolean>> disconnectJobList = new HashMap<>();
    if (getDatasetType() == DatasetType.INTERNAL) {
        // prepare job spec(s) that would disconnect any active feeds involving the dataset.
        IActiveEntityEventsListener[] activeListeners = ActiveJobNotificationHandler.INSTANCE
                .getEventListeners();
        for (IActiveEntityEventsListener listener : activeListeners) {
            if (listener.isEntityUsingDataset(this)) {
                throw new CompilationException(ErrorCode.COMPILATION_CANT_DROP_ACTIVE_DATASET,
                        RecordUtil.toFullyQualifiedName(dataverseName, datasetName),
                        listener.getEntityId().toString());
            }
        }
        // #. prepare jobs to drop the datatset and the indexes in NC
        List<Index> indexes = MetadataManager.INSTANCE.getDatasetIndexes(mdTxnCtx.getValue(), dataverseName,
                datasetName);
        for (int j = 0; j < indexes.size(); j++) {
            if (indexes.get(j).isSecondaryIndex()) {
                jobsToExecute.add(IndexUtil.buildDropIndexJobSpec(indexes.get(j), metadataProvider, this));
            }
        }
        Index primaryIndex = MetadataManager.INSTANCE.getIndex(mdTxnCtx.getValue(), dataverseName, datasetName,
                datasetName);
        jobsToExecute.add(DatasetUtil.createDropDatasetJobSpec(this, primaryIndex, metadataProvider));
        // #. mark the existing dataset as PendingDropOp
        MetadataManager.INSTANCE.dropDataset(mdTxnCtx.getValue(), dataverseName, datasetName);
        MetadataManager.INSTANCE.addDataset(mdTxnCtx.getValue(),
                new Dataset(dataverseName, datasetName, getItemTypeDataverseName(), getItemTypeName(),
                        getMetaItemTypeDataverseName(), getMetaItemTypeName(), getNodeGroupName(),
                        getCompactionPolicy(), getCompactionPolicyProperties(), getDatasetDetails(), getHints(),
                        getDatasetType(), getDatasetId(), MetadataUtil.PENDING_DROP_OP));

        MetadataManager.INSTANCE.commitTransaction(mdTxnCtx.getValue());
        bActiveTxn.setValue(false);
        progress.setValue(ProgressState.ADDED_PENDINGOP_RECORD_TO_METADATA);

        // # disconnect the feeds
        for (Pair<JobSpecification, Boolean> p : disconnectJobList.values()) {
            JobUtils.runJob(hcc, p.first, true);
        }

        // #. run the jobs
        for (JobSpecification jobSpec : jobsToExecute) {
            JobUtils.runJob(hcc, jobSpec, true);
        }

        mdTxnCtx.setValue(MetadataManager.INSTANCE.beginTransaction());
        bActiveTxn.setValue(true);
        metadataProvider.setMetadataTxnContext(mdTxnCtx.getValue());
    } else {
        // External dataset
        ExternalDatasetsRegistry.INSTANCE.removeDatasetInfo(this);
        // #. prepare jobs to drop the datatset and the indexes in NC
        List<Index> indexes = MetadataManager.INSTANCE.getDatasetIndexes(mdTxnCtx.getValue(), dataverseName,
                datasetName);
        for (int j = 0; j < indexes.size(); j++) {
            if (ExternalIndexingOperations.isFileIndex(indexes.get(j))) {
                jobsToExecute.add(IndexUtil.buildDropIndexJobSpec(indexes.get(j), metadataProvider, this));
            } else {
                jobsToExecute.add(DatasetUtil.buildDropFilesIndexJobSpec(metadataProvider, this));
            }
        }

        // #. mark the existing dataset as PendingDropOp
        MetadataManager.INSTANCE.dropDataset(mdTxnCtx.getValue(), dataverseName, datasetName);
        MetadataManager.INSTANCE.addDataset(mdTxnCtx.getValue(),
                new Dataset(dataverseName, datasetName, getItemTypeDataverseName(), getItemTypeName(),
                        getNodeGroupName(), getCompactionPolicy(), getCompactionPolicyProperties(),
                        getDatasetDetails(), getHints(), getDatasetType(), getDatasetId(),
                        MetadataUtil.PENDING_DROP_OP));

        MetadataManager.INSTANCE.commitTransaction(mdTxnCtx.getValue());
        bActiveTxn.setValue(false);
        progress.setValue(ProgressState.ADDED_PENDINGOP_RECORD_TO_METADATA);

        // #. run the jobs
        for (JobSpecification jobSpec : jobsToExecute) {
            JobUtils.runJob(hcc, jobSpec, true);
        }
        if (!indexes.isEmpty()) {
            ExternalDatasetsRegistry.INSTANCE.removeDatasetInfo(this);
        }
        mdTxnCtx.setValue(MetadataManager.INSTANCE.beginTransaction());
        bActiveTxn.setValue(true);
        metadataProvider.setMetadataTxnContext(mdTxnCtx.getValue());
    }

    // #. finally, delete the dataset.
    MetadataManager.INSTANCE.dropDataset(mdTxnCtx.getValue(), dataverseName, datasetName);
    // Drop the associated nodegroup
    String nodegroup = getNodeGroupName();
    if (!nodegroup.equalsIgnoreCase(MetadataConstants.METADATA_DEFAULT_NODEGROUP_NAME)) {
        MetadataManager.INSTANCE.dropNodegroup(mdTxnCtx.getValue(), dataverseName + ":" + datasetName);
    }
}

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

/**
 * test that Bookie calls correctly Journal.logAddEntry about "ackBeforeSync" parameter.
 *//*from  w w w .j  a v  a  2 s. c o  m*/
@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.hyracks.maven.license.LicenseMojo.java

private void addDependencyToLicenseMap(MavenProject depProject, List<Pair<String, String>> depLicenses,
        String depLocation) {// w  w w  .  java  2  s  .  c  o  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.  ja  va 2 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.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);
    Composite topRow;//w w  w.  j  ava 2s. c om

    // 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 a reader, determining on the fly
 * if the incoming object is in Castor or XStream format.</p>
 * @param reader    A reader instance.//from   ww w.  ja va  2 s.  c  om
 * @param wasCastor A mutable boolean. After the method executes,
 *                  its value will be true if the input was in
 *                  Castor format, false otherwise.
 * @return An Object reference whose field were populated from the
 *         data found in the XML file.
 * @throws SerializationException   if input or output fails.
 * @throws InterruptedIOException   if input or output is
 *                                  interrupted.
 */
public Object deserialize(Reader reader, MutableBoolean wasCastor)
        throws SerializationException, InterruptedIOException {
    // Constants
    final String recognizeCastor = "<?xml";

    // Make rewinding possible
    BufferedReader bufReader = new BufferedReader(reader);

    // Peek at beginning of input
    char[] buffer = new char[recognizeCastor.length()];
    try {
        bufReader.mark(recognizeCastor.length() + 1);
        if (StreamUtil.readChars(bufReader, buffer, buffer.length) != buffer.length) {
            throw failDeserialize(
                    new SerializationException("Could not peek at first " + buffer.length + " bytes"));
        }
        bufReader.reset();
    } catch (IOException exc) {
        throw failDeserialize(exc);
    }

    // Guess format and deserialize
    ObjectSerializer deserializer;
    if (recognizeCastor.equals(new String(buffer))) {
        deserializer = castor;
        wasCastor.setValue(true);
    } else {
        deserializer = xstream;
        wasCastor.setValue(false);
    }
    return deserializer.deserialize(bufReader);
}

From source file:org.objectweb.proactive.core.remoteobject.RemoteObjectSet.java

private Throwable handleProtocolException(Throwable e, URI uri, boolean multiProtocol,
        MutableBoolean anyException) {
    anyException.setValue(true);
    if (!uri.equals(defaultURI)) {
        LOGGER_RO.warn("[ROAdapter] Disabling protocol " + uri.getScheme() + " because of received exception",
                e);//  ww  w. j  a va  2s  .  c o m
        lastBenchmarkResults.put(uri, UNREACHABLE_VALUE);
        return null;
    } else {
        if (multiProtocol) {
            LOGGER_RO.warn("[ROAdapter] Skipping default protocol " + uri.getScheme()
                    + " because of received exception", e);
        }
        lastBenchmarkResults.put(uri, UNREACHABLE_VALUE);
        return e;
    }
}