Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

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

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

From source file:com.mobileman.kuravis.core.services.treatment_review.impl.TreatmentReviewServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}/*from   w  w  w. ja v  a2 s  .  c om*/
 * @see com.mobileman.kuravis.core.services.treatment_review.TreatmentReviewService#update(com.mongodb.DBObject, com.mongodb.DBObject)
 */
@SuppressWarnings("unchecked")
@Override
public DBObject update(DBObject treatmentReview, DBObject author) {
    if (treatmentReview == null || treatmentReview.get(EntityUtils.ID) == null || author == null) {
        throw ErrorUtils.exception("treatmentReview si nil", ErrorCodes.INCORRECT_PARAMETER);
    }

    String id = (String) treatmentReview.get(EntityUtils.ID);
    DBObject oldReview = findById(id);
    DBObject treatmentReviewOld = findById(id);
    if (treatmentReviewOld == null) {
        throw ErrorUtils.exception("Review does not exists with id: " + id, ErrorCodes.INTERNAL_ERROR);
    }

    if (!treatmentReview.containsField(TreatmentReview.DISEASE)) {
        throw ErrorUtils.exception("Disease is missing", ErrorCodes.INCORRECT_PARAMETER);
    }

    DBObject disease = diseaseService.createOrFindByName((Map<String, Object>) treatmentReview.get("disease"));
    treatmentReview.put(TreatmentReview.DISEASE, disease);

    if (!treatmentReview.containsField(TreatmentReview.TREATMENT)) {
        throw ErrorUtils.exception("Treatment is missing", ErrorCodes.INCORRECT_PARAMETER);
    }

    DBObject treatment = treatmentService
            .createOrFindByName((Map<String, Object>) treatmentReview.get(EntityUtils.TREATMENT));
    treatmentReview.put(TreatmentReview.TREATMENT, treatment);

    List<DBObject> trSideEffects = processSideEffectsOnCreateOrUpdate(treatmentReview);
    Number rating = processRatingOnCreateOrUpdate(treatmentReview);
    processUserOnCreateOrUpdate(treatmentReview, author);

    final DBObject setCommand = new BasicDBObject(TreatmentReview.DISEASE, disease)
            .append(TreatmentReview.SIDE_EFFECTS, treatmentReview.get(TreatmentReview.SIDE_EFFECTS))
            .append(TreatmentReview.TREATMENT, treatment).append(TreatmentReview.MODIFIED_ON, new Date())
            .append(TreatmentReview.TEXT, treatmentReview.get(TreatmentReview.TEXT))
            .append(TreatmentReview.DATE_OF_FIRST_SYMPTOMS,
                    treatmentReview.get(TreatmentReview.DATE_OF_FIRST_SYMPTOMS))
            .append(TreatmentReview.DATE_OF_DIAGNOSIS, treatmentReview.get(TreatmentReview.DATE_OF_DIAGNOSIS))
            .append(TreatmentReview.CURED, treatmentReview.get(TreatmentReview.CURED))
            .append(TreatmentReview.CURRENCY, treatmentReview.get(TreatmentReview.CURRENCY))
            .append(TreatmentReview.DOCTOR_COSTS, treatmentReview.get(TreatmentReview.DOCTOR_COSTS))
            .append(TreatmentReview.TREATMENT_PRICE, treatmentReview.get(TreatmentReview.TREATMENT_PRICE))
            .append(TreatmentReview.TREATMENT_QUANTITY, treatmentReview.get(TreatmentReview.TREATMENT_QUANTITY))
            .append(TreatmentReview.INSURANCE_COVERED, treatmentReview.get(TreatmentReview.INSURANCE_COVERED))
            .append(TreatmentReview.INSURANCE_COVERAGE, treatmentReview.get(TreatmentReview.INSURANCE_COVERAGE))
            .append(TreatmentReview.COINSURANCE, treatmentReview.get(TreatmentReview.COINSURANCE));

    final BasicDBObject command = new BasicDBObject();
    command.put("$set", setCommand);
    if (rating == null) {
        command.put("$unset", new BasicDBObject(TreatmentReview.RATING, ""));
    } else {
        setCommand.put(TreatmentReview.RATING, rating);
    }

    WriteResult result = getCollection().update(new BasicDBObject(EntityUtils.ID, id), command);
    if (ErrorUtils.isError(result)) {
        throw ErrorUtils.exception(result);
    }

    if (!EntityUtils.equals(treatmentReviewOld.get(EntityUtils.TREATMENT), treatment)
            || !EntityUtils.equals(treatmentReviewOld.get("disease"), disease)) {
        DBObject diseaseOld = (DBObject) treatmentReviewOld.get("disease");
        DBObject treatmentOld = (DBObject) treatmentReviewOld.get(EntityUtils.TREATMENT);
        processTreatmentReviewSummary(treatmentReview, null, CRUDAction.DELETE, author, diseaseOld,
                treatmentOld, null);
    }

    processTreatmentReviewSummary(treatmentReview, oldReview, CRUDAction.UPDATE, author, disease, treatment,
            trSideEffects);

    return ErrorUtils.success();
}

From source file:com.mobileman.kuravis.core.services.treatment_review.impl.TreatmentReviewServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}//  www.j  a va2s  . c o m
 * @see com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl#findById(java.lang.String, java.lang.String)
 */
@Override
public DBObject findById(String entityName, String id) {
    DBObject review = super.findById(entityName, id);
    if (review != null && review.containsField("author")) {
        DBObject author = (DBObject) review.get("author");
        DBObject data = userService.findUsersData(Arrays.<String>asList(EntityUtils.getEntityId(author)),
                User.SETTINGS, User.ATTR_GENDER, User.ATTR_YEAR_OF_BIRTH).get(EntityUtils.getEntityId(author));
        author.put("settings", data.get("settings"));
        author.put(User.ATTR_GENDER, data.get(User.ATTR_GENDER));
        author.put(User.ATTR_YEAR_OF_BIRTH, data.get(User.ATTR_YEAR_OF_BIRTH));
    }

    return review;
}

From source file:com.mobileman.kuravis.core.services.treatment_review.impl.TreatmentReviewServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}/*from  ww  w  . jav a2s.c  o m*/
 * @see com.mobileman.kuravis.core.services.treatment_review.TreatmentReviewService#updateTretmentReviewStatistics(com.mongodb.DBObject, com.mongodb.DBObject)
 */
@Override
public void updateTretmentReviewStatistics(DBObject newData, DBObject oldData) {
    // if gender differs
    String prevGender = UserUtils.getGender(oldData);
    String newGender = newData.containsField(User.ATTR_GENDER) ? (String) newData.get(User.ATTR_GENDER) : null;

    Number prevYearOfBirth = oldData.containsField(User.ATTR_YEAR_OF_BIRTH)
            ? (Number) oldData.get(User.ATTR_YEAR_OF_BIRTH)
            : null;
    Number newYearOfBirth = newData.containsField(User.ATTR_YEAR_OF_BIRTH)
            ? (Number) newData.get(User.ATTR_YEAR_OF_BIRTH)
            : null;

    if (newGender == null && newYearOfBirth == null) {
        return;
    }

    boolean genderChanged = newGender != null && !ObjectUtils.nullSafeEquals(prevGender, newGender);
    boolean yearOfBirthChanged = newYearOfBirth != null
            && !ObjectUtils.nullSafeEquals(prevYearOfBirth, newYearOfBirth);

    DBCursor curReviews = getCollection(ENTITY_NAME).find(
            new BasicDBObject("author._id", oldData.get(EntityUtils.ID)),
            new BasicDBObject("disease._id", 1).append("treatment._id", 1));
    Set<String> summariesId = new HashSet<String>();
    for (DBObject data : curReviews) {
        DBObject disease = (DBObject) data.get("disease");
        DBObject treatment = (DBObject) data.get(EntityUtils.TREATMENT);
        String summaryId = EntityUtils.createTreatmentReviewSummaryId(disease.get(EntityUtils.ID),
                treatment.get(EntityUtils.ID));
        summariesId.add(summaryId);
    }

    if (!summariesId.isEmpty() && genderChanged) {
        DBObject filter = QueryBuilder.start().put(EntityUtils.ID).in(summariesId).get();
        getCollection(TreatmentReviewSummary.ENTITY_NAME).update(filter,
                new BasicDBObject("$inc", new BasicDBObject("genderStatistics." + prevGender, -1)), false,
                true);
        getCollection(TreatmentReviewSummary.ENTITY_NAME).update(filter,
                new BasicDBObject("$inc", new BasicDBObject("genderStatistics." + newGender, 1)), true, true);

        for (Gender gender : Gender.values()) {
            filter = QueryBuilder.start().put("genderStatistics." + gender.getValue()).lessThan(0).get();
            getCollection(TreatmentReviewSummary.ENTITY_NAME).update(filter,
                    new BasicDBObject("$set", new BasicDBObject("genderStatistics." + gender.getValue(), 0)),
                    false, true);
        }

    }

    // if yearOfBirth differs
    if (yearOfBirthChanged || genderChanged) {
        // decrement old group if user has already entered YEAR_OF_BIRTH
        List<DBObject> oldStatfilters = new ArrayList<DBObject>();
        List<DBObject> newStatfilters = new ArrayList<DBObject>();
        if (yearOfBirthChanged && genderChanged) {

            for (String summaryId : summariesId) {

                if (prevYearOfBirth != null) {
                    DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                            .is(summaryId + prevYearOfBirth.intValue() + prevGender).put("summaryId")
                            .is(summaryId).put(User.ATTR_GENDER).is(prevGender).and(EntityUtils.NAME)
                            .is(prevYearOfBirth).get();
                    oldStatfilters.add(filter);
                }

                DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                        .is(summaryId + newYearOfBirth.intValue() + newGender).put("summaryId").is(summaryId)
                        .put(User.ATTR_GENDER).is(newGender).and(EntityUtils.NAME).is(newYearOfBirth).get();
                newStatfilters.add(filter);
            }

        } else if (yearOfBirthChanged) {

            for (String summaryId : summariesId) {
                if (prevYearOfBirth != null) {
                    DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                            .is(summaryId + prevYearOfBirth.intValue() + prevGender).put("summaryId")
                            .is(summaryId).put(User.ATTR_GENDER).is(prevGender).and(EntityUtils.NAME)
                            .is(prevYearOfBirth).get();
                    oldStatfilters.add(filter);
                }

                DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                        .is(summaryId + newYearOfBirth.intValue() + prevGender).put("summaryId").is(summaryId)
                        .put(User.ATTR_GENDER).is(prevGender).and(EntityUtils.NAME).is(newYearOfBirth).get();
                newStatfilters.add(filter);
            }
        } else if (genderChanged && prevYearOfBirth != null) { // genderChanged
            for (String summaryId : summariesId) {
                if (prevGender != null) {
                    DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                            .is(summaryId + prevYearOfBirth.intValue() + prevGender).put("summaryId")
                            .is(summaryId).put(User.ATTR_GENDER).is(prevGender).and(EntityUtils.NAME)
                            .is(prevYearOfBirth).get();
                    oldStatfilters.add(filter);
                }

                DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                        .is(summaryId + prevYearOfBirth.intValue() + newGender).put("summaryId").is(summaryId)
                        .put(User.ATTR_GENDER).is(newGender).and(EntityUtils.NAME).is(prevYearOfBirth).get();
                newStatfilters.add(filter);
            }
        }

        for (DBObject filter : oldStatfilters) {
            getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS).update(filter,
                    new BasicDBObject("$inc", new BasicDBObject("count", -1)), false, true);
        }

        for (DBObject filter : newStatfilters) {
            getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS).update(filter,
                    new BasicDBObject("$inc", new BasicDBObject("count", 1)), true, true);
        }

        // remove old zero stats
        getMongoTemplate().remove(Query.query(Criteria.where("count").lte(0)),
                EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS);
    }
}

From source file:com.mobileman.kuravis.core.services.treatment_review_summary.impl.TreatmentReviewSummaryServiceImpl.java

License:Apache License

@Override
public List<DBObject> findAllByQuery(DBObject query, Pageable page) {

    List<DBObject> result = new ArrayList<>();

    if (query.containsField("treatment." + EntityUtils.NAME)) {
        String name = (String) query.get("treatment." + EntityUtils.NAME);
        query.put("treatment." + EntityUtils.NAME,
                new BasicDBObject("$regex", "^" + name.toLowerCase() + "$").append("$options", "i"));
    }/*w  ww.  ja va  2s . c  o  m*/

    if (query.containsField("disease." + EntityUtils.NAME)) {
        String name = (String) query.get("disease." + EntityUtils.NAME);
        query.put("disease." + EntityUtils.NAME,
                new BasicDBObject("$regex", "^" + name.toLowerCase() + "$").append("$options", "i"));
    }

    DBCursor cursor = getCollection().find(query).sort(createSort(page)).skip(page.getOffset())
            .limit(page.getPageSize());

    while (cursor.hasNext()) {
        DBObject summary = cursor.next();
        String summaryId = (String) summary.get(EntityUtils.ID);
        DBObject ageStatistics = findAgeStatistics(summaryId);
        summary.put("ageStatistics", ageStatistics);

        List<DBObject> treatmentDurationStatistics = findTreatmentDurationStatistics(summary);
        summary.put(TreatmentReviewSummary.TREATMENT_DURATION_STATISTICS, treatmentDurationStatistics);

        List<DBObject> costsStatistics = findCostStatistics(summary);
        summary.put(TreatmentReviewSummary.COSTS_STATISTICS, costsStatistics);

        result.add(summary);
    }

    return result;
}

From source file:com.mobileman.kuravis.core.services.treatment_review_summary.impl.TreatmentReviewSummaryServiceImpl.java

License:Apache License

/**
 * @param summaryId//from   w  w w. j a va2  s. c om
 * @return DBObject
 */
@SuppressWarnings("unchecked")
private DBObject findAgeStatistics(String summaryId) {
    DBObject ageStatistics = new BasicDBObject();
    DBCursor ageStatCursor = getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS)
            .find(new BasicDBObject("summaryId", summaryId));
    for (DBObject ageStatistic : ageStatCursor) {
        String gender = (String) ageStatistic.get(User.ATTR_GENDER);
        if (gender == null) {
            gender = Gender.UNKNOWN.getValue();
        }

        final List<DBObject> genderAgeStats;
        if (!ageStatistics.containsField(gender)) {
            genderAgeStats = new ArrayList<DBObject>();
            ageStatistics.put(gender, genderAgeStats);
        } else {
            genderAgeStats = (List<DBObject>) ageStatistics.get(gender);
        }

        genderAgeStats.add(ageStatistic);
    }
    return ageStatistics;
}

From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java

License:Apache License

/**
 * @param newObject/*  www.  j a v a 2  s.c o  m*/
 * @param oldObject
 * @param command
 * @return true if property has to be changed
 */
private boolean addPropertyUpdate(String property, DBObject newObject, DBObject oldObject, DBObject command) {
    if (newObject.containsField(property)) {
        if (!ObjectUtils.nullSafeEquals(oldObject.get(property), newObject.get(property))) {
            if (newObject.get(property) == null) {
                command.put(property, "");
                return true;
            } else {
                command.put(property, newObject.get(property));
                return true;
            }
        }
    }

    return false;
}

From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}/* w w  w .j  av  a  2 s  .  c  o  m*/
 * @see com.mobileman.kuravis.core.services.user.UserService#findUsersByDiseaseAndTreatment(com.mongodb.DBObject, Pageable)
 */
@Override
public List<DBObject> findUsersByDiseaseAndTreatment(DBObject query, Pageable page) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();

    if (query != null) {
        if (query.containsField("diseaseId")) {
            builder.add("disease." + EntityUtils.ID, query.get("diseaseId"));
        }

        if (query.containsField("treatmentId")) {
            builder.add("treatment." + EntityUtils.ID, query.get("treatmentId"));
        }
    }

    AggregationOutput out = getCollection(TreatmentReview.ENTITY_NAME).aggregate(
            new BasicDBObject("$match", builder.get()),
            new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("_id", "$author._id"))),
            new BasicDBObject("$project", new BasicDBObject(EntityUtils.ID, "$_id._id")),
            new BasicDBObject("$skip", page.getOffset()), new BasicDBObject("$limit", page.getPageSize())

    );

    List<DBObject> result = new ArrayList<>();
    Set<String> userIds = new HashSet<String>();
    for (DBObject dbObject : out.results()) {
        String userId = EntityUtils.getEntityId(dbObject);
        userIds.add(userId);
        result.add(dbObject);
    }

    Map<String, DBObject> usersData = findUsersData(userIds, "name", "gender", "settings.profile");
    for (DBObject user : result) {
        DBObject data = usersData.get(EntityUtils.getEntityId(user));
        if (data != null) {
            user.put("name", data.get("name"));
            user.put("gender", data.get("gender"));
            user.put("settings", data.get("settings"));
        }
    }

    return result;
}

From source file:com.mobileman.moments.core.services.notification.impl.gcn.question.GCNQuestionNotifications.java

License:Apache License

@SuppressWarnings("unchecked")
@ServiceActivator(inputChannel = MomentsESBConstants.QUESTION_CREATED_CHANNEL)
public void questionCreated(final Question question) {

    final String location = "";
    final String alert = this.messageSource.getMessage("push_notification.new_question_in_interest.alert",
            new Object[] { location }, LocalizationUtils.DEFAULT_LOCALE);
    final String title = this.messageSource.getMessage("push_notification.new_question_in_interest.title",
            new Object[] { "name" }, null, LocalizationUtils.DEFAULT_LOCALE);
    final User loggedUser = SecurityUtils.getLoggedUser();

    mongoTemplate.execute(User.class, new CollectionCallback<Void>() {

        @Override/*w  w w.j  a  v  a2s .  c om*/
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            Query query = Query.query(Criteria.where("interests._id").is(new ObjectId("id")).and("_id")
                    .ne(new ObjectId(loggedUser.getId())));
            query.fields().include("_id");
            query.fields().include("interests");

            DBCursor cursor = collection.find(query.getQueryObject(), query.getFieldsObject());
            for (DBObject dbObject : cursor) {
                // UserSettings = settings = dbObject.get
                ObjectId userId = (ObjectId) dbObject.get("_id");

                List<DBObject> interests = (List<DBObject>) dbObject.get("interests");

                for (DBObject interest : interests) {
                    if (interest.get("_id").toString().equals("id")) {
                        if (interest.containsField("following_questions")
                                && Boolean.TRUE.equals(interest.get("following_questions"))) {
                            //notificationService.questionByInterestCreated(question, userId.toString(), alert, title);
                        }
                    }
                }

                // if (settings.getFollowesQuestionsNotification().isEnabled()) 
                // UserPushNotificationEvent event = new UserPushNotificationEvent(userId.toString(), title, alert);
                // momentsGateway.postPushNotificationEvent(event);

            }

            return null;
        }

    });
}

From source file:com.mongo.blog.dao.BlogPostDAO.java

License:Apache License

public DBObject findByPermalink(String permalink) {
    DBObject post = postsCollection.findOne(new BasicDBObject("permalink", permalink));

    // fix up if a post has no likes
    if (post != null) {
        List<DBObject> comments = (List<DBObject>) post.get("comments");
        for (DBObject comment : comments) {
            if (!comment.containsField("num_likes")) {
                comment.put("num_likes", 0);
            }//from w w  w . j  a v a2  s.co m
        }
    }
    return post;
}

From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java

License:Open Source License

public boolean removeTrigger(TriggerKey triggerKey) throws JobPersistenceException {
    BasicDBObject dbObject = Keys.keyToDBObject(triggerKey);
    List<DBObject> triggers = triggerCollection.find(dbObject).limit(2).toArray();
    if (triggers.size() > 0) {
        DBObject trigger = triggers.get(0);
        if (trigger.containsField(TRIGGER_JOB_ID)) {
            // There is only 1 job per trigger so no need to look further.
            DBObject job = jobCollection.findOne(new BasicDBObject("_id", trigger.get(TRIGGER_JOB_ID)));
            // Remove the orphaned job if it's durable and has no other triggers associated with it,
            // remove it
            if (job != null && (!job.containsField(JOB_DURABILITY)
                    || job.get(JOB_DURABILITY).toString().equals("false"))) {
                List<DBObject> referencedTriggers = triggerCollection
                        .find(new BasicDBObject(TRIGGER_JOB_ID, job.get("_id"))).limit(2).toArray();
                if (referencedTriggers.size() == 1) {
                    jobCollection.remove(job);
                }//from  w w w.j  av a  2s  .co  m
            }
        } else {
            log.debug("The trigger had no associated jobs");
        }
        triggerCollection.remove(dbObject);

        return true;
    }

    return false;
}