Example usage for com.mongodb BasicDBList BasicDBList

List of usage examples for com.mongodb BasicDBList BasicDBList

Introduction

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

Prototype

BasicDBList

Source Link

Usage

From source file:MDBInt.DBMongo.java

License:Apache License

public boolean testLink(String tenantName, String Cloud1, String Cloud2) {

    boolean attivo = false;
    BasicDBList or;/*from w ww  .j  a  va2s.  c  o m*/
    BasicDBObject query;
    DB database = this.getDB(tenantName);
    DBCollection collection = database.getCollection("link");
    DBObject result;
    try {
        or = new BasicDBList();
        or.add(new BasicDBObject("_id", Cloud1 + "_" + Cloud2));
        or.add(new BasicDBObject("_id", Cloud2 + "_" + Cloud1));
        query = new BasicDBObject("$or", or);
        result = collection.findOne(query);
        attivo = (boolean) result.get("status");
    } catch (Exception ex) {

        return false;

    }

    return attivo;

}

From source file:me.twister915.punishments.model.storage.mongodb.MongoStorage.java

License:Apache License

@Override
public void purge(Set<T> punishments) throws PunishException {
    BasicDBList objects = new BasicDBList();
    for (T punishment : punishments) {
        if (punishment.getDBId() == null)
            continue;
        objects.add(punishment.getDBId());
    }/*from  ww w . j  a  v  a2 s.  c o  m*/
    collection.remove(new BasicDBObject(ID_KEY, new BasicDBObject("$in", objects)));
}

From source file:mongofx.js.api.JsApiUtils.java

License:Open Source License

private static BasicDBList convertArray(Bindings from) {
    BasicDBList list = new BasicDBList();
    for (int i = 0; i < from.size(); i++) {
        list.add(from.get(String.valueOf(i)));
    }//from  w w  w . j ava 2  s  .c  o m
    return list;
}

From source file:mongoSample.MyMongoDemo.java

License:Apache License

public static void main(final String[] args) {
    String mongoServer = args[0];

    MongoClient mongoClient = new MongoClient(mongoServer);
    MongoDatabase database = mongoClient.getDatabase("NGDBDemo");
    MongoCollection<Document> collection = database.getCollection("test");

    collection.drop();//from   ww w  .  j a v a2  s .co m

    Document people = new Document(); // A document for a person
    people.put("Name", "Guy");
    people.put("Email", "guy@gmail.com");

    BasicDBList friendList = new BasicDBList(); // A list for the persons
    // friends

    BasicDBObject friendDoc = new BasicDBObject(); // A document for each
    // friend

    friendDoc.put("Name", "Jo");
    friendDoc.put("Email", "Jo@gmail.com");
    friendList.add(friendDoc);
    friendDoc.clear();
    friendDoc.put("Name", "John");
    friendDoc.put("Email", "john@gmail.com");
    friendList.add(friendDoc);
    people.put("Friends", friendDoc);

    collection.insertOne(people);

    System.out.println('1');
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    System.out.println('2');

    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }

    System.out.println('3');
    // now use a query to get 1 document out
    Document myDoc = collection.find(eq("Name", "Guy")).first();
    System.out.println(myDoc.toJson());

    database = mongoClient.getDatabase("sakila");
    collection = database.getCollection("films");
    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }
    mongoClient.close();
}

From source file:mvm.rya.indexing.mongodb.GeoMongoDBStorageStrategy.java

License:Apache License

public DBObject getQuery(StatementContraints contraints, Geometry geo, GeoQueryType queryType) {
    BasicDBObject query;/*w ww . j  av  a 2s .c o m*/
    if (queryType.equals(GeoQueryType.EQUALS)) {
        List<double[]> points = getCorrespondingPoints(geo);
        if (points.size() == 1) {
            List circle = new ArrayList();
            circle.add(points.get(0));
            circle.add(maxDistance);
            BasicDBObject polygon = new BasicDBObject("$centerSphere", circle);
            query = new BasicDBObject(GEO, new BasicDBObject(GeoQueryType.WITHIN.getKeyword(), polygon));
        } else {
            query = new BasicDBObject(GEO, points);
        }

    } else {
        query = new BasicDBObject(GEO, new BasicDBObject(queryType.getKeyword(),
                new BasicDBObject("$polygon", getCorrespondingPoints(geo))));
    }
    if (contraints.hasSubject()) {
        query.append(SUBJECT, contraints.getSubject().toString());
    }
    if (contraints.hasPredicates()) {
        Set<URI> predicates = contraints.getPredicates();
        if (predicates.size() > 1) {
            BasicDBList or = new BasicDBList();
            for (URI pred : predicates) {
                DBObject currentPred = new BasicDBObject(PREDICATE, pred.toString());
                or.add(currentPred);
            }
            query.append("$or", or);
        } else if (!predicates.isEmpty()) {
            query.append(PREDICATE, predicates.iterator().next().toString());
        }
    }
    if (contraints.hasContext()) {
        query.append(CONTEXT, contraints.getContext().toString());
    }

    return query;
}

From source file:mx.edu.cide.justiciacotidiana.v1.model.Propuesta.java

License:Open Source License

/**
 * Obtiene la lista de comentarios asociados a una propuesta.
 * @return Lista de comentarios./*from   w w  w .  j a v a  2 s  . co  m*/
 */
private BasicDBList getCommentsList() {
    BasicDBList commentsList = new BasicDBList();
    BasicDBObject query = new BasicDBObject(Comentario.FIELDS.PROPOSALID, this.id);

    DBCursor com_cur = Utils.mongo.findItems(MongoInterface.COLLECTIONS.COMENTARIOS, query);
    try {
        if (null != com_cur && com_cur.hasNext()) {
            while (com_cur.hasNext()) {
                BasicDBObject obj = (BasicDBObject) com_cur.next();
                commentsList.add(obj);
            }
        }
    } catch (MongoException ex) {
        System.out.println("Error al genera lista de comentarios asociada a propuesta");
    }
    return commentsList;
}

From source file:mx.edu.cide.justiciacotidiana.v1.model.Propuesta.java

License:Open Source License

/**
 * Obtiene la lista de votos asociados a una propuesta, de acuerdo a su valor.
 * @param value Valor del voto.//from w  w w  . ja va  2s . com
 * @return Lista de votos asociados a la propuesta con el valor especificado.
 */
private BasicDBList getVotes(String value) {
    BasicDBList votesList = new BasicDBList();
    BasicDBObject query = new BasicDBObject(Voto.FIELDS.PROPOSALID, this.id);

    if (null != value && value.length() > 0) {
        query.put(Voto.FIELDS.VALUE, value);
    }

    //Construir lista de votos
    DBCursor com_cur = Utils.mongo.findItems(MongoInterface.COLLECTIONS.VOTOS, query);
    try {
        if (null != com_cur && com_cur.hasNext()) {
            while (com_cur.hasNext()) {
                BasicDBObject obj = (BasicDBObject) com_cur.next();
                obj.remove(Voto.FIELDS.PROPOSALID);
                obj.remove(Voto.FIELDS.VALUE);
                obj.remove(Voto.FIELDS.CREATED);
                votesList.add(obj);
            }
        }
    } catch (MongoException ex) {
        System.out.println("Error al genera lista de votos asociada a propuesta");
    }
    return votesList;
}

From source file:mx.edu.cide.justiciacotidiana.v1.services.Propuestas.java

License:Open Source License

private BasicDBList getCommentsList(String proposalId) {
    BasicDBList commentsList = new BasicDBList();
    BasicDBObject query = new BasicDBObject(Comentario.FIELDS.PROPOSALID, proposalId);

    DBCursor com_cur = Utils.mongo.findItems(MongoInterface.COLLECTIONS.COMENTARIOS, query);
    try {//w ww  . jav  a 2 s  .  com
        if (null != com_cur && com_cur.hasNext()) {
            while (com_cur.hasNext()) {
                BasicDBObject obj = (BasicDBObject) com_cur.next();
                commentsList.add(obj);
            }
        }
    } catch (MongoException ex) {
        System.out.println("Error al genera lista de comentarios asociada a propuesta");
    }
    return commentsList;
}

From source file:mx.edu.cide.justiciacotidiana.v1.services.Propuestas.java

License:Open Source License

private BasicDBList getVotes(String proposalId, String value) {
    BasicDBList votesList = new BasicDBList();
    BasicDBObject query = new BasicDBObject(Voto.FIELDS.PROPOSALID, proposalId);

    if (null != value && value.length() > 0) {
        query.put(Voto.FIELDS.VALUE, value);
    }//from w  w  w  .  j a va  2s .c  o  m

    //Construir lista de votos
    DBCursor com_cur = Utils.mongo.findItems(MongoInterface.COLLECTIONS.VOTOS, query);
    try {
        if (null != com_cur && com_cur.hasNext()) {
            while (com_cur.hasNext()) {
                BasicDBObject obj = (BasicDBObject) com_cur.next();
                obj.remove(Voto.FIELDS.PROPOSALID);
                obj.remove(Voto.FIELDS.VALUE);
                obj.remove(Voto.FIELDS.CREATED);
                votesList.add(obj);
            }
        }
    } catch (MongoException ex) {
        System.out.println("Error al genera lista de votos asociada a propuesta");
    }
    return votesList;
}

From source file:net.atos.entng.statistics.services.StatisticsServiceMongoImpl.java

License:Open Source License

private void getStatistics(final List<String> schoolIds, final JsonObject params,
        final Handler<Either<String, JsonArray>> handler, boolean isExport) {
    if (schoolIds == null || schoolIds.isEmpty()) {
        throw new IllegalArgumentException("schoolIds is null or empty");
    }/*from  ww  w .j ava 2s  . c  om*/

    String indicator = params.getString(PARAM_INDICATOR);
    Long start = (Long) params.getNumber(PARAM_START_DATE);
    Long end = (Long) params.getNumber(PARAM_END_DATE);

    boolean isActivatedAccountsIndicator = STATS_FIELD_ACTIVATED_ACCOUNTS.equals(indicator);
    boolean isAccessIndicator = TRACE_TYPE_SVC_ACCESS.equals(indicator);
    String groupedBy = isAccessIndicator ? "module/structures/profil" : "structures/profil";
    final QueryBuilder criteriaQuery = QueryBuilder.start(STATS_FIELD_GROUPBY).is(groupedBy)
            .and(STATS_FIELD_DATE).greaterThanEquals(formatTimestamp(start)).lessThan(formatTimestamp(end))
            .and(indicator).exists(true);

    String module = params.getString(PARAM_MODULE);
    boolean moduleIsEmpty = module == null || module.trim().isEmpty();
    boolean isAccessAllModules = isAccessIndicator && moduleIsEmpty;
    if (isAccessIndicator && !moduleIsEmpty) {
        criteriaQuery.and(MODULE_ID).is(module);
    }

    if (schoolIds.size() > 1) {
        criteriaQuery.and(STRUCTURES_ID).in(schoolIds);
    } else {
        criteriaQuery.and(STRUCTURES_ID).is(schoolIds.get(0));

        // When getting data for only one module, a "find" is enough (no need to aggregate data)
        if (!isExport && !isAccessAllModules) {
            JsonObject projection = new JsonObject();
            projection.putNumber("_id", 0).putNumber(indicator, 1).putNumber(PROFILE_ID, 1)
                    .putNumber(STATS_FIELD_DATE, 1);
            if (isActivatedAccountsIndicator) {
                projection.putNumber(STATS_FIELD_ACCOUNTS, 1);
            }

            mongo.find(collection, MongoQueryBuilder.build(criteriaQuery), sortByDateProfile, projection,
                    MongoDbResult.validResultsHandler(handler));
            return;
        }
    }

    // Aggregate data
    final JsonObject aggregation = new JsonObject();
    JsonArray pipeline = new JsonArray();
    aggregation.putString("aggregate", collection).putBoolean("allowDiskUse", true).putArray("pipeline",
            pipeline);

    pipeline.addObject(new JsonObject().putObject("$match", MongoQueryBuilder.build(criteriaQuery)));

    JsonObject id = new JsonObject().putString(PROFILE_ID, "$" + PROFILE_ID);
    if (isAccessAllModules && !isExport) {
        // Case : get JSON data for indicator "access to all modules"
        id.putString(MODULE_ID, "$" + MODULE_ID);
    } else {
        id.putString(STATS_FIELD_DATE, "$" + STATS_FIELD_DATE);
    }

    JsonObject group = new JsonObject().putObject("_id", id).putObject(indicator,
            new JsonObject().putString("$sum", "$" + indicator));
    if (isActivatedAccountsIndicator) {
        group.putObject(STATS_FIELD_ACCOUNTS, new JsonObject().putString("$sum", "$" + STATS_FIELD_ACCOUNTS));
    }
    JsonObject groupBy = new JsonObject().putObject("$group", group);

    pipeline.addObject(groupBy);

    QueryBuilder projection = QueryBuilder.start("_id").is(0).and(PROFILE_ID).is("$_id." + PROFILE_ID);
    if (isActivatedAccountsIndicator) {
        projection.and(STATS_FIELD_ACCOUNTS).is(1);
    }

    if (!isExport) {
        projection.and(indicator).is(1);
        if (isAccessAllModules) {
            projection.and(MODULE_ID).is("$_id." + MODULE_ID);
        } else {
            projection.and(STATS_FIELD_DATE).is("$_id." + STATS_FIELD_DATE);
        }

        // Sum stats for all structure_ids
        pipeline.addObject(new JsonObject().putObject("$project", MongoQueryBuilder.build(projection)));
    } else {
        // Projection : keep 'yyyy-MM' from 'yyyy-MM-dd HH:mm.ss.SSS'
        DBObject dateSubstring = new BasicDBObject();
        BasicDBList dbl = new BasicDBList();
        dbl.add("$_id." + STATS_FIELD_DATE);
        dbl.add(0);
        dbl.add(7);
        dateSubstring.put("$substr", dbl);

        projection.and(STATS_FIELD_DATE).is(dateSubstring).and("indicatorValue").is("$" + indicator); // Replace indicatorName by label "indicatorValue", so that the mustache template can be generic

        JsonObject sort = sortByStructureDateProfile;

        // Export stats for each structure_id
        id.putString(STRUCTURES_ID, "$" + STRUCTURES_ID);
        projection.and(STRUCTURES_ID).is("$_id." + STRUCTURES_ID);

        if (isAccessIndicator) {
            if (isAccessAllModules) {
                sort = sort.copy().putNumber(MODULE_ID, 1);
            }

            // Export stats for each module_id
            id.putString(MODULE_ID, "$" + MODULE_ID);
            projection.and(MODULE_ID).is("$_id." + MODULE_ID);
        }

        pipeline.addObject(new JsonObject().putObject("$project", MongoQueryBuilder.build(projection)));
        pipeline.addObject(new JsonObject().putObject("$sort", sort));
    }

    mongo.command(aggregation.toString(), new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            if ("ok".equals(message.body().getString("status"))
                    && message.body().getObject("result", new JsonObject()).getInteger("ok") == 1) {
                JsonArray result = message.body().getObject("result").getArray("result");
                handler.handle(new Either.Right<String, JsonArray>(result));
            } else {
                String error = message.body().toString();
                handler.handle(new Either.Left<String, JsonArray>(error));
            }
        }
    });
}