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:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

public Map<String, List<String>> getSchema(boolean reset) {
    MongoDatabase db = mongoClient.getDatabase(databaseName);

    Map<String, List<String>> result = new HashMap<>();

    MongoCursor<String> cursor = db.listCollectionNames().iterator();
    try {/*from w w w.j a v  a2  s  .c  o  m*/
        while (cursor.hasNext()) {
            String name = cursor.next();
            if (!name.startsWith("system."))
                if (reset)
                    db.getCollection(name).drop();
                else
                    result.put(name, new ArrayList<String>());
        }
    } finally {
        cursor.close();
    }

    for (Map.Entry<String, List<String>> e : result.entrySet()) {
        MongoCursor<Document> idxCursor = db.getCollection(e.getKey()).listIndexes().iterator();
        try {
            while (idxCursor.hasNext()) {
                Document idx = idxCursor.next();
                String indexName = idx.get("name", String.class);
                if (CompoundIndexDescriptor.isCompondIndexName(indexName))
                    e.getValue().add(indexName);
                else {
                    String name = idx.get("key", Document.class).keySet().iterator().next();
                    if (!name.startsWith("_"))
                        e.getValue().add(name);
                }
            }
        } finally {
            idxCursor.close();
        }
    }

    return result;
}

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> List<T> search(String unitName, Class<T> cls, Criteria criteria, List<String> orderBy,
        Integer limit) {//from  ww w.ja va  2 s  . c  o  m
    SerializationDefinition def = SerializationDefinition.get(cls);
    if (def == null)
        throw new RuntimeException("Cannot find SerializationDefinition for " + cls.getSimpleName());

    MongoDatabase db = mongoClient.getDatabase(databaseName);

    FindIterable<Document> query = criteria == null ? db.getCollection(unitName).find()
            : db.getCollection(unitName).find(criteria.convert(new FilterQueryBuilder()));

    if (orderBy != null && !orderBy.isEmpty())
        if (orderBy.size() == 1)
            query = query.sort(orderBy(orderBy.get(0)));
        else {
            List<Bson> ob = new ArrayList<>();
            for (String s : orderBy)
                ob.add(orderBy(s));
            query = query.sort(Sorts.orderBy(ob));
        }

    List<T> result = new ArrayList<>();
    MongoCursor<Document> cursor = query.limit(limit).iterator();
    try {
        while (cursor.hasNext()) {
            T item = (T) def.newInstance();
            def.read(cursor.next(), item);
            result.add(item);
        }
    } finally {
        cursor.close();
    }

    return result;
}

From source file:com.sag.tn.storm.stormmaven.bolts.DocumentTypeIdentifierBolt.java

License:Open Source License

public void execute(Tuple input) {
    VTDNav vn = (VTDNav) input.getValue(0); //vn object to be processed
    try {//ww  w.j  a v a 2 s . c  om
        String rootTag = Util.getRootTag(vn);

        //make a mongo query to get document type id from root tag name
        MongoCursor<Document> cursor = this.coll.find(eq("rootTag", rootTag)).iterator();
        while (cursor.hasNext()) {
            Document document = cursor.next();
            List<Tuple> list = new ArrayList<>();
            list.add(input);
            this.logger.info(
                    "EMITTING DOCTYPE ID - com.sag.tn.storm.stormmaven.bolts.DocumentTypeIdentifierBolt: {} ",
                    (String) document.get("docTypeId"));
            this.collector.emit(list, new Values((String) document.get("docTypeId")));
            this.logger.info(
                    "EMITTED DOCTYPE ID - com.sag.tn.storm.stormmaven.bolts.DocumentTypeIdentifierBolt: {} ",
                    (String) document.get("docTypeId"));
            break;
        }
        this.collector.ack(input);
    } catch (NavException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.shampan.model.LoginAttemptModel.java

/**
 * this method will return total number of login attempts of a user
 *
 * @param email *//from   w w  w  .jav a 2s .  c o m
 */
public ResultEvent getAttemptsNum(String email) {
    try {
        MongoCollection<LoginAttemptDAO> mongoCollection = DBConnection.getInstance().getConnection()
                .getCollection(Collections.LOGINATTEMPTS.toString(), LoginAttemptDAO.class);
        String attrEmail = PropertyProvider.get("EMAIL");
        int count = 0;
        Document selectDocument = new Document();
        selectDocument.put(attrEmail, email);
        Document groupDocument = new Document();
        groupDocument.put("", email);
        List<ArrayList> array = new ArrayList<>();
        //            mongoCollection.aggregate();
        MongoCursor<LoginAttemptDAO> loginattemptList = mongoCollection.find(selectDocument).iterator();
        while (loginattemptList.hasNext()) {
            count = count + 1;
            this.getResultEvent().setResult(count);
        }
        this.getResultEvent().setResponseCode(PropertyProvider.get("SUCCESSFUL_OPERATION"));
    } catch (Exception ex) {
        this.getResultEvent().setResponseCode(PropertyProvider.get("ERROR_EXCEPTION"));
    }
    return this.resultEvent;
}

From source file:com.shampan.model.PageModel.java

public List<String> getPageIdList(String userId) {
    MongoCollection<PageMemberDAO> mongoCollection = DBConnection.getInstance().getConnection()
            .getCollection(Collections.PAGEMEMBERS.toString(), PageMemberDAO.class);
    MongoCursor<PageMemberDAO> pageList = mongoCollection.find().iterator();
    List<String> pageIdList = new ArrayList<>();
    while (pageList.hasNext()) {
        PageMemberDAO pageInfo = pageList.next();
        if (pageInfo.getMemberList().size() > 0) {
            for (int i = 0; i < pageInfo.getMemberList().size(); i++) {

                if (pageInfo.getMemberList().get(i).getUserId().equals(userId)) {
                    pageIdList.add(pageInfo.getPageId());
                }/*from  w w  w  . ja  v  a 2 s  .com*/
            }
        }
    }
    return pageIdList;
}

From source file:com.shampan.model.PageModel.java

public List<JSONObject> getPhotoInfo(String userId, MongoCursor<PagePhotoDAO> photoList) {

    int commentLimit = Integer.parseInt(PropertyProvider.get("COMMENT_LIMIT"));
    List<JSONObject> photoInfoList = new ArrayList<JSONObject>();

    while (photoList.hasNext()) {
        JSONObject photoJson = new JSONObject();
        PagePhotoDAO photoInfo = (PagePhotoDAO) photoList.next();
        photoJson.put("photoId", photoInfo.getPhotoId());
        photoJson.put("pageId", photoInfo.getPageId());
        photoJson.put("referenceId", photoInfo.getReferenceId());
        photoJson.put("pageInfo", photoInfo.getPhotoId());
        photoJson.put("description", photoInfo.getDescription());
        photoJson.put("createdOn", photoInfo.getCreatedOn());
        photoJson.put("image", photoInfo.getImage());
        if (photoInfo.getLike() != null) {
            int likeSize = photoInfo.getLike().size();
            if (likeSize > 0) {
                photoJson.put("likeCounter", likeSize);
            }//from  www .  j  a v a2s.  c o  m
            int i = 0;
            while (likeSize > 0) {
                String tempUserId = photoInfo.getLike().get(i).getUserInfo().getUserId();
                if (tempUserId.equals(userId)) {
                    photoJson.put("likeStatus", PropertyProvider.get("YourLikeStatus"));
                }
                likeSize--;
                i++;
            }

        }
        if (photoInfo.getComment() != null) {
            List<JSONObject> commentList = new ArrayList<JSONObject>();
            int commentSize = photoInfo.getComment().size();
            if (commentSize > 0) {
                int commentLimitIn = 0;
                //                    List<Comment> commentList = new ArrayList();
                for (int j = commentSize; j > 0; j--) {
                    JSONObject commentJson = new JSONObject();
                    Comment comment = photoInfo.getComment().get(j - 1);
                    commentJson.put("commentId", comment.getCommentId());
                    commentJson.put("description", comment.getDescription());
                    commentJson.put("userInfo", comment.getUserInfo());
                    commentJson.put("createdOn", comment.getCreatedOn());
                    commentJson.put("userGenderId",
                            userModel.getUserGenderInfo(comment.getUserInfo().getUserId()));
                    if (comment.getLike() != null) {
                        int commentLikeSize = comment.getLike().size();
                        if (commentLikeSize > 0) {
                            commentJson.put("commentlikeCounter", commentLikeSize);
                        }
                        int k = 0;
                        while (commentLikeSize > 0) {
                            String tempUserId = comment.getLike().get(k).getUserInfo().getUserId();
                            if (tempUserId.equals(userId)) {
                                commentJson.put("CommentlikeStatus", PropertyProvider.get("YourLikeStatus"));
                            }
                            commentLikeSize--;
                            k++;
                        }
                    }
                    commentList.add(commentJson);
                    //                        commentList.add(comment);
                    commentLimitIn = commentLimitIn + 1;
                    if (commentLimitIn != commentLimit) {
                        continue;
                    } else {
                        break;
                    }
                }
                if (commentSize > commentLimit) {
                    photoJson.put("commentCounter", commentSize - commentLimit);
                }
                photoJson.put("commentList", commentList);
            }
        }
        if (photoInfo.getShare() != null) {
            int shareSize = photoInfo.getShare().size();
            if (shareSize > 0) {
                photoJson.put("shareCounter", shareSize);
            }
        }

        photoInfoList.add(photoJson);
    }
    return photoInfoList;
}

From source file:com.shampan.model.UserModel.java

public List<JSONObject> getRecentUser() {
    int offset = 0;
    int limit = 10;
    MongoCollection<UserDAO> mongoCollection = DBConnection.getInstance().getConnection()
            .getCollection(Collections.USERS.toString(), UserDAO.class);
    Document projectionDocument = new Document();
    projectionDocument.put("firstName", "$all");
    projectionDocument.put("lastName", "$all");
    projectionDocument.put("userId", "$all");
    projectionDocument.put("gender", "$all");
    projectionDocument.put("country", "$all");
    List<JSONObject> requestList = new ArrayList<JSONObject>();
    List<UserDAO> userInfoList = new ArrayList<>();
    MongoCursor<UserDAO> userList = mongoCollection.find().sort(new Document("modifiedOn", -1)).skip(offset)
            .limit(limit).projection(projectionDocument).iterator();
    List<String> userIds = new ArrayList<>();
    while (userList.hasNext()) {
        UserDAO user = userList.next();/* w w  w . j  a va 2s  .c  om*/
        userIds.add(user.getUserId());
        userInfoList.add(user);

    }

    List<BasicProfileDAO> userBasicInfoList = basicProfileModel.getRecentUserInfo(userIds.toString());
    if (userBasicInfoList != null) {
        int userSize = userBasicInfoList.size();
        int userListSize = userInfoList.size();
        for (int j = 0; j < userSize; j++) {
            for (int i = 0; i < userListSize; i++) {
                if (userInfoList.get(i).getUserId().equals(userBasicInfoList.get(j).getUserId())) {
                    //                        BirthDate birthDay = userBasicInfoList.get(j).getBasicInfo().getBirthDate();

                    JSONObject userJson = new JSONObject();
                    //                        int age = getAge(birthDay);
                    //                        userJson.put("age", age);
                    userJson.put("userId", userInfoList.get(i).getUserId());
                    userJson.put("firstName", userInfoList.get(i).getFirstName());
                    userJson.put("lastName", userInfoList.get(i).getLastName());
                    userJson.put("gender", userInfoList.get(i).getGender());
                    userJson.put("country", userInfoList.get(i).getCountry());
                    if (userBasicInfoList.get(j).getBasicInfo().getCity() != null) {
                        userJson.put("city", userBasicInfoList.get(j).getBasicInfo().getCity().getCityName());
                    }
                    if (userBasicInfoList.get(j).getpSkills() != null) {
                        int pSkillSize = userBasicInfoList.get(j).getpSkills().size();
                        userJson.put("pSkill",
                                userBasicInfoList.get(j).getpSkills().get(pSkillSize - 1).getpSkill());
                    }
                    requestList.add(userJson);
                }
            }
        }
    }

    return requestList;
}

From source file:com.sitewhere.device.persistence.mongodb.MongoDeviceManagement.java

License:Open Source License

@Override
public List<IDeviceGroupElement> removeDeviceGroupElements(List<UUID> elementIds) throws SiteWhereException {
    List<IDeviceGroupElement> deleted = new ArrayList<IDeviceGroupElement>();
    for (UUID elementId : elementIds) {
        Document match = new Document(MongoDeviceGroupElement.PROP_ID, elementId);
        FindIterable<Document> found = getMongoClient().getGroupElementsCollection().find(match);
        MongoCursor<Document> cursor = found.iterator();

        while (cursor.hasNext()) {
            Document current = cursor.next();
            DeleteResult result = MongoPersistence.delete(getMongoClient().getGroupElementsCollection(),
                    current);//from  www.  j a v a 2 s .c o  m
            if (result.getDeletedCount() > 0) {
                deleted.add(MongoDeviceGroupElement.fromDocument(current));
            }
        }
    }
    return deleted;
}

From source file:com.sitewhere.event.persistence.mongodb.MongoDeviceEventManagement.java

License:Open Source License

@Override
public ISearchResults<IDeviceEvent> listDeviceEvents(IDeviceAssignment assignment,
        IDateRangeSearchCriteria criteria) throws SiteWhereException {
    MongoCollection<Document> events = getMongoClient().getEventsCollection();
    Document query = new Document(MongoDeviceEvent.PROP_DEVICE_ASSIGNMENT_ID, assignment.getId());
    MongoPersistence.addDateSearchCriteria(query, MongoDeviceEvent.PROP_EVENT_DATE, criteria);
    Document sort = new Document(MongoDeviceEvent.PROP_EVENT_DATE, -1)
            .append(MongoDeviceEvent.PROP_RECEIVED_DATE, -1);

    int offset = Math.max(0, criteria.getPageNumber() - 1) * criteria.getPageSize();
    FindIterable<Document> found = events.find(query).skip(offset).limit(criteria.getPageSize()).sort(sort);
    MongoCursor<Document> cursor = found.iterator();

    List<IDeviceEvent> matches = new ArrayList<IDeviceEvent>();
    SearchResults<IDeviceEvent> results = new SearchResults<IDeviceEvent>(matches);
    try {//www  .j  a v  a2s  .c  om
        results.setNumResults(events.count(query));
        while (cursor.hasNext()) {
            Document match = cursor.next();
            matches.add(MongoDeviceEventManagementPersistence.unmarshalEvent(match));
        }
    } finally {
        cursor.close();
    }
    return results;
}

From source file:com.sitewhere.user.persistence.mongodb.MongoUserManagement.java

License:Open Source License

@Override
public List<IUser> listUsers(IUserSearchCriteria criteria) throws SiteWhereException {
    try {//from   www  .  j av a2 s.c o m
        MongoCollection<Document> users = getMongoClient().getUsersCollection();
        Document dbCriteria = new Document();
        if (!criteria.isIncludeDeleted()) {
            MongoSiteWhereEntity.setDeleted(dbCriteria, false);
        }
        FindIterable<Document> found = users.find(dbCriteria)
                .sort(new BasicDBObject(MongoUser.PROP_USERNAME, 1));
        MongoCursor<Document> cursor = found.iterator();

        List<IUser> matches = new ArrayList<IUser>();
        try {
            while (cursor.hasNext()) {
                Document match = cursor.next();
                matches.add(MongoUser.fromDocument(match));
            }
        } finally {
            cursor.close();
        }
        return matches;
    } catch (MongoTimeoutException e) {
        throw new SiteWhereException("Connection to MongoDB lost.", e);
    }
}