Example usage for com.mongodb.client MongoCursor hasNext

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

Introduction

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

Prototype

@Override
    boolean hasNext();

Source Link

Usage

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

License:Apache License

@Override
public String getSPARQL(String qry) {
    String k = getMd5(qry);/*from w w  w.j  av a2  s .  c o m*/
    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:es.omarall.mtc.TailingTask.java

License:Apache License

/**
 * TAILING TASK:/* w ww.  j a v  a2 s .  c om*/
 * 
 * 1. Builds a cursor 2. Fetch documents from that cursor till cursor closed
 * o documentHandler changes its state
 * 
 * 
 */
@Override
public void run() {

    try {

        // Check start was called
        if (!getStatus().equals(ServiceStatus.STARTED))
            throw new MTCExecutionException(
                    "Trying to RUN a non started task. Please call start() method before running the tailing task. ");

        while (true) {

            // Work with cursor until lost or
            // documentHandler changes its state to not started.

            // hasNext throws IllegalStateException when cursor is closed
            // (not by documentHandler)
            MongoCursor<Document> cursor = buildCursor();
            // "Await" for data
            if (cursor != null) {
                if (cursor.hasNext()) {

                    // throws ChangedStateToNotStarted
                    iterateCursor(cursor);

                    // Cursor was LOST

                    // wait to regenerate another cursor if configured so
                    applyDelayToGenerateCursor();
                } else {

                    // hasNext returned with no data
                    LOG.debug("Cursor returned no data");
                    cursor.close();
                }
            }
        } // while(keepRunning) block

    } catch (IllegalStateException e) {

        // hasNext() throws IllegalStateException when cursor is close by
        // other thread.
        LOG.info("+ MONGOESB: Cursor was closed");

        // STOP or Suspend

    } catch (NotStartedException e) {
        // Consumer changed its state
        LOG.info("+ MONGOESB: Consumer changed its state");
    } finally {
        LOG.info("+ MONGOESB - STOP TAILING TASK");
    }

}

From source file:es.omarall.mtc.TailingTask.java

License:Apache License

/**
 * Cursor LOGIC. A built cursor can be iterated until lost or until the
 * state is changed to a no started state.
 * //  w w w.j a  v a 2s. c  o  m
 * @throws NotStartedException
 *             to signal state changed to a non started state
 */
private void iterateCursor(final MongoCursor<Document> cursor) {

    if (cursor == null)
        return;

    // stores the id of the last document fetched by THIS cursor...
    ObjectId lastProcessedId = null;

    try {

        while (true) {

            // Is there a new document to be processed?
            Document next = cursor.tryNext();

            if (next == null) {

                // No doc to be processed ...
                // It is likely we come from a burst of processing ...
                // This is a chance to persist last processed
                // id...go for it

                if (tracker != null && lastProcessedId != null) {

                    tracker.persistLastTrackedEventId(lastProcessedId);
                    lastTrackedId = lastProcessedId;
                }

                // Wait for a new document to be processed
                if (!cursor.hasNext()) {
                    LOG.debug("INNER has NEXT returned no data");
                    if (cursor != null)
                        cursor.close();
                }

            } else {

                // There is a document to be processed
                try {

                    documentHandler.handleDocument(next);
                    lastProcessedId = next.getObjectId("_id");
                } catch (Exception e) {
                    LOG.error("DocumentHandler raised an exception", e);
                    // Notifiy but keep going
                }
            }

            // Check whether to keep execution
            if (getStatus().equals(ServiceStatus.STOPPED))
                throw new NotStartedException("Cursor Changed its state to not started");
        } // while

    } catch (MongoSocketException e) {
        // The cursor was closed
        LOG.error("\n\nMONGOESB - NETWORK problems: Server Address: {}", e.getServerAddress().toString(), e);

        // Not recoverable. Do not regenerate the cursor
        throw new MTCException(String.format("Network Problemns detected. Server address: %s",
                e.getServerAddress().toString()));
    } catch (MongoQueryException e) {
        // MongoCursorNotFoundException
        // The cursor was closed
        // Recoverable: Do regenerate the cursor
        LOG.info("Cursor {} has been closed.", e);
    } catch (IllegalStateException e) {
        // .hasNext(): Cursor was closed by other THREAD (documentHandler
        // cleaningup)?)
        // Recoverable. Do regenerate the cursor.
        LOG.info("Cursor being iterated was closed", e);
    } catch (NotStartedException e) {
        // Not recoverable: Do not regenerate the cursor.
        throw e;
    } finally {

        // persist tracking state
        if (tracker != null && lastProcessedId != null) {
            tracker.persistLastTrackedEventId(lastProcessedId);
            lastTrackedId = lastProcessedId;
        }

        // Cleanup resources.
        if (cursor != null)
            cursor.close();
    }
}

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 va2  s  .c  om
        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 w w  .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()) {
            //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
 *///from w  w w. j  a  v a 2  s  .  co 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);/*from  w  w  w .j a  va2 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.j  ava2 s  . co  m

    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 {/*  ww w . j ava  2  s.c om*/
        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;//  w w w . java 2s  . c om
    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;
}