Example usage for com.mongodb.client MongoCursor next

List of usage examples for com.mongodb.client MongoCursor next

Introduction

In this page you can find the example usage for com.mongodb.client MongoCursor next.

Prototype

@Override
    TResult next();

Source Link

Usage

From source file:edu.ucuenca.storage.services.MongoServiceImpl.java

License:Apache License

@Override
public List<Document> getCountries() {
    List<Document> c = new ArrayList<>();
    FindIterable<Document> cls = countries.find();
    MongoCursor<Document> it = cls.iterator();
    while (it.hasNext()) {
        c.add(it.next());
    }/*from  w  w  w. ja v a  2s  .co m*/
    return c;
}

From source file:edu.ucuenca.storage.services.MongoServiceImpl.java

License:Apache License

@Override
public List<Document> getClustersTotals() {
    List<Document> c = new ArrayList<>();
    MongoCursor<Document> it = clustersTotals.find().iterator();
    while (it.hasNext()) {
        c.add(it.next());
    }/*from ww  w.jav a  2s. c o m*/
    return c;
}

From source file:edu.ucuenca.storage.services.MongoServiceImpl.java

License:Apache License

@Override
public String getSPARQL(String qry) {
    String k = getMd5(qry);// w w w  . ja va 2  s .c om
    String R = "";
    MongoCursor<Document> find = sparqls.find(eq("_id", k)).iterator();
    if (!find.hasNext()) {
        try {
            RepositoryConnection conn = sesameService2.getConnection();
            StringWriter writter = new StringWriter();
            RDFWriter jsonldWritter = Rio.createWriter(RDFFormat.JSONLD, writter);
            conn.prepareGraphQuery(QueryLanguage.SPARQL, qry).evaluate(jsonldWritter);
            //Object compact = JsonLdProcessor.compact(JsonUtils.fromString(writter.toString()), new HashMap(), new JsonLdOptions());
            Map<String, Object> json = new HashMap<String, Object>();
            json.put("_id", k);
            json.put("data", writter.toString());
            sparqls.insertOne(new Document(json));
            conn.close();
            writter.getBuffer().setLength(0);
            find = sparqls.find(eq("_id", k)).iterator();
        } catch (Exception ex) {
            ex.printStackTrace();
            log.debug("Unexpected error cached-query {}", ex);
        }
    }
    Document next = find.next();
    R = next.getString("data");
    return R;
}

From source file:eu.vre4eic.evre.telegram.commands.RegisterAuthCommand.java

License:Apache License

@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

    String userName = user.getFirstName() + " " + user.getLastName();
    StringBuilder messageBuilder = new StringBuilder();
    if (arguments.length != 2) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("please use: /register username pwd");
    } else {/*from w ww.j a  v a2 s.c  o m*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("evre");
        MongoCollection<Document> collection = db.getCollection("eVREUserProfile");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userId", arguments[0]);
        FindIterable<Document> itcursor = collection.find(searchQuery);
        //FindIterable<Document> itcursor=collection.find();
        MongoCursor<Document> cursor = itcursor.iterator();
        if (cursor.hasNext()) {

            Document userCan = cursor.next();
            String pwd = userCan.getString("password");

            Binary binS = userCan.get("salt", org.bson.types.Binary.class);
            String salt = new String(binS.getData());
            boolean validUser = false;
            if (pwd.equals(arguments[1]))
                validUser = true;

            if (salt != null && !checkEncryptedData(arguments[1], salt.getBytes()).equals(arguments[1]))
                validUser = true;

            //if(pwd.equals(arguments[1])){
            if (validUser) {

                userCan.replace("authId", chat.getId());
                BasicDBObject updateObj = new BasicDBObject();
                updateObj.put("$set", userCan);
                //check this!!!
                collection.updateOne(searchQuery, updateObj);

                messageBuilder.append("Done ").append(userName).append(",\n");
                messageBuilder.append(
                        "this Telegram account is now registered as e-VRE Authenticator for " + arguments[0]);

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append("\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }

}

From source file:eu.vre4eic.evre.telegram.commands.RemoveAuthCommand.java

License:Apache License

@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

    String userName = user.getFirstName() + " " + user.getLastName();
    StringBuilder messageBuilder = new StringBuilder();
    if (arguments.length != 2) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("please use: /remove username pwd");
    } else {//from w  ww  . j a v  a2s .  c o  m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("evre");
        MongoCollection<Document> collection = db.getCollection("eVREUserProfile");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userId", arguments[0]);
        FindIterable<Document> itcursor = collection.find(searchQuery);
        //FindIterable<Document> itcursor=collection.find();
        MongoCursor<Document> cursor = itcursor.iterator();
        if (cursor.hasNext()) {
            //System.out.println("################## "+cursor.next());
            Document userCan = cursor.next();
            String pwd = userCan.getString("password");
            if (pwd.equals(arguments[1])) {

                String aId = userCan.getString("authId");
                if (!aId.equals("0")) {
                    // we don't check if the chat.getId() is the same,
                    //because a user can remove this from another Telegram ID,
                    // need to check this

                    userCan.replace("authId", "0");
                    BasicDBObject updateObj = new BasicDBObject();
                    updateObj.put("$set", userCan);
                    //check this!!!
                    collection.updateOne(searchQuery, updateObj);

                    messageBuilder.append("Done ").append(userName).append(", \n");
                    messageBuilder.append(
                            "this Telegram account is no longer an e-VRE Authenticator for " + arguments[0]);
                } else {//the user with the provided credentials has no authenticator defined
                    messageBuilder.append("Hi ").append(userName).append(",\n");
                    messageBuilder.append("something went wrong, please contact the administrator!");
                }

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append(",\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }
}

From source file:examples.tour.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 */// w ww. ja  v a 2  s.  c  o m
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
            new Document("x", 203).append("y", 102));

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

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

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    Block<Document> printBlock = new Block<Document>() {

        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);

    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());

    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());

    // Aggregation
    collection
            .aggregate(
                    asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}"))))
            .forEach(printBlock);

    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), set("i", 110));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("i", 110));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    //collection.find().forEach(printBlock);

    // Clean up
    database.drop();

    // release resources
    mongoClient.close();
}

From source file:flipkart.mongo.replicator.node.ReplicationTask.java

License:Apache License

private void executeCursor(MongoCursor<Document> cursor) {

    while (cursor.hasNext()) {
        Document obj = cursor.next();
        ReplicationEvent event = taskContext.versionHandler.getReplicationEventAdaptor().convert(obj);
        replicateEvent(event);/*w w w  .  ja v a 2  s .c  o m*/

        if (lastCp == null || (event.v.getTime() - lastCp.getTime() >= taskContext.checkPointHandler
                .getCycleTimeinSecs())) {

            taskContext.checkPointHandler.checkPoint(rsConfig.shardName, event.v);
            lastCp = event.v;
        }
    }
}

From source file:foam.dao.MongoDAO.java

License:Open Source License

@Override
public Sink select_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) {
    sink = prepareSink(sink);/*w  w w  . ja  va2s . c om*/

    Sink decorated = decorateSink_(sink, skip, limit, order, predicate);
    Subscription sub = new Subscription();
    Logger logger = (Logger) x.get("logger");

    if (getOf() == null) {
        throw new IllegalArgumentException("`of` is not set");
    }

    MongoCollection<BsonDocument> collection = database.getCollection(collectionName, BsonDocument.class);
    MongoCursor<BsonDocument> cursor = collection.find().iterator();

    try {
        while (cursor.hasNext()) {
            if (sub.getDetached())
                break;

            FObject obj = createFObject(x, new BsonDocumentReader(cursor.next()), getOf().getObjClass(),
                    logger);

            if ((predicate == null) || predicate.f(obj)) {
                decorated.put(obj, sub);
            }
        }
    } finally {
        cursor.close();
    }

    decorated.eof();

    return sink;
}

From source file:fr.lirmm.graphik.graal.keyval.KeyValueStoreMongoDB.java

License:Open Source License

public void showCollection(MongoCollection<Document> col) {
    System.out.println(col.getNamespace().getCollectionName() + " : ");
    MongoCursor<Document> cursor = col.find().iterator();
    try {//from w ww.j  av a  2  s.c o  m
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
}

From source file:fr.lirmm.graphik.graal.keyval.KeyValueStoreMongoDB.java

License:Open Source License

public boolean contains(PathAtom pathAtom) throws AtomSetException {
    // On initialise nos variable
    Boolean result = false;//from  w  w  w.  ja  v  a2  s .c o  m
    ListCollectionsIterable<Document> listColl = db.listCollections();
    MongoCursor<Document> itrCol = listColl.iterator();

    // On itre sur les collection de la DB
    while (itrCol.hasNext() && !result) {

        // On test si la pathAtome possde un homomorphisme dans la
        // collection
        if (containsInCollection(pathAtom, itrCol.next().getString("name"))) {
            result = true;
        }
    }
    return result;
}