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:org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient.java

License:Apache License

private MongoResult aggregate(MongoQueryOptions mongoQueryOptions, MongoResult mongoResult,
        MongoCollection<Document> collection) {
    AggregateIterable<Document> aggregate = collection.aggregate(mongoQueryOptions.getOperations());
    aggregate.useCursor(true);//w w w . ja  va 2s  . c  o m

    int index = 0;
    MongoCursor<Document> iterator = aggregate.iterator();
    while (iterator.hasNext() && index < mongoQueryOptions.getResultLimit()) {
        mongoResult.add(iterator.next());
    }
    return mongoResult;
}

From source file:org.eclipse.leshan.server.demo.servlet.FetchServlet.java

License:Open Source License

/**
 * {@inheritDoc}//from  ww  w .  j  a  v  a  2  s .c  o m
 */

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Properties props = new Properties();
    props.put("zookeeper.connect", "localhost:2181");
    props.put("group.id", "testgroup");
    props.put("zookeeper.session.timeout.ms", "400");
    props.put("zookeeper.sync.time.ms", "300");
    props.put("auto.commit.interval.ms", "1000");
    ConsumerConfig conConfig = new ConsumerConfig(props);
    consumerConnector = Consumer.createJavaConsumerConnector(conConfig);
    resp.setContentType("application/json");
    MongoClient client = new MongoClient(mongoDBAdd, mongoDBPort);
    // MongoClient client = new MongoClient("54.161.178.113", 27017);
    MongoDatabase database = client.getDatabase(mongoDBName);
    MongoCollection<Document> collection = database.getCollection("events");
    Gson gson = new Gson();

    ArrayList<ClientDao> clientDaoList = new ArrayList<ClientDao>();
    if (req.getPathInfo() == null) {
        try {
            MongoCursor<String> mongoCursor = database.getCollection("events")
                    .distinct("client_ep", String.class).iterator();
            while (mongoCursor.hasNext()) {
                String clientEp = mongoCursor.next();
                ClientDao clientDao = new ClientDao();
                clientDao.setClientEP(clientEp);
                clientDao.setTimestamp(null);
                clientDaoList.add(clientDao);
            }

            String json = gson.toJson(clientDaoList);
            resp.getWriter().write(json.toString());
            resp.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    if (req.getPathInfo() != null) {
        String[] path = StringUtils.split(req.getPathInfo(), '/');
        if (path.length == 1) {
            try {

                BasicDBObject query1 = new BasicDBObject();
                BasicDBObject sort = new BasicDBObject();
                sort.put("timestamp", -1);

                query1.put("client_ep", path[0].toString());
                Iterable<Document> cur = collection.find(query1).sort(sort);
                Iterator<Document> itr = cur.iterator();
                while (itr.hasNext()) {

                    Document document = itr.next();
                    ClientDao clientDao = new ClientDao();
                    clientDao.setClientEP(document.getString("client_ep"));
                    clientDao.setEvent(document.getString("event"));
                    clientDao.setTimestamp(document.getString("timestamp"));
                    clientDaoList.add(clientDao);
                }

                //                    String json = gson.toJson(clientDaoList);
                //                    resp.getWriter().write(json.toString());
                //                    resp.setStatus(HttpServletResponse.SC_OK);

                Map<String, Integer> topicCount = new HashMap<String, Integer>();
                topicCount.put(topic, new Integer(1));

                //ConsumerConnector creates the message stream for each topic
                Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = consumerConnector
                        .createMessageStreams(topicCount);

                // Get Kafka stream for topic 'mytopic'
                List<KafkaStream<byte[], byte[]>> kStreamList = consumerStreams.get(topic);
                // Iterate stream using ConsumerIterator
                for (final KafkaStream<byte[], byte[]> kStreams : kStreamList) {
                    ConsumerIterator<byte[], byte[]> consumerIte = kStreams.iterator();
                    int count = 0;
                    while (consumerIte.hasNext()) {
                        count++;

                        // Shutdown the consumer connector
                        if (consumerConnector != null && count == 10)
                            consumerConnector.shutdown();
                        Message msg = new Message(consumerIte.next().message());
                        ByteBuffer buffer = msg.payload();
                        byte[] bytes = new byte[buffer.remaining()];
                        buffer.get(bytes);
                        String result = new String(bytes);
                        JSONObject jsonObj = new JSONObject(result);

                        ClientDao clientDao = new ClientDao();
                        clientDao.setClientEP(jsonObj.getString("client_ep"));
                        clientDao.setEvent(jsonObj.getString("event"));
                        clientDao.setTimestamp(jsonObj.getString("timestamp"));
                        clientDaoList.add(clientDao);

                    }
                }

                String json = gson.toJson(clientDaoList);
                resp.getWriter().write(json.toString());
                resp.setStatus(HttpServletResponse.SC_OK);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                client.close();
            }

        }

    }

}

From source file:org.et.ddi.HypernymyExtractor.Core.Extractor.java

public void getLemmaList() {
    MongoCursor<Document> cursor = mcwords.find().iterator();
    int counter = 0;
    while (cursor.hasNext()) {
        Document d = cursor.next();
        String name = (String) d.get("Name");
        String type = (String) d.get("Type");
        if (!type.equals("fiil") && !type.equals("-") && !name.contains(" ") && name.length() > 3) {
            lemmas.add(name.trim());/*ww  w  .  j ava  2s . co m*/
            System.out.println("Founded: " + (++counter));
        }
        //else{System.out.println(name+" "+type);}
    }

    try {
        for (String lemma : lemmas)
            bw.write(lemma + System.lineSeparator());
        bw.close();
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

From source file:org.flywaydb.core.internal.dbsupport.mongo.MongoDatabaseUtil.java

License:Apache License

/**
 * Checks whether a Mongo database exists.
 *
 * @param client a MongoClient for connecting to the database.
 * @param dbName the database name.// w  ww .ja  v a 2 s .c o m
 * @return {@code true} if a database with the given name exists, {@code false} if not.
 * @throws FlywayException when the check fails.
 */
public static boolean exists(MongoClient client, String dbName) throws FlywayException {
    try {
        MongoCursor<String> dbNameIterator = client.listDatabaseNames().iterator();
        while (dbNameIterator.hasNext()) {
            if (dbNameIterator.next().equals(dbName))
                return true;
        }
        return false;
    } catch (MongoException e) {
        throw new FlywayException("Unable to check whether Mongo database" + dbName + " exists", e);
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

@Override
public List<UserEntity> findUserAccounts() throws MetaStoreException {
    try {//from  ww w . ja v  a2  s .  com
        List<UserEntity> users = Lists.newArrayList();

        MongoCursor<Document> cursor = userAccountCollection.find().iterator();
        try {
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                UserEntity user = new UserEntity();
                user.setId(doc.getObjectId("_id").toString());
                user.setName(doc.getString("name"));
                user.setPassword(doc.get("password", Binary.class).getData());
                user.setCreateTime(doc.getDate("createTime"));
                user.setLastModifyTime(doc.getDate("lastModifyTime"));

                users.add(user);
            }
        } finally {
            cursor.close();
        }

        return users;
    } catch (MongoException e) {
        LOG.error("Failed to find user accounts", e);
        throw new MetaStoreException("Failed to find user accounts", e);
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<Schema> findSchemas(UserEntity owner) throws MetaStoreException {
    try {//from  ww w.j a  v a2s  .c  o m
        List<Schema> schemas = Lists.newArrayList();

        MongoCursor<Document> cursor = schemaCollection.find(eq("owner", owner.getId())).iterator();
        try {
            while (cursor.hasNext()) {
                Document doc = cursor.next();

                Schema schema = (Schema) Utils.deserialize(doc.get("desc", Binary.class).getData());
                schema.setId(doc.getObjectId("_id").toString());
                schema.setTopologies(doc.get("topologies", ArrayList.class));
                schema.setOwner(owner);
                schema.setCreateTime(doc.getDate("createTime"));
                schema.setComment(doc.getString("comment"));

                schemas.add(schema);
            }
        } finally {
            cursor.close();
        }

        return schemas;
    } catch (MongoException e) {
        LOG.error("Failed to find schemas", e);
        throw new MetaStoreException("Failed to find schemas", e);
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

@Override
public List<GungnirTopology> findTopologies(UserEntity owner) throws MetaStoreException {
    try {/*from  w  w  w  . jav  a2 s  .  co m*/
        List<GungnirTopology> topologies = Lists.newArrayList();

        MongoCursor<Document> cursor = topologyCollection.find(eq("owner", owner.getId())).iterator();
        try {
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                GungnirTopology topology = (GungnirTopology) Utils
                        .deserialize(doc.get("desc", Binary.class).getData());
                topology.setId(doc.getObjectId("_id").toString());
                topology.setName(doc.getString("name"));
                topology.setOwner(owner);
                topology.setStatus(TopologyStatus.valueOf(doc.getString("status")));
                topology.setCreateTime(doc.getDate("createTime"));
                topology.setComment(doc.getString("comment"));

                topologies.add(topology);
            }
        } finally {
            cursor.close();
        }

        return topologies;
    } catch (MongoException e) {
        LOG.error("Failed to find topologies", e);
        throw new MetaStoreException("Failed to find topologies", e);
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

@Override
public List<GungnirTopology> findTopologies(UserEntity owner, TopologyStatus status) throws MetaStoreException {
    try {/* w  w  w  .j  av a2 s  . co m*/
        List<GungnirTopology> topologies = Lists.newArrayList();

        MongoCursor<Document> cursor = topologyCollection
                .find(and(eq("owner", owner.getId()), eq("status", status.toString()))).iterator();
        try {
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                GungnirTopology topology = (GungnirTopology) Utils
                        .deserialize(doc.get("desc", Binary.class).getData());
                topology.setId(doc.getObjectId("_id").toString());
                topology.setName(doc.getString("name"));
                topology.setStatus(TopologyStatus.valueOf(doc.getString("status")));
                topology.setOwner(owner);
                topology.setCreateTime(doc.getDate("createTime"));
                topology.setComment(doc.getString("comment"));

                topologies.add(topology);
            }
        } finally {
            cursor.close();
        }

        return topologies;
    } catch (MongoException e) {
        LOG.error("Failed to find topologies", e);
        throw new MetaStoreException("Failed to find topologies", e);
    }
}

From source file:org.gennai.gungnir.topology.processor.MongoFetchProcessor.java

License:Apache License

private List<List<Object>> find(Document execQuery) {
    List<List<Object>> valuesList = Lists.newArrayList();
    FindIterable<Document> find = collection.find(execQuery).projection(fetchFields);
    if (sort != null) {
        find.sort(sort);//  w w w.j  a  va  2s . c  o m
    }
    if (limit != null) {
        find.limit(limit);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Fetch from '{}.{}' query {}", dbName, collectionName, execQuery);
    }

    MongoCursor<Document> cursor = find.iterator();
    try {
        while (cursor.hasNext()) {
            Document doc = cursor.next();

            List<Object> values = Lists.newArrayListWithCapacity(fetchFieldNames.length);
            for (String fieldName : fetchFieldNames) {
                values.add(toValue(doc.get(fieldName)));
            }
            valuesList.add(values);
        }
    } finally {
        cursor.close();
    }
    return valuesList;
}

From source file:org.helm.rest.MongoDB.java

public long SelectID(String table, String key, String value) {
    key = key.toLowerCase();//from  ww  w.j  av a  2s.  c o m

    MongoCollection coll = db.getCollection(table);
    BsonDocument where = BsonDocument
            .parse("{\"" + key + "\": {$regex: \"^" + value.replace("\"", "\\\"") + "$\", $options: \"i\"}}"); // case insensitive
    Document fields = new Document("_id", false);
    fields.append("id", true);
    MongoCursor cur = coll.find(where).limit(1).projection(fields).iterator();
    if (cur == null || !cur.hasNext())
        return 0;

    Document d = (Document) cur.next();
    return (long) d.get("id");
}