Example usage for com.mongodb BasicDBObjectBuilder add

List of usage examples for com.mongodb BasicDBObjectBuilder add

Introduction

In this page you can find the example usage for com.mongodb BasicDBObjectBuilder add.

Prototype

public BasicDBObjectBuilder add(final String key, final Object val) 

Source Link

Document

Same as append

Usage

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Update an existing test run with new details
 *
 * @param test/*from  w w w  .ja  v  a2s .  c o m*/
 *        the name of the test
 * @param run
 *        the name of the test run (must exist)
 * @param version
 *        the version of the test for concurrency checking
 * @param newName
 *        the new name of the test run
 * @param newDescription
 *        the new description or <tt>null</tt> ot leave it
 * @return <tt>true</tt> if the test run was modified or <tt>false</tt> if
 *         not
 */
public boolean updateTestRun(String test, String run, int version, String newName, String newDescription) {
    if (test == null || run == null) {
        throw new IllegalArgumentException("Updated requires a name and version.");
    }

    // Get the test
    DBObject testObj = getTest(test, false);
    if (testObj == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to update test run; test not found: " + test);
        }
        return false;
    }

    // Find the test run by name and version
    DBObject queryObj = QueryBuilder.start().and(FIELD_TEST).is(testObj.get(FIELD_ID)).and(FIELD_NAME).is(run)
            .and(FIELD_VERSION).is(version).get();

    // Handle version wrap-around
    Integer newVersion = version >= Short.MAX_VALUE ? 1 : version + 1;
    // Gather all the setters required
    BasicDBObjectBuilder setObjBuilder = BasicDBObjectBuilder.start().add(FIELD_VERSION, newVersion);
    if (newName != null) {
        Pattern pattern = Pattern.compile(RUN_NAME_REGEX);
        Matcher matcher = pattern.matcher(newName);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("The test run name '" + newName + "' is invalid.  "
                    + "Test run names may only contain characters, numbers or underscore.");
        }
        setObjBuilder.add(FIELD_NAME, newName);
    }
    if (newDescription != null) {
        setObjBuilder.add(FIELD_DESCRIPTION, newDescription);
    }
    DBObject setObj = setObjBuilder.get();

    // Now push the values to set into the update
    DBObject updateObj = BasicDBObjectBuilder.start().add("$set", setObj).get();

    WriteResult result = testRuns.update(queryObj, updateObj);
    boolean written = (result.getN() > 0);

    // Done
    if (logger.isDebugEnabled()) {
        if (written) {
            logger.debug("Updated test run: \n" + "   Test:      " + test + "\n" + "   Run:       " + run + "\n"
                    + "   Update:    " + updateObj);
        } else {
            logger.debug("Did not update test run: " + test + "." + run);
        }
    }
    return written;
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Update the run state of a test run.//  w  w  w  . j  a v  a  2 s .  c  o  m
 * <p/>
 * The test run {@link TestConstants#FIELD_STATE state} will be set based on
 * the values.
 * <p/>
 * Note that a test run can either be stopped or completed but not both. In
 * both cases,
 * though, the test run must have been scheduled and then started.
 *
 * @param test
 *        the name of the test
 * @param run
 *        the name of the test run (must exist)
 * @param version
 *        the version of the test for concurrency checking
 * @param testRunState
 *        the test run state to set (<null> to ignore)
 * @param scheduled
 *        the time when the test run is scheduled to start (<null> to
 *        ignore)
 * @param started
 *        the time when the test run started (<null> to ignore)
 * @param stopped
 *        the time when the test run was stopped (<null> to ignore)
 * @param completed
 *        the time when the test run was completed (<null> to ignore)
 * @param duration
 *        the time the test has been running for in ms (<null> to ignore)
 * @param progress
 *        the new progress for the test run (<null> to ignore)
 * @param resultsSuccess
 *        the number of successful results (<null> to ignore)
 * @param resultsFailure
 *        the number of failed results (<null> to ignore)
 * @return <tt>true</tt> if the test run was modified or <tt>false</tt> if
 *         not
 */
public boolean updateTestRunState(ObjectId runId, int version, TestRunState testRunState, Long scheduled,
        Long started, Long stopped, Long completed, Long duration, Double progress, Long resultsSuccess,
        Long resultsFail) {
    // Find the test run by name and version
    DBObject queryObj = QueryBuilder.start().and(FIELD_ID).is(runId).and(FIELD_VERSION).is(version).get();

    // Gather all the setters required
    BasicDBObjectBuilder setObjBuilder = BasicDBObjectBuilder.start();
    if (testRunState != null) {
        setObjBuilder.add(FIELD_STATE, testRunState.toString());
    }
    if (scheduled != null) {
        setObjBuilder.add(FIELD_SCHEDULED, scheduled);
    }
    if (started != null) {
        setObjBuilder.add(FIELD_STARTED, started);
    }
    if (stopped != null) {
        setObjBuilder.add(FIELD_STOPPED, stopped);
    }
    if (completed != null) {
        setObjBuilder.add(FIELD_COMPLETED, completed);
    }
    if (duration != null) {
        setObjBuilder.add(FIELD_DURATION, duration);
    }
    if (progress != null) {
        // Adjust accuracy of the progress
        long progressLong = Math.round(progress * 10000.0);
        if (progressLong < 0L || progressLong > 10000L) {
            throw new IllegalArgumentException("Progress must be expressed as a double in range [0.0, 1.0].");
        }
        progress = progressLong / 10000.0; // Accuracy

        setObjBuilder.add(FIELD_PROGRESS, progress);
    }
    if (resultsSuccess != null || resultsFail != null) {
        if (resultsSuccess == null || resultsFail == null) {
            throw new IllegalArgumentException("resultsSuccess and resultsFail must be updated together.");
        }
        long resultsTotal = Long.valueOf(resultsSuccess.longValue() + resultsFail.longValue());
        double successRate = (resultsTotal == 0) ? 1.0 : (resultsSuccess / (double) resultsTotal);
        setObjBuilder.add(FIELD_RESULTS_SUCCESS, resultsSuccess);
        setObjBuilder.add(FIELD_RESULTS_FAIL, resultsFail);
        setObjBuilder.add(FIELD_RESULTS_TOTAL, resultsTotal);
        setObjBuilder.add(FIELD_SUCCESS_RATE, successRate);
    }
    if (resultsFail != null) {
        setObjBuilder.add(FIELD_RESULTS_FAIL, resultsFail);
    }
    // Check that we are actually going to do something
    if (setObjBuilder.get().keySet().size() == 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("No updates provided for test run: " + runId);
        }
        return false;
    }

    // Handle version wrap-around
    Integer newVersion = version >= Short.MAX_VALUE ? 1 : version + 1;
    setObjBuilder.add(FIELD_VERSION, newVersion);
    // Get the object containing the set values
    DBObject setObj = setObjBuilder.get();

    // Now push the values to set into the update
    DBObject updateObj = BasicDBObjectBuilder.start().add("$set", setObj).get();

    WriteResult result = testRuns.update(queryObj, updateObj);
    boolean written = (result.getN() > 0);

    // Done
    if (logger.isDebugEnabled()) {
        if (written) {
            logger.debug("Updated test run state: \n" + "   Run ID:    " + runId + "\n" + "   Update:    "
                    + updateObj);
        } else {
            logger.debug("Did not update test run state: " + runId);
        }
    }
    return written;
}

From source file:org.alfresco.bm.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Utility method to copy a DBObject/*from   www .  ja  v a2s .  c o  m*/
 */
private static DBObject copyDBObject(DBObject input) {
    // Copy the property to a new instance
    BasicDBObjectBuilder newPropObjBuilder = BasicDBObjectBuilder.start();
    for (String fieldName : input.keySet()) {
        Object fieldValue = input.get(fieldName);
        newPropObjBuilder.add(fieldName, fieldValue);
    }
    return newPropObjBuilder.get();
}

From source file:org.alfresco.bm.user.UserDataServiceImpl.java

License:Open Source License

@Override
public long countUsers(String domain, DataCreationState creationState) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (domain != null) {
        queryObjBuilder.add(FIELD_DOMAIN, domain);
    }// ww w. j  a  va  2  s .  co  m
    if (creationState != null) {
        queryObjBuilder.add(FIELD_CREATION_STATE, creationState.toString());
    }
    DBObject queryObj = queryObjBuilder.get();

    return collection.count(queryObj);
}

From source file:org.alfresco.bm.user.UserDataServiceImpl.java

License:Open Source License

@Override
public long deleteUsers(DataCreationState creationState) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (creationState != null) {
        queryObjBuilder.add(FIELD_CREATION_STATE, creationState.toString());
    }//w  ww. j a v a2 s . c om
    DBObject queryObj = queryObjBuilder.get();

    WriteResult result = collection.remove(queryObj);
    return result.getN();
}

From source file:org.alfresco.cacheserver.dao.mongo.MongoWebSocketDAO.java

License:Open Source License

protected DBCollection getCappedCollection(DB db, String collectionName, Integer maxCollectionSize,
        Integer maxDocuments, WriteConcern writeConcern) {
    if (!db.collectionExists(collectionName)) {
        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();

        builder.add("capped", true);

        if (maxCollectionSize != null) {
            builder.add("size", maxCollectionSize);
        }//www .  j a  va2 s  .  com

        if (maxDocuments != null) {
            builder.add("max", maxDocuments);
        }

        DBObject options = builder.get();
        db.createCollection(collectionName, options);
    }
    DBCollection collection = db.getCollection(collectionName);
    collection.setWriteConcern(writeConcern);

    return collection;
}

From source file:org.alfresco.events.serialize.AbstractEventSerializer.java

License:Open Source License

protected void buildDBObjectFromEvent(BasicDBObjectBuilder builder, Event event) {
    builder.add(FIELD_EVENT_TIMESTAMP, event.getTimestamp()).add(FIELD_ID, event.getId())
            .add(FIELD_TYPE, event.getType().toString()).add(FIELD_USER_ID, event.getUsername());
}

From source file:org.alfresco.events.serialize.AbstractNodeEventSerializer.java

License:Open Source License

protected void buildDBObjectFromNodeEvent(BasicDBObjectBuilder builder, NodeEvent nodeEvent) {
    Client client = nodeEvent.getClient();

    // TODO deal with secondary paths
    List<String> paths = nodeEvent.getPaths();
    Path path = (paths != null && paths.size() > 0 ? new Path(paths.get(0)) : null);

    String alfrescoClientId = (client != null ? client.getClientId() : null);
    ClientType clientType = (client != null ? client.getType() : null);

    builder.add(FIELD_EVENT_TIMESTAMP, nodeEvent.getTimestamp()).add(FIELD_ID, nodeEvent.getId())
            .add(FIELD_NAME, nodeEvent.getName()).add(FIELD_TXN_ID, nodeEvent.getTxnId())
            .add(FIELD_SEQ_NO, nodeEvent.getSeqNumber()).add(FIELD_TYPE, nodeEvent.getType().toString())
            .add(FIELD_NODE_ID, nodeEvent.getNodeId())
            .add(FIELD_NODE_INTERNAL_ID, nodeEvent.getNodeInternalId())
            .add(FIELD_NODE_VERSION_LABEL, nodeEvent.getVersionLabel())
            .add(FIELD_NETWORK_ID, nodeEvent.getNetworkId()).add(FIELD_SITE_ID, nodeEvent.getSiteId())
            .add(FIELD_USER_ID, nodeEvent.getUsername())
            .add(FIELD_CLIENT_ID, (clientType != null ? clientType.toString() : null))
            .add(FIELD_PRIMARY_PATH, (path != null ? path.getArrayPath() : new LinkedList<>()))
            .add(FIELD_PARENT_NODE_IDS, nodeEvent.getParentNodeIds())
            .add(FIELD_NODE_TYPE, nodeEvent.getNodeType()).add(FIELD_ASPECTS, nodeEvent.getAspects())
            .add(FIELD_NODE_PROPERTIES, nodeEvent.getNodeProperties())
            .add(FIELD_NODE_MODIFICATION_TIME, nodeEvent.getNodeModificationTime())
            .add(FIELD_ALFRESCO_CLIENT_ID, alfrescoClientId);
}

From source file:org.alfresco.events.serialize.NodeCheckedOutEventSerializer.java

License:Open Source License

@Override
protected DBObject serializeNodeEvent(NodeEvent nodeEvent) {
    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
    buildDBObjectFromNodeEvent(builder, nodeEvent);

    if (nodeEvent instanceof NodeCheckedOutEvent) {
        NodeCheckedOutEvent nodeCheckedOutEvent = (NodeCheckedOutEvent) nodeEvent;
        builder.add(FIELD_CHECKED_OUT_NODE_ID, nodeCheckedOutEvent.getCheckedOutNodeId());
    }/* ww  w . j a va 2s.  c o m*/

    return builder.get();
}

From source file:org.alfresco.events.serialize.NodeContentPutEventSerializer.java

License:Open Source License

@Override
protected DBObject serializeNodeEvent(NodeEvent nodeEvent) {
    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
    buildDBObjectFromNodeEvent(builder, nodeEvent);

    if (nodeEvent instanceof NodeContentPutEvent) {
        NodeContentPutEvent nodeCPEvent = (NodeContentPutEvent) nodeEvent;
        builder.add(FIELD_SIZE, nodeCPEvent.getSize()).add(FIELD_ENCODING, nodeCPEvent.getEncoding())
                .add(FIELD_MIME_TYPE, nodeCPEvent.getMimeType());
    }//from   w  w  w . j  a v a 2 s  . c  om

    return builder.get();
}