Example usage for com.mongodb BasicDBObjectBuilder start

List of usage examples for com.mongodb BasicDBObjectBuilder start

Introduction

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

Prototype

public static BasicDBObjectBuilder start() 

Source Link

Document

Creates a builder intialized with an empty document.

Usage

From source file:org.alfresco.bm.data.ProcessDataDAO.java

License:Open Source License

/**
 * Create a new process/*  w ww .  jav a 2s  . c  o  m*/
 * 
 * @return                      <tt>true</tt> if the insert was successful
 */
public boolean createProcess(String processName) {
    DBObject insertObj = BasicDBObjectBuilder.start().add(ProcessData.FIELD_NAME, processName)
            .add(ProcessData.FIELD_STATE, DataCreationState.NotScheduled.toString()).get();
    try {
        collection.insert(insertObj);
        return true;
    } catch (MongoException e) {
        // Log and rethrow
        return false;
    }
}

From source file:org.alfresco.bm.data.ProcessDataDAO.java

License:Open Source License

/**
 * Find a process by unique name/*from  w ww  . jav a  2s  .c om*/
 * 
 * @param processName           the name of the process to find
 * @return                      Returns the data or <tt>null</tt> if not found
 */
public ProcessData findProcessByName(String processName) {
    DBObject queryObj = BasicDBObjectBuilder.start().add(ProcessData.FIELD_NAME, processName).get();
    DBObject resultObj = collection.findOne(queryObj);
    if (resultObj == null) {
        return null;
    } else {
        ProcessData result = new ProcessData();
        String stateStr = (String) resultObj.get(ProcessData.FIELD_STATE);
        DataCreationState state = DataCreationState.valueOf(stateStr);
        result.setState(state);
        result.setName((String) resultObj.get(ProcessData.FIELD_NAME));
        return result;
    }
}

From source file:org.alfresco.bm.data.ProcessDataDAO.java

License:Open Source License

public boolean updateProcessState(String processName, DataCreationState state) {
    DBObject findObj = new BasicDBObject().append(ProcessData.FIELD_NAME, processName);
    DBObject setObj = BasicDBObjectBuilder.start().push("$set")
            .append(ProcessData.FIELD_STATE, state.toString()).pop().get();
    DBObject foundObj = collection.findAndModify(findObj, setObj);
    return foundObj != null;
}

From source file:org.alfresco.bm.data.WebScriptInvocationDataDAO.java

License:Open Source License

/**
 * Create a new Web Script invocation. It's state is usually set to scheduled so it will be immediately picked
 * up for processing./*from  ww  w.j  ava2s .  co  m*/
 *
 * @param webScriptInvocation - the Web Script Invocation data
 * @return <tt>true</tt> if the insert was successful
 */
public boolean createWebScriptInvocation(WebScriptInvocationData webScriptInvocation) {
    DBObject insertObj = BasicDBObjectBuilder.start()
            .add(WebScriptInvocationData.FIELD_WS_INVOCATION_NAME, webScriptInvocation.getName())
            .add(WebScriptInvocationData.FIELD_WS_INVOCATION_MESSAGE, webScriptInvocation.getMessage())
            .add(WebScriptInvocationData.FIELD_WS_INVOCATION_USERNAME, webScriptInvocation.getUsername())
            .add(WebScriptInvocationData.FIELD_WS_INVOCATION_STATE, webScriptInvocation.getState().toString())
            .get();
    try {
        collection.insert(insertObj);
        return true;
    } catch (MongoException e) {
        // Log and rethrow
        return false;
    }
}

From source file:org.alfresco.bm.data.WebScriptInvocationDataDAO.java

License:Open Source License

/**
 * Find a Web Script Invocation by unique name
 *
 * @param webScriptInvocationName - the name of the Web Script invocation to find
 * @return Returns the data or <tt>null</tt> if not found
 *///www  . j  a  v  a2  s.c o  m
public WebScriptInvocationData findWebScriptInvocationByName(String webScriptInvocationName) {
    DBObject queryObj = BasicDBObjectBuilder.start()
            .add(WebScriptInvocationData.FIELD_WS_INVOCATION_NAME, webScriptInvocationName).get();
    DBObject resultObj = collection.findOne(queryObj);
    if (resultObj == null) {
        return null;
    } else {
        WebScriptInvocationData result = new WebScriptInvocationData();
        String stateStr = (String) resultObj.get(WebScriptInvocationData.FIELD_WS_INVOCATION_STATE);
        DataCreationState state = DataCreationState.valueOf(stateStr);
        result.setState(state);
        result.setName((String) resultObj.get(WebScriptInvocationData.FIELD_WS_INVOCATION_NAME));
        result.setMessage((String) resultObj.get(WebScriptInvocationData.FIELD_WS_INVOCATION_MESSAGE));
        result.setUsername((String) resultObj.get(WebScriptInvocationData.FIELD_WS_INVOCATION_USERNAME));
        return result;
    }
}

From source file:org.alfresco.bm.data.WebScriptInvocationDataDAO.java

License:Open Source License

/**
 * Set the state of a Web Script invocation
 *
 * @param webScriptInvocationName - the name of the Web Script invocation to update
 * @param state                   the new invocation state
 * @return <tt>true</tt> if the update was successful
 *///  ww  w.jav  a2 s .  c om
public boolean updateWebScriptInvacationState(String webScriptInvocationName, DataCreationState state) {
    DBObject findObj = new BasicDBObject().append(WebScriptInvocationData.FIELD_WS_INVOCATION_NAME,
            webScriptInvocationName);
    DBObject setObj = BasicDBObjectBuilder.start().push("$set")
            .append(WebScriptInvocationData.FIELD_WS_INVOCATION_STATE, state.toString()).pop().get();
    DBObject foundObj = collection.findAndModify(findObj, setObj);
    return foundObj != null;
}

From source file:org.alfresco.bm.dataload.rm.fileplan.LoadFilePlan.java

License:Open Source License

/**
 * Helper method that creates specified number of root record categories if the specified container is the filePlan,
 * specified number of record categories and record folder children if the container is a record category,
 * or only specified number of record folders if we are on the last level or record categories.
 *
 * @param container - filePlan, root record category, or ordinary record category
 * @param rootFoldersToCreate - number of root record categories to create
 * @param categoriesToCreate - number of record category children
 * @param foldersToCreate - number of record folder children
 * @return EventResult - the loading result or error if there was an exception on loading
 * @throws IOException//from   www  .j  a  v a2s.co  m
 */
private EventResult loadCategory(FolderData container, int rootCategoriesToCreate, int categoriesToCreate,
        int foldersToCreate) throws IOException {
    UserData user = getRandomUser(logger);
    String username = user.getUsername();
    String password = user.getPassword();
    UserModel userModel = new UserModel(username, password);
    try {
        List<Event> scheduleEvents = new ArrayList<Event>();
        // Create root categories
        if (rootCategoriesToCreate > 0) {
            super.resumeTimer();
            createRootCategory(container, userModel, rootCategoriesToCreate, ROOT_CATEGORY_NAME_IDENTIFIER,
                    RECORD_CATEGORY_CONTEXT, loadFilePlanDelay);
            super.suspendTimer();
            String lockedPath = container.getPath() + "/locked";
            fileFolderService.deleteFolder(container.getContext(), lockedPath, false);
        }

        // Create categories
        if (categoriesToCreate > 0) {
            super.resumeTimer();
            createSubCategory(container, userModel, categoriesToCreate, CATEGORY_NAME_IDENTIFIER,
                    RECORD_CATEGORY_CONTEXT, loadFilePlanDelay);
            super.suspendTimer();
            String lockedPath = container.getPath() + "/locked";
            fileFolderService.deleteFolder(container.getContext(), lockedPath, false);
        }

        // Create folders
        if (foldersToCreate > 0) {
            super.resumeTimer();
            createRecordFolder(container, userModel, foldersToCreate, RECORD_FOLDER_NAME_IDENTIFIER,
                    RECORD_FOLDER_CONTEXT, loadFilePlanDelay);
            super.suspendTimer();
            String lockedPath = container.getPath() + "/locked";
            fileFolderService.deleteFolder(container.getContext(), lockedPath, false);
        }

        DBObject eventData = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, container.getContext())
                .add(FIELD_PATH, container.getPath()).get();
        Event event = new Event(eventNameRecordCategoryLoaded, eventData);
        scheduleEvents.add(event);

        DBObject resultData = BasicDBObjectBuilder.start()
                .add("msg",
                        "Created " + rootCategoriesToCreate + " root categories, " + categoriesToCreate
                                + " categories and " + foldersToCreate + " record folders.")
                .add("path", container.getPath()).add("username", username).get();

        return new EventResult(resultData, scheduleEvents);
    } catch (Exception e) {
        String error = e.getMessage();
        String stack = ExceptionUtils.getStackTrace(e);
        // Grab REST API information
        DBObject data = BasicDBObjectBuilder.start().append("error", error).append("username", username)
                .append("path", container.getPath()).append("stack", stack).get();
        // Build failure result
        return new EventResult(data, false);
    }
}

From source file:org.alfresco.bm.dataload.rm.fileplan.LoadRecords.java

License:Open Source License

/**
 * Helper method that load specified numbers of records in specified record folder.
 *
 * @param container - record folder//w  w  w .  ja v a2  s.com
 * @param recordsToCreate - number of records to create
 * @return EventResult - the loading result or error if there was an exception on loading
 * @throws IOException
 */
private EventResult loadRecords(FolderData container, int recordsToCreate) throws IOException {
    UserData user = getRandomUser(logger);
    String username = user.getUsername();
    String password = user.getPassword();
    UserModel userModel = new UserModel(username, password);
    try {
        List<Event> scheduleEvents = new ArrayList<Event>();
        // Create records
        if (recordsToCreate > 0) {
            super.resumeTimer();
            //TODO uncomment this and remove createRecord when RM-4564 issue is fixed
            //uploadElectronicRecordInRecordFolder(container, userModel, recordsToCreate, RECORD_NAME_IDENTIFIER, loadRecordsDelay);
            createNonElectonicRecordInRecordFolder(container, userModel, recordsToCreate,
                    RECORD_NAME_IDENTIFIER, loadRecordsDelay);
            super.suspendTimer();
            // Clean up the lock
            String lockedPath = container.getPath() + "/locked";
            fileFolderService.deleteFolder(container.getContext(), lockedPath, false);
        }

        DBObject eventData = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, container.getContext())
                .add(FIELD_PATH, container.getPath()).get();
        Event nextEvent = new Event(eventNameRecordsLoaded, eventData);

        scheduleEvents.add(nextEvent);
        DBObject resultData = BasicDBObjectBuilder.start()
                .add("msg", "Created " + recordsToCreate + " records.").add("path", container.getPath())
                .add("username", username).get();

        return new EventResult(resultData, scheduleEvents);
    } catch (Exception e) {
        String error = e.getMessage();
        String stack = ExceptionUtils.getStackTrace(e);
        // Grab REST API information
        DBObject data = BasicDBObjectBuilder.start().append("error", error).append("username", username)
                .append("path", container.getPath()).append("stack", stack).get();
        // Build failure result
        return new EventResult(data, false);
    }
}

From source file:org.alfresco.bm.dataload.rm.fileplan.ScheduleFilePlanLoaders.java

License:Open Source License

/**
 * Helper method for preparing the events that load the root record categories.
 *
 * @param loaderSessionsToCreate - the number of still active loader sessions
 * @param nextEvents - list of prepared events
 *///from   www  .j  a v a2s . com
private void prepareRootCategories(int loaderSessionsToCreate, List<Event> nextEvents) {
    int skip = 0;
    int limit = 100;
    while (nextEvents.size() < loaderSessionsToCreate) {
        // Get categories needing loading
        List<FolderData> emptyFolders = fileFolderService.getFoldersByCounts(FILEPLAN_CONTEXT,
                Long.valueOf(FILE_PLAN_LEVEL), Long.valueOf(FILE_PLAN_LEVEL), //we need only file plan level here since we load root categories on filePlan
                0L, Long.valueOf((categoryNumber - 1)), //limit the maximum number of child folders to number of needed root categories - 1
                null, null, // Ignore file limits
                skip, limit);
        if (emptyFolders.size() == 0) {
            // The folders were populated in the mean time
            break;
        }
        // Schedule a load for each folder
        for (FolderData emptyFolder : emptyFolders) {
            int rootCategoriesToCreate = categoryNumber - (int) emptyFolder.getFolderCount();
            try {
                // Create a lock folder that has too many files and folders so that it won't be picked up
                // by this process in subsequent trawls
                String lockPath = emptyFolder.getPath() + "/locked";
                FolderData lockFolder = new FolderData(UUID.randomUUID().toString(), emptyFolder.getContext(),
                        lockPath, Long.MAX_VALUE, Long.MAX_VALUE);
                fileFolderService.createNewFolder(lockFolder);
                // We locked this, so the load can be scheduled.
                // The loader will remove the lock when it completes
                DBObject loadData = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, emptyFolder.getContext())
                        .add(FIELD_PATH, emptyFolder.getPath())
                        .add(FIELD_ROOT_CATEGORIES_TO_CREATE, Integer.valueOf(rootCategoriesToCreate))
                        .add(FIELD_CATEGORIES_TO_CREATE, Integer.valueOf(0))
                        .add(FIELD_FOLDERS_TO_CREATE, Integer.valueOf(0)).get();
                Event loadEvent = new Event(eventNameLoadRecordCategories, loadData);
                // Each load event must be associated with a session
                String sessionId = sessionService.startSession(loadData);
                loadEvent.setSessionId(sessionId);
                // Add the event to the list
                nextEvents.add(loadEvent);
            } catch (Exception e) {
                // The lock was already applied; find another
                continue;
            }
            // Check if we have enough
            if (nextEvents.size() >= loaderSessionsToCreate) {
                break;
            }
        }
        skip += limit;
    }
}

From source file:org.alfresco.bm.dataload.rm.fileplan.ScheduleFilePlanLoaders.java

License:Open Source License

/**
 * Helper method for preparing the load events for record categories children and record folders children without the last level of record folders.
 *
 * @param loaderSessionsToCreate - the number of still active loader sessions
 * @param nextEvents - list of prepared events
 *///from   w  ww.j  a  va2  s . c  o  m
private void prepareSubCategoriesAndRecordFolders(int loaderSessionsToCreate, List<Event> nextEvents) {
    int skip = 0;
    int limit = 100;
    while (nextEvents.size() < loaderSessionsToCreate) {
        // Get categories needing loading
        // the maximum number of children a folder should contain so that it will be picked up for further loading
        int maxChildren = folderNumber + childCategNumber - 1;
        List<FolderData> emptyFolders = fileFolderService.getFoldersByCounts(RECORD_CATEGORY_CONTEXT,
                Long.valueOf(FILE_PLAN_LEVEL + 1), //min level FILE_PLAN_LEVEL + 1 = 4, root categories
                Long.valueOf(maxLevel - 1), //last level will be for record folders, FILE_PLAN_LEVEL+depth-1 required
                0L, Long.valueOf(maxChildren), //maximum number of sub folders so that it will be picked up for further loading
                null, null, skip, limit);
        if (emptyFolders.size() == 0) {
            // The folders were populated in the mean time
            break;
        }
        // Schedule a load for each folder
        for (FolderData emptyFolder : emptyFolders) {
            int categoryCount = fileFolderService
                    .getChildFolders(RECORD_CATEGORY_CONTEXT, emptyFolder.getPath(), skip, limit).size();
            int folderCount = fileFolderService
                    .getChildFolders(RECORD_FOLDER_CONTEXT, emptyFolder.getPath(), skip, limit).size();

            int categoriesToCreate = childCategNumber - categoryCount;

            int foldersToCreate = 0;
            if (this.folderCategoryMix) {
                foldersToCreate = folderNumber - folderCount;
            }

            try {
                // Create a lock folder that has too many files and folders so that it won't be picked up
                // by this process in subsequent trawls
                String lockPath = emptyFolder.getPath() + "/locked";
                FolderData lockFolder = new FolderData(UUID.randomUUID().toString(), emptyFolder.getContext(),
                        lockPath, Long.MAX_VALUE, Long.MAX_VALUE);
                fileFolderService.createNewFolder(lockFolder);
                // We locked this, so the load can be scheduled.
                // The loader will remove the lock when it completes
                DBObject loadData = BasicDBObjectBuilder.start().add(FIELD_CONTEXT, emptyFolder.getContext())
                        .add(FIELD_PATH, emptyFolder.getPath())
                        .add(FIELD_ROOT_CATEGORIES_TO_CREATE, Integer.valueOf(0))
                        .add(FIELD_CATEGORIES_TO_CREATE, Integer.valueOf(categoriesToCreate))
                        .add(FIELD_FOLDERS_TO_CREATE, Integer.valueOf(foldersToCreate)).get();
                Event loadEvent = new Event(eventNameLoadRecordCategories, loadData);
                // Each load event must be associated with a session
                String sessionId = sessionService.startSession(loadData);
                loadEvent.setSessionId(sessionId);
                // Add the event to the list
                nextEvents.add(loadEvent);
            } catch (Exception e) {
                // The lock was already applied; find another
                continue;
            }
            // Check if we have enough
            if (nextEvents.size() >= loaderSessionsToCreate) {
                break;
            }
        }
        skip += limit;
    }
}