Example usage for com.mongodb QueryBuilder QueryBuilder

List of usage examples for com.mongodb QueryBuilder QueryBuilder

Introduction

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

Prototype

public QueryBuilder() 

Source Link

Document

Creates a builder with an empty query

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;//  w  w  w.  java2s  .  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 ww  w  .ja va  2  s . c  o  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.docstore.mongogrid.MongoGridDocStoreService.java

License:Open Source License

void markAsIndexedHelper(String identifier, int status) throws DocStoreException {
    final DBObject identifierQuery = new QueryBuilder().and(FILENAME_KEY).is(identifier).get();

    final DBObject updateSet = BasicDBObjectBuilder.start().add(INDEX_STATUS_QUERY, status)
            .add(INDEX_TIMESTAMP_QUERY, new Date()).get();
    final BasicDBObject update = new BasicDBObject("$set", updateSet);

    final boolean doNotRemove = false;
    final boolean returnNewVersion = true;
    final boolean doNotUpsert = false;
    final DBObject doNotSort = null;

    DBObject result = filesCollection.findAndModify(identifierQuery, RETRIEVE_OBJECT_ID, doNotSort, doNotRemove,
            update, returnNewVersion, doNotUpsert);
    if (result == null) {
        throw new DocStoreException(
                "could not mark document '" + identifier + "' with indexing status of " + status + ".");
    } else {//from   w  w  w .  j  av a2  s.c  o  m
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(
                    "Marked document " + result.get(OBJECT_ID_KEY) + " with index status of " + status + ".");
        }
    }
}

From source file:com.linuxbox.enkive.docstore.mongogrid.MongoGridDocStoreService.java

License:Open Source License

private DBObject createUnindexedQuery(int shardKeyLow, int shardKeyHigh) {
    QueryBuilder protoQuery = new QueryBuilder();

    protoQuery.and(INDEX_STATUS_QUERY).is(STATUS_UNINDEXED);

    if (shardKeyLow > 0) {
        protoQuery.and(INDEX_SHARD_QUERY).greaterThanEquals(shardKeyLow);
    }//from  www.  j  a va  2  s . c om

    if (shardKeyHigh < INDEX_SHARD_KEY_COUNT) {
        protoQuery.and(INDEX_SHARD_QUERY).lessThan(shardKeyHigh);
    }

    final DBObject finalQuery = protoQuery.get();
    return finalQuery;
}

From source file:com.linuxbox.util.lockservice.mongodb.MongoLockService.java

License:Open Source License

/**
 * Releases control of the identifier by removing the record. If the record
 * does not exist then throw a ControlReleaseException.
 * // w w w. j  a v  a  2  s .  co  m
 * @param identifier
 * @throws LockReleaseException
 */
public void releaseLock(String identifier) throws LockReleaseException {
    final DBObject identifierQuery = new QueryBuilder().and(LOCK_IDENTIFIER_KEY).is(identifier).get();
    final DBObject lockRecord = lockCollection.findAndRemove(identifierQuery);
    if (lockRecord == null) {
        throw new LockReleaseException(identifier);
    }
}

From source file:com.linuxbox.util.queueservice.mongodb.MongoQueueService.java

License:Open Source License

@Override
public QueueEntry dequeueByShardKey(int rangeLow, int rangeHigh) throws QueueServiceException {
    final QueryBuilder query = new QueryBuilder().and(STATUS_FIELD).is(STATUS_ENQUEUED).and(SHARD_KEY_FIELD)
            .greaterThanEquals(rangeLow).and(SHARD_KEY_FIELD).lessThan(rangeHigh);
    return dequeueHelper(query.get());
}

From source file:com.mlveda.dori.Webhook.java

public ArrayList<Collection> getCollectionList() {

    MongoDatabase db = MongoProvider.getInstance();

    //        MongoCollection<Product> products = db.getCollection("disneytoys.myshopify.com_products", Product.class);
    BasicDBObject document = new BasicDBObject();
    QueryBuilder qb = new QueryBuilder();
    qb.or(new QueryBuilder().put("handle").notEquals("frontpage").get(),
            new QueryBuilder().put("published_at").notEquals(null).get());
    document.putAll(qb.get());/*  w w w.  j a va 2s. com*/

    FindIterable<Document> coll = db.getCollection("dakshal.myshopify.com_collections")
            .find(and(ne("title", "Frontpage"), ne("published_at", null)));
    //        FindIterable<Document> coll = db.getCollection("disneytoys.myshopify.com_collection").find(document);

    //        FindIterable<Document> foundDocument = coll.find(and(ne("title", "Frontpage"), ne("published_at", null)));
    final Type collectionType = new TypeToken<ArrayList<Collection>>() {
    }.getType();

    final ArrayList<Collection> collection = new ArrayList<>();

    System.out.println();
    System.out.println();

    System.out.println("document: " + document);
    coll.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {

            collection.add(gson.fromJson(gson.toJson(document), Collection.class));

            //                System.out.println("document: " + document);
            //                ArrayList<Collection> c = gson.fromJson(gson.toJson(document.get("collections")), collectionType);
            //                System.out.println("collection: " + c);
            //                if (!c.isEmpty()) {
            //                    collection.addAll(c);
            //                }
            //                collection.add(t);
        }
    });
    System.out.println("Collection: " + gson.toJson(collection));
    System.out.println();
    System.out.println();

    return collection;
}

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 ava  2  s.co m*/
         * 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:fr.wseduc.pages.filters.PageReadFilter.java

License:Open Source License

@Override
public void authorize(HttpServerRequest request, Binding binding, UserInfos user, Handler<Boolean> handler) {
    String sharedMethod = binding.getServiceMethod().replaceAll("\\.", "-");
    String id = request.params().get(conf.getResourceIdLabel());
    if (id != null && !id.trim().isEmpty()) {
        List<DBObject> groups = new ArrayList<>();
        groups.add(QueryBuilder.start("userId").is(user.getUserId()).put(sharedMethod).is(true).get());
        for (String gpId : user.getGroupsIds()) {
            groups.add(QueryBuilder.start("groupId").is(gpId).put(sharedMethod).is(true).get());
        }/*from  ww  w. j  a  va2 s.co m*/
        QueryBuilder query = QueryBuilder.start("_id").is(id).or(
                QueryBuilder.start("owner.userId").is(user.getUserId()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());
        MongoAppFilter.executeCountQuery(request, conf.getCollection(), MongoQueryBuilder.build(query), 1,
                handler);
    } else {
        handler.handle(false);
    }
}

From source file:fr.wseduc.pages.filters.PagesFilter.java

License:Open Source License

public void pageRead(HttpServerRequest request, String sharedMethod, UserInfos user, Handler<Boolean> handler) {
    String id = request.params().get(resourceIdLabel);
    if (id != null && !id.trim().isEmpty()) {
        List<DBObject> groups = new ArrayList<>();
        groups.add(QueryBuilder.start("userId").is(user.getUserId()).put(sharedMethod).is(true).get());
        for (String gpId : user.getGroupsIds()) {
            groups.add(QueryBuilder.start("groupId").is(gpId).put(sharedMethod).is(true).get());
        }/* w w  w. jav  a 2 s  . c o  m*/
        QueryBuilder query = QueryBuilder.start("_id").is(id).or(
                QueryBuilder.start("owner.userId").is(user.getUserId()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());
        executeCountQuery(request, collection, MongoQueryBuilder.build(query), 1, handler);
    } else {
        handler.handle(false);
    }
}