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.cm.FileFolderService.java

License:Open Source License

/**
 * Get a list of folders filtered by the number of child files and/or folders, returning
 * results sorted according to the parameters supplied.
 * <p/>/*from  ww  w .j av a 2s . c  om*/
 * Apart from the context, all parametes are optional.  However, for best performance,
 * do not mix the file and folder levels; the underlying query performance will be OK
 * but the sorting will not be ideal.
 * <p/>
 * The sort precedence is <b>folderCount-fileCount</b>.
 * 
 * @param context           the context in which the folder path is valid (mandatory)
 * @param minLevel          the minimum folder level to consider (inclusive, optional)
 * @param maxLevel          the maximum folder level to consider (inclusive, optional)
 * @param minFiles          the minimum number of files in the folder (inclusive, optional)
 * @param maxFiles          the maximum number of files in the folder (inclusive, optional)
 * @param skip              the number of entries to skip
 * @param limit             the number of entries to return
 * @return                  the folders with the correct number of children
 */
public List<FolderData> getFoldersByCounts(String context, Long minLevel, Long maxLevel, Long minFolders,
        Long maxFolders, Long minFiles, Long maxFiles, int skip, int limit) {
    if (context == null) {
        throw new IllegalArgumentException();
    }

    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    BasicDBObjectBuilder sortObjBuilder = BasicDBObjectBuilder.start();

    queryObjBuilder.add(FIELD_CONTEXT, context);
    if (minLevel != null || maxLevel != null) {
        queryObjBuilder.push(FIELD_LEVEL);
        {
            if (minLevel != null) {
                queryObjBuilder.add("$gte", minLevel);
            }
            if (maxLevel != null) {
                queryObjBuilder.add("$lte", maxLevel);
            }
            // No sorting by level!
        }
        queryObjBuilder.pop();
    }
    if (minFolders != null || maxFolders != null) {
        queryObjBuilder.push(FIELD_FOLDER_COUNT);
        {
            if (minFolders != null) {
                queryObjBuilder.add("$gte", minFolders);
            }
            if (maxFolders != null) {
                queryObjBuilder.add("$lte", maxFolders);
            }
            // We have to sort by the counts
            sortObjBuilder.add(FIELD_FOLDER_COUNT, 1);
        }
        queryObjBuilder.pop();
    }
    if (minFiles != null || maxFiles != null) {
        queryObjBuilder.push(FIELD_FILE_COUNT);
        {
            if (minFiles != null) {
                queryObjBuilder.add("$gte", minFiles);
            }
            if (maxFiles != null) {
                queryObjBuilder.add("$lte", maxFiles);
            }
            // We have to sort by the counts
            sortObjBuilder.add(FIELD_FILE_COUNT, 1);
        }
        queryObjBuilder.pop();
    }
    DBObject queryObj = queryObjBuilder.get();
    DBObject sortObj = sortObjBuilder.get();

    DBCursor cursor = collection.find(queryObj).sort(sortObj).skip(skip).limit(limit);
    List<FolderData> results = fromDBCursor(cursor);
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Found " + results.size() + " results for file counts: \n" + "   context:    " + context
                + "\n" + "   minLevel:   " + minLevel + "\n" + "   maxLevel:   " + maxLevel + "\n"
                + "   minFiles:   " + minFiles + "\n" + "   maxFiles:   " + maxFiles + "\n" + "   skip:       "
                + skip + "\n" + "   limit:      " + limit);
    }
    return results;
}

From source file:org.alfresco.bm.dataload.rm.site.PrepareRMSite.java

License:Open Source License

/**
 * @see org.alfresco.bm.event.AbstractEventProcessor#processEvent(org.alfresco.bm.event.Event)
 *///from   w w  w  .  ja v a 2 s.  c  om
@Override
protected EventResult processEvent(Event event) throws Exception {
    StringBuilder msg = new StringBuilder("Preparing Records Management: \n");
    List<Event> events = new ArrayList<Event>(10);

    UserModel userModel = new UserModel(getUsername(), getPassword());
    //authenticate with provided credentials and verify that they are valid
    restCoreAPI.authenticateUser(userModel);
    restCoreAPI.withCoreAPI().usingAuthUser().getPerson();
    String statusCode = restCoreAPI.getStatusCode();
    if (HttpStatus.valueOf(Integer.parseInt(statusCode)) != HttpStatus.OK) {
        return new EventResult(
                "Provided RM Site Creator does not exist, or provided credentials are not valid.", false);
    }

    UserData rmAdmin = userDataService.findUserByUsername(getUsername());
    if (rmAdmin == null) {
        rmAdmin = new UserData();
        rmAdmin.setCreationState(Created);
        rmAdmin.setDomain(RM_SITE_DOMAIN);
        rmAdmin.setUsername(getUsername());
        rmAdmin.setPassword(getPassword());
        userDataService.createNewUser(rmAdmin);
    } else {
        // Check for creation
        if (rmAdmin.getCreationState() != Created) {
            userDataService.setUserCreationState(getUsername(), Created);
            msg.append("   Updating user " + getUsername() + " state to created.\n");
        }
    }

    SiteData rmSite = siteDataService.getSite(RM_SITE_ID);
    if (rmSite == null) {
        // Create data
        rmSite = new SiteData();
        rmSite.setSiteId(RM_SITE_ID);
        rmSite.setTitle(RM_SITE_TITLE);
        rmSite.setGuid(RM_SITE_GUID);
        rmSite.setDomain(RM_SITE_DOMAIN);
        rmSite.setDescription(RM_SITE_DESC);
        rmSite.setSitePreset(RM_SITE_PRESET);
        rmSite.setVisibility(RM_SITE_VISIBILITY);
        rmSite.setType(RM_SITE_TYPE);
        rmSite.setCreationState(Scheduled);
        siteDataService.addSite(rmSite);
        msg.append("   Added RM site '" + RM_SITE_ID + "' as created.\n");

        // Record the administrator
        SiteMemberData rmAdminMember = new SiteMemberData();
        rmAdminMember.setCreationState(Created);
        rmAdminMember.setRole(Administrator.toString());
        rmAdminMember.setSiteId(RM_SITE_ID);
        rmAdminMember.setUsername(getUsername());
        siteDataService.addSiteMember(rmAdminMember);
        msg.append("   Added user '" + getUsername() + "' RM administrator.\n");
    }

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
    builder.add(FIELD_SITE_ID, rmSite.getSiteId()).add(FIELD_SITE_MANAGER, getUsername());

    boolean existsRMSite = restAPIFactory.getRMSiteAPI(userModel).existsRMSite();

    // RM site exists and it is loaded in MongoDB
    if (existsRMSite && rmSite.getCreationState() == Created) {
        return new EventResult("RM Site already created, continue loading data.",
                new Event(getEventNameContinueLoadingData(), null));
    }

    // RM site exists and it is not loaded in MongoDB
    if (existsRMSite && rmSite.getCreationState() != Created) {
        builder.add(FIELD_ONLY_DB_LOAD, true);
        DBObject data = builder.get();
        events.add(new Event(getEventNameLoadRMSiteIntoDB(), data));
    }

    // RM site does not exist and will be created
    if (!existsRMSite) {
        DBObject data = builder.get();
        events.add(new Event(getEventNameRMSitePrepared(), data));
    }

    // Done
    return new EventResult(msg.toString(), events);
}

From source file:org.alfresco.bm.event.mongo.MongoEventService.java

License:Open Source License

/**
 * Helper method to convert an {@link Event} into a {@link DBObject persistable object}
 *///from  ww  w.j av  a  2 s.  c  o  m
public static DBObject convertEvent(Event event) {
    // Check the event
    if (event.getDataInMemory() && event.getDriver() != null) {
        throw new IllegalStateException(
                "Events cannot be assigned a specific driver when they have their data bound in memory: "
                        + event);
    }

    BasicDBObjectBuilder insertObjBuilder = BasicDBObjectBuilder.start();
    // Handle the data-key-data-owner link i.e. we store either the object or the key and owner of the key
    insertObjBuilder.add(Event.FIELD_DATA, event.getData());
    insertObjBuilder.add(Event.FIELD_LOCK_OWNER, event.getLockOwner())
            .add(Event.FIELD_LOCK_TIME, new Date(event.getLockTime())).add(Event.FIELD_NAME, event.getName())
            .add(Event.FIELD_SCHEDULED_TIME, new Date(event.getScheduledTime()))
            .add(Event.FIELD_SESSION_ID, event.getSessionId()).add(Event.FIELD_DRIVER, event.getDriver());
    DBObject insertObj = insertObjBuilder.get();
    // Handle explicit setting of the ID
    if (event.getId() != null) {
        insertObj.put(Event.FIELD_ID, new ObjectId(event.getId()));
    }
    return insertObj;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public void recordResult(EventRecord result) {
    if (result == null) {
        throw new IllegalArgumentException("EventRecord may not be null.");
    }/*w ww. j a v  a2 s  . co  m*/

    Event event = result.getEvent();
    if (event == null) {
        throw new IllegalArgumentException("EventRecord must contain an Event.");
    }

    DBObject eventObj = MongoEventService.convertEvent(event);
    // Remove the event data if it is not persistable
    if (event.getDataInMemory()) {
        eventObj.removeField(Event.FIELD_DATA);
    }
    // Remove data that is captured in the result
    eventObj.removeField(Event.FIELD_DATA_OWNER); // This is covered by the processedBy
    eventObj.removeField(Event.FIELD_ID); // Internal and not required
    eventObj.removeField(Event.FIELD_SCHEDULED_TIME); // This is the (startTime - startDelay)
    eventObj.removeField(Event.FIELD_LOCK_TIME); // Locking was an internal function
    eventObj.removeField(Event.FIELD_LOCK_OWNER); // Locking was an internal function

    BasicDBObjectBuilder insertObjBuilder = BasicDBObjectBuilder.start()
            .add(EventRecord.FIELD_PROCESSED_BY, result.getProcessedBy())
            .add(EventRecord.FIELD_CHART, result.isChart()).add(EventRecord.FIELD_DATA, result.getData())
            .add(EventRecord.FIELD_DRIVER_ID, result.getDriverId())
            .add(EventRecord.FIELD_START_DELAY, result.getStartDelay())
            .add(EventRecord.FIELD_START_TIME, new Date(result.getStartTime()))
            .add(EventRecord.FIELD_SUCCESS, result.isSuccess()).add(EventRecord.FIELD_TIME, result.getTime())
            .add(EventRecord.FIELD_EVENT, eventObj);
    if (result.getWarning() != null) {
        insertObjBuilder.add(EventRecord.FIELD_WARNING, result.getWarning());
    }
    DBObject insertObj = insertObjBuilder.get();

    try {
        collection.insert(insertObj);
    } catch (MongoException e) {
        throw new RuntimeException("Failed to insert event result:\n" + "   Result: " + insertObj, e);
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Recorded result: " + insertObj);
    }
}

From source file:org.alfresco.bm.log.MongoLogService.java

License:Open Source License

/**
 * Construct an instance providing the DB and collection name to use
 * /*from  w  ww. ja  v a  2 s .  c o  m*/
 * @param db            the database to use
 * @param size          the size (bytes) to cap the log size at or 0 to ignore.
 *                      This must be zero if the TTL is set.
 * @param max           the maximum number of log entries or 0 to ignore.
 *                      This must be zero if the TTL is set.
 * @param ttl           the time to live (seconds) of a log message or 0 to ignore.
 *                      This must be zero or less if the logs are capped by size or max entries.
 */
public MongoLogService(DB db, int size, int max, int ttl) {
    try {
        BasicDBObjectBuilder optionsBuilder = BasicDBObjectBuilder.start();
        if (size > 0L) {
            optionsBuilder.add("capped", true);
            optionsBuilder.add("size", size);
            if (max > 0L) {
                optionsBuilder.add("max", max);
            }
            if (ttl > 0) {
                throw new IllegalArgumentException(
                        "The log collection can only be capped by size, max entries or time to live.");
            }
        } else if (max > 0L) {
            throw new IllegalArgumentException(
                    "The logs must always be capped by size before capping by number.");
        }
        DBObject options = optionsBuilder.get();
        this.collection = db.createCollection(COLLECTION_LOGS, options);
    } catch (MongoException ex) {
        if (!db.getCollectionNames().contains(COLLECTION_LOGS)) {
            throw ex;
        }
        this.collection = db.getCollection(COLLECTION_LOGS);
    }
    this.ttl = ttl;
}

From source file:org.alfresco.bm.log.MongoLogService.java

License:Open Source License

@Override
public void log(String driverId, String test, String testRun, LogLevel level, String msg) {
    BasicDBObjectBuilder insertObjBuilder = BasicDBObjectBuilder.start().add(FIELD_TIME, new Date())
            .add(FIELD_LEVEL, level.getLevel()).add(FIELD_MSG, msg);
    if (driverId != null) {
        insertObjBuilder.add(FIELD_DRIVER_ID, driverId);
    }//from  w  ww . ja va 2s.  c o m
    if (test != null) {
        insertObjBuilder.add(FIELD_TEST, test);
    }
    if (testRun != null) {
        insertObjBuilder.add(FIELD_TEST_RUN, testRun);
    }
    DBObject insertObj = insertObjBuilder.get();

    collection.insert(insertObj);
}

From source file:org.alfresco.bm.log.MongoLogService.java

License:Open Source License

@Override
public DBCursor getLogs(String driverId, String test, String testRun, LogLevel level, Long minTime,
        Long maxTime, int skip, int limit) {
    BasicDBObjectBuilder queryObjBuilder = BasicDBObjectBuilder.start();
    if (level != null) {
        queryObjBuilder.push(FIELD_LEVEL).add("$gte", level.getLevel()).pop();
    }/*ww  w .ja  v  a2 s  .c o m*/
    if (driverId != null) {
        queryObjBuilder.add(FIELD_DRIVER_ID, driverId);
    }
    if (test != null) {
        queryObjBuilder.add(FIELD_TEST, test);
    }
    if (testRun != null) {
        queryObjBuilder.add(FIELD_TEST_RUN, testRun);
    }
    if (minTime != null || maxTime != null) {
        queryObjBuilder.push(FIELD_TIME);
        if (minTime != null) {
            queryObjBuilder.add("$gte", new Date(minTime));
        }
        if (maxTime != null) {
            queryObjBuilder.add("$lt", new Date(maxTime));
        }
        queryObjBuilder.pop();
    }
    DBObject queryObj = queryObjBuilder.get();
    DBObject sortObj = new BasicDBObject(FIELD_TIME, -1);
    DBObject fieldsObj = BasicDBObjectBuilder.start().add(FIELD_ID, false).add(FIELD_TIME, true)
            .add(FIELD_DRIVER_ID, true).add(FIELD_TEST, true).add(FIELD_TEST_RUN, true).add(FIELD_LEVEL, true)
            .add(FIELD_MSG, true).get();
    return collection.find(queryObj, fieldsObj).sort(sortObj).skip(skip).limit(limit);
}

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

License:Open Source License

/**
 * Get a list of all defined tests//from   ww w.j  av  a 2  s .  c  om
 * 
 * @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

/**
 * Update an existing test to use new test details
 * /*from  w  w  w  .ja  v  a2 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//from  ww  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;
}