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.api.AbstractRestResource.java

License:Open Source License

/**
 * Does a deep copy of an object to allow for subsequent modification
 *//*from ww w  . j  ava 2 s  . com*/
public static DBObject copyDBObject(DBObject dbObject) {
    DBObject orig = dbObject;
    BasicDBObjectBuilder dbObjectBuilder = BasicDBObjectBuilder.start();
    for (String field : orig.keySet()) {
        Object value = orig.get(field);
        dbObjectBuilder.add(field, value);
    }
    return dbObjectBuilder.get();
}

From source file:org.alfresco.bm.cm.FileFolderService.java

License:Open Source License

/**
 * Create a new folder entry with the given data
 *///  ww  w .j  ava2  s . c  o m
public void createNewFolder(FolderData data) {
    BasicDBObjectBuilder insertObjBuilder = BasicDBObjectBuilder.start().add(FIELD_ID, data.getId())
            .add(FIELD_CONTEXT, data.getContext()).add(FIELD_PATH, data.getPath())
            .add(FIELD_LEVEL, data.getLevel()).add(FIELD_PARENT_PATH, data.getParentPath())
            .add(FIELD_NAME, data.getName()).add(FIELD_FOLDER_COUNT, data.getFolderCount())
            .add(FIELD_FILE_COUNT, data.getFileCount());
    DBObject insertObj = insertObjBuilder.get();

    try {
        collection.insert(insertObj);
    } catch (DuplicateKeyException e) {
        // We just rethrow as per the API
        throw e;
    }
}

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 w  w w . j  a  v a2  s  .  co  m*/
 * 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)
 *//* w ww.  j  a v a  2 s.  co  m*/
@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  w  ww  .  ja  va2s .  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.MongoEventService.java

License:Open Source License

/**
 * {@inheritDoc}/*  w w  w .jav a2s  . c om*/
 */
@Override
public Event nextEvent(String driverId, long latestScheduledTime) {
    // Build query
    BasicDBObjectBuilder qb = BasicDBObjectBuilder.start().push(Event.FIELD_SCHEDULED_TIME) // Must be scheduled to execute
            .add("$lte", new Date(latestScheduledTime)).pop().add(Event.FIELD_LOCK_OWNER, null) // Must not be locked
            .push(Event.FIELD_DATA_OWNER) // We must own the data it or it must be unowned
            .add("$in", new String[] { dataOwner, null }).pop();
    if (driverId != null) {
        qb.push(Event.FIELD_DRIVER) // Must be assigned to the given driver or must be unassigned
                .add("$in", new String[] { driverId, null }).pop();
    }
    DBObject queryObj = qb.get();
    // Build sort
    DBObject sortObj = BasicDBObjectBuilder.start().add(Event.FIELD_SCHEDULED_TIME, Integer.valueOf(1)).get();
    // Build update
    long now = System.currentTimeMillis();
    DBObject updateObj = BasicDBObjectBuilder.start().push("$set").add(Event.FIELD_LOCK_OWNER, dataOwner)
            .add(Event.FIELD_LOCK_TIME, new Date(now)).pop().get();

    DBObject oldObj = collection.findAndModify(queryObj, sortObj, updateObj);
    // Make sure we return the event, as modified
    Event event = null;
    if (oldObj != null) {
        event = convertDBObject(oldObj);
        event.setLockOwner(dataOwner);
        event.setLockTime(now);
    }

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("\n" + "Fetched next event (no lock present): \n" + "   Latest scheduled time:  "
                + latestScheduledTime + "\n" + "   Driver ID:              " + driverId + "\n" + "   Event: "
                + event);
    }
    return event;
}

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 . c om*/

    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
 * //  www  .  j a v a2 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.  j  a v  a2 s .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();
    }//from  ww  w  . jav a  2  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);
}