Example usage for com.mongodb BasicDBObjectBuilder get

List of usage examples for com.mongodb BasicDBObjectBuilder get

Introduction

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

Prototype

public DBObject get() 

Source Link

Document

Gets the top level document.

Usage

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

License:Open Source License

/**
 * Get a list of all defined tests//from   w  w  w .  java 2 s .  c  o m
 * 
 * @param release
 *        the test definition software release or <tt>null</tt> for all test
 *        releases
 * @param schema
 *        the schema number or <tt>null</tt> for all schemas
 * @return all the currently-defined tests
 */
public DBCursor getTests(String release, Integer schema, int skip, int count) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (release != null && release.length() > 0) {
        queryObjBuilder.add(FIELD_RELEASE, release);
    }
    if (schema != null) {
        queryObjBuilder.add(FIELD_SCHEMA, schema);
    }
    DBObject queryObj = queryObjBuilder.get();

    // We don't want everything just now
    DBObject fieldsObj = BasicDBObjectBuilder.start().add(FIELD_NAME, true).add(FIELD_VERSION, true)
            .add(FIELD_DESCRIPTION, true).add(FIELD_RELEASE, true).add(FIELD_SCHEMA, true).get();

    DBCursor dbCursor = tests.find(queryObj, fieldsObj).skip(skip).limit(count);

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Fetched tests: \n" + "   Release: " + release + "\n" + "   Schema:  " + schema + "\n"
                + "   Results: " + dbCursor.count());
    }
    return dbCursor;
}

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

License:Open Source License

/**
 * Retrieve the data for given test/*from   ww  w .j a  v a2 s.c o m*/
 * 
 * @param testObjId
 *        the ID of the test
 * @param includeProperties
 *        <tt>true</tt> to flesh out the properties
 * @return the test object or <tt>null</tt> if not found
 */
public DBObject getTest(ObjectId testObjId, boolean includeProperties) {
    DBObject queryObj = QueryBuilder.start(FIELD_ID).is(testObjId).get();

    BasicDBObjectBuilder fieldsObjBuilder = BasicDBObjectBuilder.start(FIELD_NAME, 1).add(FIELD_VERSION, true)
            .add(FIELD_DESCRIPTION, true).add(FIELD_RELEASE, true).add(FIELD_SCHEMA, true);
    DBObject fieldsObj = fieldsObjBuilder.get();

    DBObject testObj = tests.findOne(queryObj, fieldsObj);
    if (testObj == null) {
        // The test run no longer exists
        logger.warn("Test not found.  Returning null test: " + testObjId);
        return null;
    }

    BasicDBList propsList = new BasicDBList();
    if (includeProperties) {
        // Get the associated test definition
        String test = (String) testObj.get(FIELD_NAME);
        String release = (String) testObj.get(FIELD_RELEASE);
        Integer schema = (Integer) testObj.get(FIELD_SCHEMA);
        TestDefEntry testDefEntry = getTestDefCached(release, schema);
        if (testDefEntry == null) {
            // Again, we don't bother trying to resolve this
            logger.warn("Test definition not found for test: " + testObj);
            logger.warn("Deleting test without a test definition: " + testObj);
            this.deleteTest(test);
            return null;
        } else {
            // Start with the properties from the test definition
            Map<String, DBObject> propsMap = new HashMap<String, DBObject>(testDefEntry.testDefPropsMap);

            // Fetch the properties for the test
            DBCursor testPropsCursor = getTestPropertiesRaw(testObjId, null);
            // Combine
            MongoTestDAO.mergeProperties(propsMap, testPropsCursor);

            // Turn into a map and add back into the object
            propsList = MongoTestDAO.getPropertyList(propsMap);
            testObj.put(FIELD_PROPERTIES, propsList);
        }
    }

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Found test: " + testObj);
    }
    return testObj;
}

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

License:Open Source License

/**
 * Update an existing test to use new test details
 * /*from w  w w .j  av a 2  s.com*/
 * @param name
 *        the name of the test (must exist)
 * @param version
 *        the version of the test for concurrency checking
 * @param newName
 *        the new test name
 * @param newDescription
 *        the new description or <tt>null</tt> ot leave it
 * @param newRelease
 *        the new software release or <tt>null</tt> to leave it
 * @param newSchema
 *        the new schema number or <tt>null</tt> to leave it
 * @return <tt>true</tt> if the test run was modified or <tt>false</tt> if
 *         not
 */
public boolean updateTest(String name, int version, String newName, String newDescription, String newRelease,
        Integer newSchema) {
    if (name == null) {
        throw new IllegalArgumentException("Updated requires a name and version.");
    }

    // Find the test by name and version
    DBObject queryObj = QueryBuilder.start().and(FIELD_NAME).is(name).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(TEST_NAME_REGEX);
        Matcher matcher = pattern.matcher(newName);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("The test name '" + newName + "' is invalid.  "
                    + "Test names must start with a character and contain only characters, numbers or underscore.");
        }

        setObjBuilder.add(FIELD_NAME, newName);
    }
    if (newDescription != null) {
        setObjBuilder.add(FIELD_DESCRIPTION, newDescription);
    }
    if (newRelease != null) {
        setObjBuilder.add(FIELD_RELEASE, newRelease);
    }
    if (newSchema != null) {
        setObjBuilder.add(FIELD_SCHEMA, newSchema);
    }
    DBObject setObj = setObjBuilder.get();

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

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

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

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

License:Open Source License

/**
 * @param test// w w  w .j a v a 2  s. c o m
 *        only fetch runs for this test or <tt>null</tt> to get all test
 *        runs
 * @param testRunStates
 *        optional states that the test runs must be in or empty for all
 * @return a cursor onto the test runs for the given test
 */
public DBCursor getTestRuns(String test, int skip, int count, TestRunState... testRunStates) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (test != null) {
        ObjectId testObjId = getTestId(test);
        if (testObjId == null) {
            // The test no longer exists, so the run effectively doesn't
            // either
            logger.warn("Test not found: " + test);
            // Use a ficticious ID that will never match
            testObjId = new ObjectId();
        }
        queryObjBuilder.add(FIELD_TEST, testObjId);
    }

    // Build query for the test run states
    if (testRunStates.length > 0) {
        List<String> stateStrs = new ArrayList<String>(testRunStates.length);
        for (int i = 0; i < testRunStates.length; i++) {
            stateStrs.add(testRunStates[i].toString());
        }
        queryObjBuilder.push(FIELD_STATE);
        queryObjBuilder.add("$in", stateStrs);
    }

    DBObject queryObj = queryObjBuilder.get();

    DBObject fieldsObj = BasicDBObjectBuilder.start().add(FIELD_NAME, true).add(FIELD_TEST, true)
            .add(FIELD_VERSION, true).add(FIELD_DESCRIPTION, true).add(FIELD_STATE, true)
            .add(FIELD_SCHEDULED, true).add(FIELD_STARTED, true).add(FIELD_STOPPED, true)
            .add(FIELD_COMPLETED, true).add(FIELD_DURATION, true).add(FIELD_PROGRESS, true)
            .add(FIELD_RESULTS_SUCCESS, true).add(FIELD_RESULTS_FAIL, true).add(FIELD_RESULTS_TOTAL, true)
            .add(FIELD_SUCCESS_RATE, true).get();

    DBCursor dbCursor = testRuns.find(queryObj, fieldsObj).skip(skip).limit(count);

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Fetched test runs: \n" + "   Test:    " + test + "\n" + "   Results: " + dbCursor.count());
    }
    return dbCursor;
}

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

License:Open Source License

/**
 * Retrieve the data for given test run//from  w  w  w .  j  a v a  2s . c om
 * 
 * @param runObjId
 *        (ObjectId, mandatory) the ID of the test run
 * 
 * @param includeProperties
 *        <tt>true</tt> to flesh out all the properties
 * 
 * @return the test object
 */
public DBObject getTestRun(ObjectId runObjId, boolean includeProperties) throws ObjectNotFoundException {
    ArgumentCheck.checkMandatoryObject(runObjId, "runObjId");

    DBObject queryObj = QueryBuilder.start().and(FIELD_ID).is(runObjId).get();

    BasicDBObjectBuilder fieldsObjBuilder = BasicDBObjectBuilder.start().add(FIELD_NAME, true)
            .add(FIELD_TEST, true).add(FIELD_VERSION, true).add(FIELD_DESCRIPTION, true).add(FIELD_STATE, true)
            .add(FIELD_SCHEDULED, true).add(FIELD_STARTED, true).add(FIELD_STOPPED, true)
            .add(FIELD_COMPLETED, true).add(FIELD_DURATION, true).add(FIELD_PROGRESS, true)
            .add(FIELD_RESULTS_SUCCESS, true).add(FIELD_RESULTS_FAIL, true).add(FIELD_RESULTS_TOTAL, true)
            .add(FIELD_SUCCESS_RATE, true).add(FIELD_DRIVERS, true);
    DBObject fieldsObj = fieldsObjBuilder.get();

    DBObject runObj = testRuns.findOne(queryObj, fieldsObj);
    if (runObj == null) {
        // The test run no longer exists
        throw new ObjectNotFoundException("Test run");
    }

    if (includeProperties) {
        ObjectId testObjId = (ObjectId) runObj.get(FIELD_TEST);
        String testName = runObj.get(FIELD_TEST).toString();
        String runName = runObj.get(FIELD_NAME).toString();

        BasicDBList propsList = getTestRunProperties(testObjId, runObjId, testName, runName);
        runObj.put(FIELD_PROPERTIES, propsList);
    }

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Found test run " + runObjId + ": " + runObj);
    }
    return runObj;
}

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 ww  .  j a  v  a 2 s  .c  om
 *        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./* www  .  j  a  va  2  s.  co  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//w w  w .  j ava2s.  co  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.test.mongo.MongoTestDAO.java

License:Open Source License

/**
 * Fetch masked property names (passwords) by test name.
 * //w w w. j  a v a  2  s.  c om
 * @param testName
 *        (String, mandatory) test name
 * 
 * @return (Set<String>) or exception
 * 
 * @throws ObjectNotFoundException
 * @since 2.1.2
 */
public Set<String> getMaskedProperyNames(String testName) throws ObjectNotFoundException {
    ArgumentCheck.checkMandatoryString(testName, "testName");

    DBObject queryObj = QueryBuilder.start().and(FIELD_NAME).is(testName).get();

    BasicDBObjectBuilder fieldsObjBuilder = BasicDBObjectBuilder.start(FIELD_RELEASE, true).add(FIELD_SCHEMA,
            true);

    DBObject testObj = tests.findOne(queryObj, fieldsObjBuilder.get());
    ObjectNotFoundException.checkObject(testObj, testName);

    return getMaskedProperyNames((String) testObj.get(FIELD_RELEASE), (Integer) testObj.get(FIELD_SCHEMA));
}

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

License:Open Source License

public DBObject importTestRun(String testName, String runName, DBObject importObj) {
    // create return object
    DBObject resultObj = new BasicDBObject();
    String message = "Import succeeded.";
    ImportResult result = ImportResult.OK;

    try {/* w  w w  . j  av  a 2  s.  c  o m*/
        ArgumentCheck.checkMandatoryString(testName, "testName");
        ArgumentCheck.checkMandatoryString(runName, "runName");
        ArgumentCheck.checkMandatoryObject(importObj, "importObj");

        // get object IDs
        ObjectId testObjId = getTestId(testName);
        ObjectId runObjId = getTestRunId(testObjId, runName);
        if (null == testObjId) {
            throw new ObjectNotFoundException(testName + "." + runName);
        }

        // get test definition
        DBObject queryObj = QueryBuilder.start(FIELD_ID).is(testObjId).get();
        BasicDBObjectBuilder fieldsObjBuilder = BasicDBObjectBuilder.start(FIELD_NAME, 1)
                .add(FIELD_RELEASE, true).add(FIELD_SCHEMA, true);
        DBObject fieldsObj = fieldsObjBuilder.get();

        DBObject testObj = tests.findOne(queryObj, fieldsObj);
        if (testObj == null) {
            throw new ObjectNotFoundException(testName + "." + runName);
        }

        // get values from test
        String release = (String) testObj.get(FIELD_RELEASE);
        Object tmp = testObj.get(FIELD_SCHEMA);
        Integer schema = null == tmp ? 0 : Integer.valueOf(tmp.toString());

        // get properties
        Map<String, DBObject> mapProps = getTestRunPropertiesMap(testObjId, runObjId, testName, runName);

        // get values from the import object
        Object relObj = importObj.get(FIELD_RELEASE);
        Object schemaObj = importObj.get(FIELD_SCHEMA);
        if (null != relObj && !relObj.toString().equals(release)) {
            result = ImportResult.WARN;
            message += "\r\nWARN: Release '" + release + "' from test to import doesn't match import release '"
                    + relObj.toString() + "'!";
        }
        if (null != schemaObj && !schemaObj.toString().equals(schema.toString())) {
            result = ImportResult.WARN;
            message += "\r\nWARN: Schema '" + schema + "' from test to import doesn't match import schema '"
                    + schemaObj.toString() + "'!";
        }

        // decrypt all values in the properties 
        // separate from set value - might throw exception and nothing should be changed if
        BasicDBList propsListEnc = (BasicDBList) importObj.get(FIELD_PROPERTIES);
        BasicDBList propsListDec = new BasicDBList();
        for (final Object obj : propsListEnc) {
            final DBObject dbObj = (DBObject) obj;
            String propName = (String) dbObj.get(FIELD_NAME);

            // decrypt
            DBObject prop = decryptPropertyValue(dbObj, propName);
            propsListDec.add(prop);
        }

        // again a loop and update the values 
        for (final Object objProp : propsListDec) {
            // get property
            final DBObject dbObj = (DBObject) objProp;
            String propName = (String) dbObj.get(FIELD_NAME);

            // get oldProperty
            final DBObject oldProp = mapProps.get(propName);
            if (null == oldProp) {
                result = ImportResult.WARN;
                message += "\r\nWARN: Ignored property '" + propName + "' not found";
            } else {
                // see if the value differs
                String oldValue = getPropValueAsString(oldProp);
                String newValue = getPropValueAsString(dbObj);
                if (!oldValue.equals(newValue)) {
                    // update property
                    updateProperty(testName, runName, propName, newValue, oldProp);
                }
            }
        }
    } catch (ObjectNotFoundException onfe) {
        message = "Test or test run not found: '" + testName + "." + runName + "'!";
        result = ImportResult.ERROR;
        logger.error(message, onfe);

        message += "\r\n\r\n" + onfe.toString();
    } catch (CipherException ce) {
        message = "Error during decryption while import properties of test run: '" + testName + "." + runName
                + "'! No value imported";
        result = ImportResult.ERROR;
        logger.error(message, ce);

        message += "\r\n\r\n" + ce.toString();
    }

    // put return values
    resultObj.put(FIELD_RESULT, result.toString());
    resultObj.put(FIELD_MESSAGE, message);

    return resultObj;
}