Example usage for com.mongodb QueryBuilder put

List of usage examples for com.mongodb QueryBuilder put

Introduction

In this page you can find the example usage for com.mongodb QueryBuilder put.

Prototype

public QueryBuilder put(final String key) 

Source Link

Document

Adds a new key to the query if not present yet.

Usage

From source file:com.ccoe.build.alerts.connector.Connector.java

License:Apache License

public static DBObject getLastRecord(DBCollection collection, Date startDate, Date endDate) {
    DBObject lastone = null;// www. j a v  a2  s.c o m
    try {
        BasicDBObject searchQuery = new BasicDBObject();
        QueryBuilder qb = new QueryBuilder();
        qb.put("Date").greaterThanEquals(startDate).lessThanEquals(endDate);
        searchQuery.putAll(qb.get());
        DBCursor cursor = collection.find(searchQuery);

        while (cursor.hasNext()) {

            lastone = cursor.next();
        }

    } catch (MongoException e) {
        e.printStackTrace();

    }
    return lastone;
}

From source file:com.ccoe.build.alerts.connector.Connector.java

License:Apache License

public static double getMovingAverage(DBCollection collection, String field, Date startDate, Date endDate) {
    double weekSum = 0;
    DBObject record = null;//from  w  ww. j ava 2 s .co m
    int count = 0;
    try {
        BasicDBObject searchQuery = new BasicDBObject();
        QueryBuilder qb = new QueryBuilder();
        qb.put("Date").greaterThanEquals(startDate).lessThanEquals(endDate);
        searchQuery.putAll(qb.get());
        DBCursor cursor = collection.find(searchQuery);

        while (cursor.hasNext()) {
            record = cursor.next();
            DBObject dbo = (DBObject) record.get("Data");
            Set<String> keySet = dbo.keySet();

            for (String keyName : keySet) {
                if (field.equals(keyName)) {
                    count++;
                    Object keyValue = dbo.get(keyName);
                    double keyValueNum = 0;
                    if (keyValue instanceof Integer) {
                        int intValue = (Integer) keyValue;
                        keyValueNum = Double.parseDouble("" + intValue);
                    } else if (keyValue instanceof Double) {
                        keyValueNum = (Double) keyValue;
                    }
                    weekSum += keyValueNum;
                }
            }
        }
    } catch (MongoException e) {
        e.printStackTrace();
    }
    DAYS = count;
    return weekSum * 1.0 / count;
}

From source file:com.linuxbox.enkive.audit.mongodb.MongoAuditService.java

License:Open Source License

/**
 * If there is a username, then we hint to use that index, as we expect
 * there to be many users compared to event codes. Thus it is likely that
 * generally filtering by users will reduce the result set by the greatest
 * amount. Of course some event codes are more prevalent than others, so
 * this won't always be the case./*from   w  w w  . j av a  2s.co m*/
 * 
 * @param startTime
 *            all results must occur ON or AFTER this timestamp
 * @param endTime
 *            all results must occur BEFORE this timestamp
 * @throws AuditServiceException
 */
@Override
public List<AuditEntry> search(Integer eventCode, String userIdentifier, Date startTime, Date endTime)
        throws AuditServiceException {
    final QueryBuilder qb = QueryBuilder.start();
    String indexHint = TIMESTAMP_INDEX;

    if (eventCode != null) {
        qb.put(CODE_FIELD).is(eventCode);
        indexHint = CODE_TIMESTAMP_INDEX;
    }
    if (userIdentifier != null) {
        qb.put(USERNAME_FIELD).is(userIdentifier);
        indexHint = CODE_TIMESTAMP_INDEX;
    }
    if (startTime != null) {
        final int epochTime = (int) (startTime.getTime() / 1000);
        final BSONTimestamp timestamp = new BSONTimestamp(epochTime, 0);
        qb.put(TIMESTAMP_FIELD).greaterThanEquals(timestamp);
    }
    if (endTime != null) {
        final int epochTime = (int) (Math.ceil(endTime.getTime() / 1000.0));
        final BSONTimestamp timestamp = new BSONTimestamp(epochTime, 0);
        qb.put(TIMESTAMP_FIELD).lessThan(timestamp);
    }

    final DBCursor cursor = auditCollection.find(qb.get()).sort(DATE_BACKWARD_SORT).hint(indexHint);
    return dbCursortoAuditEntryList(cursor);
}

From source file:com.naryx.tagfusion.expression.function.string.serializejson.java

License:Open Source License

public void encodeJSON(StringBuilder out, cfData var, boolean serializeQueryByColumns, CaseType caseConversion,
        DateType datetype) throws dataNotSupportedException {

    if (var == null || var.getDataType() == cfData.CFNULLDATA) {
        out.append("null");

    } else if (var.getDataType() == cfData.CFSTRINGDATA) {

        /*/*  w  w  w . j  a  v a2  s.c om*/
         * Encode Strings
         */
        out.append("\"" + encodeString(var.getString()) + "\"");

    } else if (var.getDataType() == cfData.CFBOOLEANDATA) {

        /*
         * Boolean Data
         */
        out.append(var.getBoolean() ? "true" : "false");

    } else if (var.getDataType() == cfData.CFDATEDATA) {

        /*
         * Encode Date
         */
        Date localeDate = (Date) ((cfDateData) var).getUnderlyingInstance();

        if (datetype == DateType.LONG)
            out.append("\"" + dateLongFormat.format(localeDate) + "\"");
        else if (datetype == DateType.HTTP)
            out.append("\"" + dateHTTPFormat.format(localeDate) + "\"");
        else if (datetype == DateType.JSON)
            out.append("\"" + dateJSONFormat.format(localeDate) + "\"");
        else if (datetype == DateType.MONGO)
            out.append("{$date:\"" + dateMongoFormat.format(localeDate) + "\"}");
        else
            out.append("\"" + var.getString() + "\"");

    } else if (cfData.isSimpleValue(var)) {

        /*
         * Encode numbers and booleans
         */
        out.append(var.getString());

    } else if (var.getDataType() == cfData.CFARRAYDATA) {

        /*
         * Encode Arrays
         */
        out.append("[");

        cfArrayData cfarraydata = (cfArrayData) var;
        for (int x = 0; x < cfarraydata.size(); x++) {
            encodeJSON(out, cfarraydata.getElement(x + 1), serializeQueryByColumns, caseConversion, datetype);

            if (x < cfarraydata.size() - 1)
                out.append(",");
        }
        out.append("]");

    } else if (var.getDataType() == cfData.CFSTRUCTDATA) {

        /*
         * Encode Structs
         */
        out.append("{");

        cfStructData cfstructdata = (cfStructData) var;
        Object[] keys = cfstructdata.keys();
        String key, value = null;
        for (int x = 0; x < keys.length; x++) {
            key = (String) keys[x];

            if (caseConversion == CaseType.LOWER)
                value = key.toLowerCase();
            else if (caseConversion == CaseType.UPPER)
                value = key.toUpperCase();
            else if (caseConversion == CaseType.MAINTAIN)
                value = key;

            out.append("\"" + encodeString(value) + "\"");
            out.append(":");
            encodeJSON(out, cfstructdata.getData(key), serializeQueryByColumns, caseConversion, datetype);

            if (x < keys.length - 1)
                out.append(",");
        }

        out.append("}");

    } else if (var.getDataType() == cfData.CFQUERYRESULTDATA) {

        /*
         * Encode Query
         */
        out.append("{");

        if (serializeQueryByColumns)
            encodeQueryByColumnsJSON(out, (cfQueryResultData) var, serializeQueryByColumns, caseConversion,
                    datetype);
        else
            encodeQueryByRowsJSON(out, (cfQueryResultData) var, serializeQueryByColumns, caseConversion,
                    datetype);

        out.append("}");

    } else if (var.getDataType() == cfData.CFJAVAOBJECTDATA) {
        Object o = ((cfJavaObjectData) var).getUnderlyingInstance();
        if (o instanceof org.bson.types.ObjectId)
            out.append("{$oid:\"" + ((org.bson.types.ObjectId) o).toString() + "\"}");
        else if (o instanceof java.util.regex.Pattern) {

            QueryBuilder qb = new QueryBuilder();
            qb.put("tmp");
            qb.regex((java.util.regex.Pattern) o);
            String json = qb.get().toString();
            json = json.substring(json.indexOf("{", 1), json.lastIndexOf("}"));
            out.append(json);

        } else
            out.append("\"" + encodeString(String.valueOf(o)) + "\"");
    } else {
        out.append("\"unsupported\"");
    }
}

From source file:net.atos.entng.calendar.services.impl.EventServiceMongoImpl.java

License:Open Source License

@Override
public void retrieve(String calendarId, String eventId, UserInfos user,
        Handler<Either<String, JsonObject>> handler) {
    // Query/*from  w  w w  .  j a  va 2  s.  c om*/
    QueryBuilder query = QueryBuilder.start("_id").is(eventId);
    query.put("calendar").is(calendarId);

    // Projection
    JsonObject projection = new JsonObject();

    mongo.findOne(this.collection, MongoQueryBuilder.build(query), projection, validResultHandler(handler));
}

From source file:net.atos.entng.calendar.services.impl.EventServiceMongoImpl.java

License:Open Source License

@Override
public void retrieveByIcsUid(String calendarId, String icsUid, UserInfos user,
        Handler<Either<String, JsonObject>> handler) {
    // Query// w  w w. j a  va 2  s. co  m
    QueryBuilder query = QueryBuilder.start("icsUid").is(icsUid);
    query.put("calendar").is(calendarId);

    // Projection
    JsonObject projection = new JsonObject();

    mongo.findOne(this.collection, MongoQueryBuilder.build(query), projection, validResultHandler(handler));
}

From source file:net.atos.entng.calendar.services.impl.EventServiceMongoImpl.java

License:Open Source License

@Override
public void update(String calendarId, String eventId, JsonObject body, UserInfos user,
        Handler<Either<String, JsonObject>> handler) {
    // Query/*from   w w w.  j  ava2  s.  c  o m*/
    QueryBuilder query = QueryBuilder.start("_id").is(eventId);
    query.put("calendar").is(calendarId);

    // Clean data
    body.removeField("_id");
    body.removeField("calendar");

    // Modifier
    MongoUpdateBuilder modifier = new MongoUpdateBuilder();
    for (String attr : body.getFieldNames()) {
        modifier.set(attr, body.getValue(attr));
    }
    modifier.set("modified", MongoDb.now());
    mongo.update(this.collection, MongoQueryBuilder.build(query), modifier.build(),
            validActionResultHandler(handler));

}

From source file:net.atos.entng.calendar.services.impl.EventServiceMongoImpl.java

License:Open Source License

@Override
public void delete(String calendarId, String eventId, UserInfos user,
        Handler<Either<String, JsonObject>> handler) {
    QueryBuilder query = QueryBuilder.start("_id").is(eventId);
    query.put("calendar").is(calendarId);
    mongo.delete(this.collection, MongoQueryBuilder.build(query), validActionResultHandler(handler));

}

From source file:net.atos.entng.forum.services.impl.MongoDbMessageService.java

License:Open Source License

@Override
public void create(final String categoryId, final String subjectId, final JsonObject body, final UserInfos user,
        final Handler<Either<String, JsonObject>> handler) {
    // Prepare Message object
    final ObjectId newId = new ObjectId();
    JsonObject now = MongoDb.now();/*from w w  w . j a  va  2  s .  c o  m*/
    body.putString("_id", newId.toStringMongod())
            .putObject("owner",
                    new JsonObject().putString("userId", user.getUserId()).putString("displayName",
                            user.getUsername()))
            .putString("contentPlain", StringUtils.stripHtmlTag(body.getString("content", "")))
            .putObject("created", now).putObject("modified", now);

    // Prepare Query
    QueryBuilder query = QueryBuilder.start("_id").is(subjectId);
    query.put("category").is(categoryId);
    MongoUpdateBuilder modifier = new MongoUpdateBuilder();
    modifier.push("messages", body);
    modifier.inc("nbMessages", 1);
    modifier.set("modified", MongoDb.now());

    // Execute query
    mongo.update(subjects_collection, MongoQueryBuilder.build(query), modifier.build(),
            validActionResultHandler(new Handler<Either<String, JsonObject>>() {
                @Override
                public void handle(Either<String, JsonObject> event) {
                    if (event.isRight()) {
                        try {
                            if (event.right().getValue().getNumber("number").intValue() == 1) {
                                // Respond with created message Id
                                JsonObject created = new JsonObject();
                                created.putString("_id", newId.toStringMongod());
                                handler.handle(new Either.Right<String, JsonObject>(created));
                            } else {
                                handler.handle(new Either.Left<String, JsonObject>("Subject not found"));
                            }
                        } catch (Exception e) {
                            handler.handle(new Either.Left<String, JsonObject>(
                                    "Malformed response : " + e.getClass().getName() + " : " + e.getMessage()));
                        }
                    } else {
                        handler.handle(event);
                    }
                }
            }));
}

From source file:net.atos.entng.forum.services.impl.MongoDbMessageService.java

License:Open Source License

@Override
public void checkIsSharedOrMine(final String categoryId, final String subjectId, final String messageId,
        final UserInfos user, final String sharedMethod, final Handler<Boolean> handler) {
    // Prepare Category Query
    final QueryBuilder methodSharedQuery = QueryBuilder.start();
    prepareIsSharedMethodQuery(methodSharedQuery, user, categoryId, sharedMethod);

    // Check Category Sharing with method
    executeCountQuery(categories_collection, MongoQueryBuilder.build(methodSharedQuery), 1,
            new Handler<Boolean>() {
                @Override/*from   ww w  .  ja v  a2 s .com*/
                public void handle(Boolean event) {
                    if (event) {
                        handler.handle(true);
                    } else {
                        // Prepare Category Query
                        final QueryBuilder anySharedQuery = QueryBuilder.start();
                        prepareIsSharedAnyQuery(anySharedQuery, user, categoryId);

                        // Check Category Sharing with any method
                        executeCountQuery(categories_collection, MongoQueryBuilder.build(anySharedQuery), 1,
                                new Handler<Boolean>() {
                                    @Override
                                    public void handle(Boolean event) {
                                        if (event) {
                                            // Prepare Subject and Message query
                                            QueryBuilder query = QueryBuilder.start("_id").is(subjectId)
                                                    .put("category").is(categoryId);

                                            DBObject messageMatch = new BasicDBObject();
                                            messageMatch.put("_id", messageId);
                                            messageMatch.put("owner.userId", user.getUserId());
                                            query.put("messages").elemMatch(messageMatch);

                                            // Check Message is mine
                                            executeCountQuery(subjects_collection,
                                                    MongoQueryBuilder.build(query), 1, handler);
                                        } else {
                                            handler.handle(false);
                                        }
                                    }
                                });
                    }
                }
            });
}