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.cmis.CreateFolder.java

License:Open Source License

@Override
protected EventResult processCMISEvent(Event event) throws Exception {
    // Suspect timer
    super.suspendTimer();

    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to create folder; no session provided.", false);
    }/*from w  ww. j ava2s.c om*/
    if (data.getBreadcrumb().isEmpty()) {
        return new EventResult("Unable to create folder; no folder provided.", false);
    }
    Folder folder = data.getBreadcrumb().getLast();

    // The folder name
    String newFolderName = UUID.randomUUID().toString() + "-" + super.getName();

    Map<String, String> newFolderProps = new HashMap<String, String>();
    newFolderProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
    newFolderProps.put(PropertyIds.NAME, newFolderName);

    super.resumeTimer();
    Folder newFolder = folder.createFolder(newFolderProps);
    super.stopTimer();

    // Append it to the breadcrumb
    data.getBreadcrumb().add(newFolder);

    // Done
    Event doneEvent = new Event(eventNameFolderCreated, data);
    EventResult result = new EventResult(
            BasicDBObjectBuilder.start().append("msg", "Successfully created folder.").push("folder")
                    .append("id", newFolder.getId()).append("name", newFolder.getName()).pop().get(),
            doneEvent);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.DeleteFolder.java

License:Open Source License

@Override
protected EventResult processCMISEvent(Event event) throws Exception {
    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to get CMIS root folder; no session provided.", false);
    }//from  w  w  w .ja  v a 2s .  c  o m
    LinkedList<Folder> breadcrumb = data.getBreadcrumb();
    if (breadcrumb.size() < 2) {
        return new EventResult("We need at least two folders to work with.", false);
    }

    // Delete the last folder
    Folder folder = breadcrumb.getLast();
    folder.deleteTree(true, UnfileObject.DELETE, false);

    // Append it to the breadcrumb
    data.getBreadcrumb().removeLast();

    // Done
    Event doneEvent = new Event(eventNameFolderDeleted, data);
    EventResult result = new EventResult(
            BasicDBObjectBuilder.start().append("msg", "Successfully deleted folder.").push("folder")
                    .append("id", folder.getId()).append("name", folder.getName()).pop().get(),
            doneEvent);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.DownloadFile.java

License:Open Source License

@Override
protected EventResult processCMISEvent(Event event) throws Exception {
    super.suspendTimer(); // Timer control

    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to download file; no session provided.", false);
    }// ww  w  .  j a v a  2  s. c o  m
    if (data.getBreadcrumb().size() == 0) {
        return new EventResult("Unable to download file; no folder provided.", false);
    }
    if (data.getDocument() == null) {
        return new EventResult("Unable to download file; no file provided.", false);
    }
    // Go to the folder
    Document document = data.getDocument();
    String filename = document.getName();
    // We will need this to look it up by path
    Folder folder = data.getBreadcrumb().getLast();
    String folderPath = folder.getPath();

    // The path
    String path = folderPath + "/" + filename;

    super.resumeTimer(); // Timer control
    // Look it up.
    try {
        CmisObject foundObj = data.getSession().getObjectByPath(path);
        if (!(foundObj instanceof Document)) {
            return new EventResult(
                    "Recently-created document not found at '" + path + "', but found " + foundObj, false);
        }
        document = (Document) foundObj;
    } catch (CmisObjectNotFoundException e) {
        return new EventResult("Unable to find recently-created document: " + path, false);
    }
    // Now download
    ContentStream cs = document.getContentStream();
    if (cs == null) {
        return new EventResult("Recently-created document has no content: " + path, false);
    }
    InputStream is = cs.getStream();
    File file = null;
    long fileSize = 0L;
    try {
        file = File.createTempFile(getName(), ".tmp");
        FileUtils.copyInputStreamToFile(is, file);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        // Stop the timer, here
        super.stopTimer(); // Timer control
        // Remove the local file
        if (file != null) {
            fileSize = file.length();
            FileUtils.deleteQuietly(file);
        }
    }

    // Done
    Event doneEvent = new Event(eventNameFileDownloaded, data);
    EventResult result = new EventResult(
            BasicDBObjectBuilder.start().append("msg", "Successfully downloaded document.").push("document")
                    .append("id", document.getId()).append("name", document.getName())
                    .append("paths", document.getPaths()).append("size", fileSize).pop().get(),
            doneEvent);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.FindFolder.java

License:Open Source License

@Override
protected EventResult processCMISEvent(Event event) throws Exception {
    super.suspendTimer(); // Timer control

    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to search for folder; no session provided.", false);
    }/*from  w w w  .jav  a  2  s  .co m*/
    Session session = data.getSession();

    super.resumeTimer(); // Timer control

    String typeStr = "cmis:folder";

    // Get the query name of cmis:objectId
    ObjectType type = session.getTypeDefinition(typeStr);
    PropertyDefinition<?> objectIdPropDef = type.getPropertyDefinitions().get(PropertyIds.OBJECT_ID);
    String objectIdQueryName = objectIdPropDef.getQueryName();
    String query = "SELECT " + objectIdQueryName + " FROM " + type.getQueryName();

    // execute query
    ItemIterable<QueryResult> queryResults = session.query(query, false);

    long totalResults = queryResults.getTotalNumItems(); // For information only
    Folder folder = null;
    if (totalResults == 0L) {
        return new EventResult("No folders found.  Unable to do folder listing.", false);
    }
    if (totalResults == -1L) {
        return new EventResult("Result size unknown.  Unable to choose a random folder.", false);
    }
    // Choose a random skip value
    long skip = (long) (Math.random() * (double) totalResults);

    Iterable<QueryResult> pageQueryResults = queryResults.skipTo(skip);
    Iterator<QueryResult> pageQueryIterator = pageQueryResults.iterator();
    if (pageQueryIterator.hasNext()) {
        QueryResult result = pageQueryIterator.next();
        String objectId = result.getPropertyValueByQueryName(objectIdQueryName);
        folder = (Folder) session.getObject(session.createObjectId(objectId));
    } else {
        return new EventResult(
                "Skipped to position with no result.  Total: " + totalResults + ".  Skipped: " + skip, false);
    }

    super.stopTimer(); // Timer control

    // Attach the folder to the data
    data.getBreadcrumb().add(folder);

    // Done
    Event doneEvent = new Event(eventNameFolderFound, data);
    EventResult result = new EventResult(BasicDBObjectBuilder.start()
            .append("msg", "Successfully selected random folder.").append("query", query).push("paging")
            .append("total", totalResults).append("skippedTo", skip).pop().push("folder")
            .append("id", folder.getId()).append("name", folder.getName()).pop().get(), doneEvent);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.ListFolderContents.java

License:Open Source License

@Override
@SuppressWarnings("unused")
protected EventResult processCMISEvent(Event event) throws Exception {
    super.suspendTimer(); // Timer control

    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to get CMIS root folder; no session provided.", false);
    }//from  ww  w.ja  v a 2 s.c o  m
    if (data.getBreadcrumb().isEmpty()) {
        return new EventResult("Unable to get CMIS folder listing; no folder provided.", false);
    }
    Folder folder = data.getBreadcrumb().getLast();

    // Get details of how to page, etc
    OperationContext ctx = data.getSession().getDefaultContext();
    int pageSize = ctx.getMaxItemsPerPage();

    super.resumeTimer(); // Timer control
    ItemIterable<CmisObject> children = folder.getChildren();
    long totalChildren = children.getTotalNumItems(); // For information only
    int pageCount = 0;
    // We have to iterate using paging
    long skip = 0L;
    ItemIterable<CmisObject> pageOfChildren = children.skipTo(skip);
    while (pageOfChildren.getPageNumItems() > 0L) {
        pageCount++;
        for (CmisObject cmisObject : pageOfChildren) {
            skip++;
        }
        // Get the next page of children
        pageOfChildren = children.skipTo(skip);
    }
    super.stopTimer(); // Timer control

    // Done
    Event doneEvent = new Event(eventNameFolderContentsListed, data);
    EventResult result = new EventResult(BasicDBObjectBuilder.start()
            .append("msg", "Successfully retrieved folder listing.").push("folder").append("id", folder.getId())
            .append("name", folder.getName()).push("paging").append("pageSize", pageSize)
            .append("totalChildren", totalChildren).append("pageCount", pageCount).pop().get(), doneEvent);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.RetrieveTestFolder.java

License:Open Source License

@Override
protected EventResult processCMISEvent(Event event) throws Exception {
    super.suspendTimer(); // Timer control

    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to get CMIS test folder; no session provided.", false);
    }//  w w w .  j ava  2s.c om

    // Get the session
    Session session = data.getSession();

    super.resumeTimer(); // Timer control
    Folder folder = FileUtils.getFolder(path, session);
    super.stopTimer(); // Timer control
    if (folder == null) {
        return new EventResult("Failed to find test folder at path " + path, false);
    }

    // Store the folder
    data = new CMISEventData(data);
    data.getBreadcrumb().clear();
    data.getBreadcrumb().add(folder);

    // Done
    Event doneEvent = new Event(eventNameTestFolderRetrieved, data);
    EventResult result = new EventResult(BasicDBObjectBuilder.start()
            .append("msg", "Successfully retrieved test folder.").push("folder").append("id", folder.getPath())
            .append("id", folder.getId()).append("name", folder.getName()).pop().get(), doneEvent);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.SearchInFolder.java

License:Open Source License

@Override
@SuppressWarnings("unused")
protected EventResult processCMISEvent(Event event) throws Exception {
    super.suspendTimer(); // Timer control

    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to upload file; no session provided.", false);
    }//w  w w . j a  v a  2  s . c  om
    if (data.getBreadcrumb().isEmpty()) {
        return new EventResult("Unable to upload file; no folder provided.", false);
    }
    Folder folder = data.getBreadcrumb().getLast();

    // Get details of how to page, etc
    OperationContext ctx = data.getSession().getDefaultContext();
    int pageSize = ctx.getMaxItemsPerPage();

    // Get a random string
    String[] searchStrings = getSearchStrings();
    String searchString = AbstractCMISEventProcessor.getRandomSearchString(searchStrings);
    String query = String.format("SELECT D.* FROM cmis:document D WHERE IN_FOLDER('%s') AND CONTAINS('%s')",
            folder.getId(), searchString);

    super.resumeTimer();
    ItemIterable<QueryResult> queryResults = data.getSession().query(query, false);
    long totalResults = queryResults.getTotalNumItems(); // For information only
    int pageCount = 0;
    // We have to iterate using paging
    long skip = 0L;
    ItemIterable<QueryResult> pageOfResults = queryResults.skipTo(skip);
    while (pageOfResults.getPageNumItems() > 0L) {
        pageCount++;
        for (QueryResult queryResult : pageOfResults) {
            skip++;
        }
        // Get the next page of children
        pageOfResults = queryResults.skipTo(skip);
    }
    super.stopTimer(); // Timer control

    // Done
    Event doneEvent = new Event(eventNameSearchCompleted, data);
    EventResult result = new EventResult(
            BasicDBObjectBuilder.start().append("msg", "Successfully searched in folder.")
                    .append("query", query).push("folder").append("id", folder.getId())
                    .append("name", folder.getName()).push("paging").append("pageSize", pageSize)
                    .append("totalResults", totalResults).append("pageCount", pageCount).pop().get(),
            doneEvent);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.StartCMISSession.java

License:Open Source License

@Override
protected EventResult processCMISEvent(Event event) throws Exception {
    String username = (String) event.getData();
    // A quick double-check
    if (username == null) {
        return new EventResult("Unable to start CMIS session without a username.", false);
    }/*from w  w  w . j a  v  a 2 s  . c  o  m*/
    UserData user = userDataService.findUserByUsername(username);
    if (user == null) {
        return new EventResult("Unable to start CMIS session; user no longer exists: " + username, false);
    }
    String password = user.getPassword();

    // Build session parameters
    Map<String, String> parameters = new HashMap<String, String>();
    if (bindingType != null && bindingType.equals(BindingType.ATOMPUB.value())) {
        parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
        parameters.put(SessionParameter.ATOMPUB_URL, bindingUrl);
    } else if (bindingType != null && bindingType.equals(BindingType.BROWSER.value())) {
        parameters.put(SessionParameter.BINDING_TYPE, BindingType.BROWSER.value());
        parameters.put(SessionParameter.BROWSER_URL, bindingUrl);
    } else {
        return new EventResult("Unsupported CMIS binding type: " + bindingType, false);
    }
    parameters.put(SessionParameter.USER, username);
    parameters.put(SessionParameter.PASSWORD, password);

    // First check if we need to choose a repository
    SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
    List<Repository> repositories = sessionFactory.getRepositories(parameters);
    if (repositories.size() == 0) {
        return new EventResult("Unable to find any repositories at " + bindingUrl + " with user " + username,
                false);
    }
    if (repositoryId.equals(REPOSITORY_ID_USE_FIRST)) {
        String repositoryIdFirst = repositories.get(0).getId();
        parameters.put(SessionParameter.REPOSITORY_ID, repositoryIdFirst);
    } else {
        parameters.put(SessionParameter.REPOSITORY_ID, repositoryId);
    }

    // Create the session
    Session session = SessionFactoryImpl.newInstance().createSession(parameters);
    session.setDefaultContext(ctx);

    // get repository info
    RepositoryInfo repositoryInfo = session.getRepositoryInfo();
    CMISEventData cmisData = new CMISEventData(session);

    super.stopTimer(); // Timer control

    // Done
    Event doneEvent = new Event(eventNameSessionStarted, cmisData);
    EventResult result = new EventResult(
            BasicDBObjectBuilder.start().append("msg", "Successfully created CMIS session.")
                    .append("repository", parameters.get(SessionParameter.REPOSITORY_ID))
                    .append("user", username).append("ctx", convertOperationContext(ctx)).get(),
            doneEvent);

    // Start a load test session
    DBObject sessionObj = new BasicDBObject().append("repository", repositoryInfo.toString()).append("user",
            username);
    String sessionId = sessionService.startSession(sessionObj);
    doneEvent.setSessionId(sessionId);

    // Done
    return result;
}

From source file:org.alfresco.bm.cmis.StartCMISSession.java

License:Open Source License

/**
 * Convert an operation context into a DBObject for neat, searchable persistence
 */// w  ww . j  a  v a 2  s.  c  o  m
public static DBObject convertOperationContext(OperationContext ctx) {
    return BasicDBObjectBuilder.start().append("pageSize", ctx.getMaxItemsPerPage())
            .append("orderBy", ctx.getOrderBy()).append("cacheEnabled", ctx.isCacheEnabled())
            .append("includeAcls", ctx.isIncludeAcls())
            .append("includeAllowableActions", ctx.isIncludeAllowableActions())
            .append("includePathSegments", ctx.isIncludePathSegments())
            .append("includePolicies", ctx.isIncludePolicies()).get();
}

From source file:org.alfresco.bm.cmis.UploadFile.java

License:Open Source License

@Override
protected EventResult processCMISEvent(Event event) throws Exception {
    super.suspendTimer(); // Timer control

    CMISEventData data = (CMISEventData) event.getData();
    // A quick double-check
    if (data == null) {
        return new EventResult("Unable to upload file; no session provided.", false);
    }//from   w w  w .  j a  v  a 2s.  c om
    if (data.getBreadcrumb().isEmpty()) {
        return new EventResult("Unable to upload file; no folder provided.", false);
    }
    Folder folder = data.getBreadcrumb().getLast();

    // The file name
    File file = testFileService.getFile();
    if (file == null) {
        return new EventResult("No test files exist for upload: " + testFileService, false);
    }
    String filename = UUID.randomUUID().toString() + "-" + super.getName() + "-" + file.getName();

    Map<String, String> newFileProps = new HashMap<String, String>();
    newFileProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
    newFileProps.put(PropertyIds.NAME, filename);

    // Open up a stream to the file
    InputStream is = new BufferedInputStream(new FileInputStream(file));
    Document newFile = null;
    try {
        long fileLen = file.length();
        ContentStream cs = new ContentStreamImpl(filename, BigInteger.valueOf(fileLen),
                "application/octet-stream", is);

        // Make sure we only time the document creation
        super.resumeTimer(); // Timer control
        newFile = folder.createDocument(newFileProps, cs, VersioningState.MAJOR);
        super.stopTimer(); // Timer control
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    // Append it to the breadcrumb
    data.setDocument(newFile);

    // Done
    Event doneEvent = new Event(eventNameFileUploaded, data);
    EventResult result = new EventResult(BasicDBObjectBuilder.start()
            .append("msg", "Successfully uploaded document.").push("document").append("id", newFile.getId())
            .append("name", newFile.getName()).append("paths", newFile.getPaths()).pop().get(), doneEvent);

    // Done
    return result;
}