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.devicesync.dao.mongo.MongoMetricsService.java

License:Open Source License

@Override
public Stream<Metrics> getMetrics(int skip, int limit) {
    DBObject query = BasicDBObjectBuilder.start().get();
    DBObject orderBy = BasicDBObjectBuilder.start("timestampMS", 1).get();
    DBCursor cur = collection.find(query).sort(orderBy).skip(skip).limit(limit);
    Stream<Metrics> stream = StreamSupport.stream(cur.spliterator(), false).onClose(() -> cur.close()) // need to close cursor;
            .map(dbo -> Metrics.fromDBObject(dbo));
    return stream;
}

From source file:org.alfresco.bm.devicesync.eventprocessor.AbstractCMISEventProcessor.java

License:Open Source License

public final EventResult processEvent(Event event) throws Exception {
    try {/*from  w ww  .j  a v  a 2 s  .c o m*/
        return processCMISEvent(event);
    } catch (CmisRuntimeException e) {
        String error = e.getMessage();
        String stack = ExceptionUtils.getStackTrace(e);
        // Grab the CMIS information
        DBObject data = BasicDBObjectBuilder.start().append("msg", error).append("stack", stack)
                .push("cmisFault").append("code", "" + e.getCode()) // BigInteger is not
                // Serializable
                .append("errorContent", e.getErrorContent()).pop().get();
        // Build failure result
        return new EventResult(data, false);
    } catch (RuntimeException e) {
        e.printStackTrace();
        return new EventResult(BasicDBObjectBuilder.start().append("msg", "Exception uploading document.")
                .append("exception", e.getMessage()).get(), false);
    }
}

From source file:org.alfresco.bm.devicesync.eventprocessor.GetFile.java

License:Open Source License

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

    DBObject dbObject = (DBObject) event.getData();
    String username = (String) dbObject.get("username");
    String path = (String) dbObject.get("path");

    try {//  ww  w .  j a  v a2 s . c  om
        super.resumeTimer(); // Timer control
        DBObject downloadResult = downloadFileHelper.download(username, path);
        super.suspendTimer(); // Timer control

        // Done
        Event doneEvent = new Event(eventNameFileDownloaded, downloadResult);
        EventResult result = new EventResult(BasicDBObjectBuilder.start()
                .append("msg", "Successfully downloaded document.").append("result", downloadResult).get(),
                doneEvent);

        // Done
        return result;
    } catch (UploadFileException e) {
        e.printStackTrace();
        return new EventResult(
                BasicDBObjectBuilder.start().append("msg", "Exception downloading document.")
                        .append("exception", e.getE().getMessage()).append("document", e.getData()).get(),
                false);
    } catch (Exception e) {
        e.printStackTrace();
        return new EventResult(BasicDBObjectBuilder.start().append("msg", "Exception downloading document.")
                .append("exception", e.getMessage()).get(), false);
    }
}

From source file:org.alfresco.bm.devicesync.eventprocessor.UploadFileForSubscription.java

License:Open Source License

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

    DBObject dbObject = (DBObject) event.getData();
    UploadFileData uploadFileData = UploadFileData.fromDBObject(dbObject);
    String subscriptionId = uploadFileData.getSubscriptionId();
    SubscriptionData subscriptionData = subscriptionsService.getSubscription(subscriptionId);

    try {/*w  ww. jav  a  2s  .c o m*/
        DBObject data = uploadFileHelper.doUpload(uploadFileData, subscriptionData, new UploadListener() {
            @Override
            public void beforeUpload() {
                UploadFileForSubscription.super.resumeTimer(); // Timer
                                                               // control
            }

            @Override
            public void afterUpload() {
                UploadFileForSubscription.super.stopTimer(); // Timer
                                                             // control
            }

            @Override
            public void onException(Exception e) {
                UploadFileForSubscription.super.stopTimer(); // Timer
                                                             // control
            }
        }, super.getName());

        // Done
        Event doneEvent = new Event(eventNameFileUploaded, data);
        EventResult result = new EventResult(BasicDBObjectBuilder.start()
                .append("msg", "Successfully uploaded document.").append("document", data).get(), doneEvent);

        // Done
        return result;
    } catch (UploadFileException e) {
        return new EventResult(
                BasicDBObjectBuilder.start().append("msg", "Exception uploading document.")
                        .append("exception", e.getE().getMessage()).append("document", e.getData()).get(),
                false);
    }
}

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   www. ja v  a  2  s . com
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

@Override
public Event getEvent(String id) {
    DBObject queryObj = BasicDBObjectBuilder.start().add(Event.FIELD_ID, new ObjectId(id)).get();
    DBObject eventObj = collection.findOne(queryObj);
    Event event = null;//from  w  ww.j av  a  2 s . c o m
    if (eventObj != null) {
        event = convertDBObject(eventObj);
    }

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Fetched event for ID '" + id + ": " + event);
    }
    return event;
}

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

License:Open Source License

/**
 * {@inheritDoc}//from w  ww  .  ja  va  2 s  . c  o  m
 */
@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.MongoEventService.java

License:Open Source License

@Override
public boolean deleteEvent(Event event) {
    String id = event.getId();/*  w w  w. j a  v  a2  s  .  c  o m*/
    DBObject queryObj = BasicDBObjectBuilder.start().add(Event.FIELD_ID, new ObjectId(id)).get();
    // Drop any associated memory data
    runLocalData.remove(id);

    WriteResult wr = collection.remove(queryObj);
    if (wr.getN() != 1) {
        // Done
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to removed event: \n" + "   Event:  " + event + "\n" + "   Result: " + wr);
        }
        return false;
    } else {
        // Done
        if (logger.isDebugEnabled()) {
            logger.debug("Removed event: " + event);
        }
        return true;
    }
}

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.");
    }//from   w  ww .  ja 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.event.mongo.MongoResultService.java

License:Open Source License

@Override
public EventRecord getFirstResult() {
    DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(1)).get();

    DBObject resultObj = collection.findOne(null, null, sortObj);
    EventRecord result = convertToEventRecord(resultObj);

    if (logger.isDebugEnabled()) {
        logger.debug("Found first result: " + result);
    }/*from  ww  w. ja v  a  2 s.  c om*/
    return result;
}