Example usage for com.mongodb QueryBuilder start

List of usage examples for com.mongodb QueryBuilder start

Introduction

In this page you can find the example usage for com.mongodb QueryBuilder start.

Prototype

public static QueryBuilder start() 

Source Link

Document

Returns a new QueryBuilder.

Usage

From source file:com.mobileman.kuravis.core.services.event.impl.EventServiceImpl.java

License:Apache License

@Override
public String save(Event event) {
    boolean actualReminder = false;
    TreatmentEvent actualEvent = null;/*  ww  w.jav a 2  s.c  om*/
    if (event instanceof TreatmentEvent) {
        DBObject reminder = getCollection().findOne(
                QueryBuilder.start().put(TreatmentEvent.ID).is(event.get_id()).get(),
                new BasicDBObject(TreatmentEvent.REMINDER, 1));
        actualReminder = EntityUtils.getBoolean(TreatmentEvent.REMINDER, reminder);
        actualEvent = getEventById(event.get_id(), TreatmentEvent.class);
    }
    String id = super.save(event);
    if (event instanceof TreatmentEvent) {
        TreatmentEvent te = (TreatmentEvent) event;
        if (te.isReminder() && actualReminder != te.isReminder()) {
            reminderService.createReminderForEvent(te);
        } else {
            reminderService.deleteAllRemindersOfEvent(event.get_id());
        }
        this.treatmentReviewSummaryService.updateTreatmentDurationStatistics(te, actualEvent,
                CRUDAction.UPDATE);
    }
    return id;
}

From source file:com.mobileman.kuravis.core.services.event.impl.EventServiceImpl.java

License:Apache License

/**
 * {@inheritDoc}// w  w  w  .  ja v  a2 s  .  c o m
 * 
 * @see com.mobileman.kuravis.core.services.event.EventService#findAllTreatmentEvents(java.lang.String, java.lang.String, java.lang.String, org.springframework.data.domain.Pageable)
 */
@Override
public List<DBObject> findAllTreatmentEvents(String userId, String diseaseId, String treatmentId,
        Pageable page) {
    QueryBuilder query = QueryBuilder.start().put(Event.EVENT_TYPE).is(EventType.TREATMENT.name());
    if (!StringUtils.isBlank(userId)) {
        query = query.and(Event.USER + "." + Event.ID).is(userId);
    }

    if (!StringUtils.isBlank(diseaseId)) {
        query = query.and(TreatmentEvent.DISEASE + "." + TreatmentEvent.ID).is(diseaseId);
    }

    if (!StringUtils.isBlank(treatmentId)) {
        query = query.and(TreatmentEvent.TREATMENT + "." + TreatmentEvent.ID).is(treatmentId);
    }

    List<DBObject> result = findAllByQuery(query.get(), page);
    return result;
}

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

License:Apache License

/** 
 * {@inheritDoc}/*  w ww.ja  v a  2s.  co m*/
 * @see com.mobileman.kuravis.core.services.treatment_review.TempTreatmentReviewService#deleteAllTempTreatmentReviewsOfUser(java.lang.String, java.lang.String)
 */
@Override
public void deleteAllTempTreatmentReviewsOfUser(String userId, String email) {
    if (userId == null) {
        userId = "";
    }

    if (email == null) {
        email = "";
    }

    QueryBuilder query = QueryBuilder.start().or(new BasicDBObject("subscription.email", email),
            new BasicDBObject("author." + EntityUtils.ID, userId));
    getCollection(EntityUtils.TEMP_TREATMENT_REVIEW).remove(query.get());
}

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

License:Apache License

/**
 * @param review/*w  w w.j a v  a 2 s.c o  m*/
 * @param user
 * @param disease
 * @param treatment
 * @param trSideEffects
 */
private void processTreatmentReviewSummary(DBObject review, DBObject oldReview, CRUDAction action,
        DBObject user, DBObject disease, DBObject treatment, List<DBObject> trSideEffects) {

    final String trsid = EntityUtils.createTreatmentReviewSummaryId(disease.get(EntityUtils.ID),
            treatment.get(EntityUtils.ID));
    lockManager.lock(TreatmentReviewSummary.ENTITY_NAME, trsid);

    try {

        DBObject summary = findById(TreatmentReviewSummary.ENTITY_NAME, trsid);
        if (summary == null && !action.equals(CRUDAction.DELETE)) {
            String gender = UserUtils.getGender(user);
            summary = new BasicDBObject();
            summary.put(EntityUtils.ID, trsid);
            summary.put(EntityUtils.CREATED_ON, new Date());
            summary.put(EntityUtils.MODIFIED_ON, summary.get(EntityUtils.CREATED_ON));
            summary.put(TreatmentReviewSummary.DISEASE, disease);
            summary.put(TreatmentReviewSummary.TREATMENT, treatment);
            summary.put(TreatmentReviewSummary.REVIEWS_COUNT, 1);

            if (review.get(TreatmentReview.RATING) != null) {
                summary.put(TreatmentReviewSummary.RATINGS,
                        Arrays.asList(new BasicDBObject(EntityUtils.NAME, review.get(TreatmentReview.RATING))
                                .append("count", 1)));
                summary.put(TreatmentReviewSummary.RATING, review.get(TreatmentReview.RATING));
            }

            summary.put(TreatmentReviewSummary.SIDE_EFFECTS,
                    createTreatmentReviewSummarySideEffects(trSideEffects, new HashMap<String, DBObject>())
                            .values());
            summary.put(TreatmentReviewSummary.GENDER_STATISTICS, new BasicDBObject(gender, 1));

            try {
                WriteResult wresult = getCollection(TreatmentReviewSummary.ENTITY_NAME).insert(summary);
                if (!StringUtils.isEmpty(wresult.getError())) {
                    throw ErrorUtils.exception(wresult);
                }

                // handle YEAR_OF_BIRTH statistics
                if (user.get(User.ATTR_YEAR_OF_BIRTH) != null) {

                    DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                            .is(trsid + user.get(User.ATTR_YEAR_OF_BIRTH) + gender).put("summaryId").is(trsid)
                            .and(User.ATTR_GENDER).is(gender).and(EntityUtils.NAME)
                            .is(user.get(User.ATTR_YEAR_OF_BIRTH)).get();
                    wresult = getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS).update(filter,
                            new BasicDBObject("$inc", new BasicDBObject("count", 1)), true, true);
                    if (!StringUtils.isEmpty(wresult.getError())) {
                        throw ErrorUtils.exception(wresult);
                    }
                }

            } catch (DuplicateKey e) {
                summary = findById(TreatmentReviewSummary.ENTITY_NAME, trsid);
                updateTreatmentReviewSummary(summary, user, review, (String) disease.get(EntityUtils.ID),
                        (String) treatment.get(EntityUtils.ID), action);
            }

        } else {
            updateTreatmentReviewSummary(summary, user, review, (String) disease.get(EntityUtils.ID),
                    (String) treatment.get(EntityUtils.ID), action);
        }

        this.treatmentReviewSummaryService.computeTreatmentReviewSummaryStatistics(review, oldReview, action);

    } finally {
        lockManager.unlock(TreatmentReviewSummary.ENTITY_NAME, trsid);
    }
}

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

License:Apache License

/**
 * Updates existing treatment review summary
 * @param treatmentReviewSummary//from  www . java  2 s. c o m
 * @param review
 * @param reviewAction
 * @return error string in case error, null otherwise
 */
@SuppressWarnings("unchecked")
private DBObject updateTreatmentReviewSummary(DBObject treatmentReviewSummary, DBObject user, DBObject review,
        String diseaseId, String treatmentId, CRUDAction reviewAction) {
    if (treatmentReviewSummary == null) {
        return null;
    }

    String gender = UserUtils.getGender(user);
    String trsid = (String) treatmentReviewSummary.get(EntityUtils.ID);

    DBCursor trCursor = findAllTreatmentReviews(diseaseId, treatmentId, TreatmentReview.RATING,
            TreatmentReview.SIDE_EFFECTS,
            //
            TreatmentReview.CURRENCY, TreatmentReview.DOCTOR_COSTS, TreatmentReview.TREATMENT_PRICE,
            TreatmentReview.TREATMENT_QUANTITY, TreatmentReview.INSURANCE_COVERED,
            TreatmentReview.INSURANCE_COVERAGE, TreatmentReview.COINSURANCE);

    // go through all reviews and count them based on their value (group it) + add rating of given review
    // go through all side effects and count them based on side effect name (group it) + add side effects of given review
    Map<Number, DBObject> ratingsCounts = new HashMap<Number, DBObject>();
    Map<String, DBObject> trsSideEffects = new HashMap<String, DBObject>();

    int reviewsCount = 0;
    int ratingsCount = 0;
    BigDecimal ratingSum = BigDecimal.ZERO;

    List<TreatmentCost> treatmentCosts = new ArrayList<TreatmentCost>();

    for (DBObject tmpReview : trCursor) {
        if (CRUDAction.DELETE.equals(reviewAction)
                && String.class.cast(review.get(ID)).equalsIgnoreCase((String) tmpReview.get(EntityUtils.ID))) {
            continue;
        }

        TreatmentCost treatmentCost = TreatmentCost.createFromReview(tmpReview);
        if (treatmentCost != null) {
            treatmentCosts.add(treatmentCost);
        }

        reviewsCount++;
        Number trRating = (Number) tmpReview.get(TreatmentReview.RATING);
        if (trRating != null) {
            ++ratingsCount;

            ratingSum = ratingSum.add(new BigDecimal(trRating.doubleValue()));

            if (!ratingsCounts.containsKey(trRating)) {
                ratingsCounts.put(trRating, new BasicDBObject(EntityUtils.NAME, trRating).append("count", 1));
            } else {
                incrementCount(ratingsCounts.get(trRating));
            }
        }

        List<DBObject> trSideEffects = (List<DBObject>) tmpReview.get(TreatmentReview.SIDE_EFFECTS);
        if (trSideEffects != null) {
            createTreatmentReviewSummarySideEffects(trSideEffects, trsSideEffects);
        }
    }

    BigDecimal ratingAvg = null;
    if (ratingsCount > 0) {
        ratingAvg = ratingSum.divide(new BigDecimal(ratingsCount), 5, BigDecimal.ROUND_HALF_EVEN);
    }

    if (reviewsCount == 0 && CRUDAction.DELETE.equals(reviewAction)) {
        // no reviews then remove summary
        getCollection(TreatmentReviewSummary.ENTITY_NAME).remove(new BasicDBObject(EntityUtils.ID, trsid));
        getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS)
                .remove(new BasicDBObject("summaryId", trsid));
        getCollection(TreatmentCostStatistics.ENTITY_NAME)
                .remove(new BasicDBObject(TreatmentCostStatistics.SUMMARY_ID, trsid));
        getCollection(TreatmentDurationStatistics.ENTITY_NAME)
                .remove(new BasicDBObject(TreatmentCostStatistics.SUMMARY_ID, trsid));
    } else {
        DBObject setCommand = new BasicDBObject()
                .append(TreatmentReviewSummary.RATINGS, new ArrayList<>(ratingsCounts.values()))
                .append(TreatmentReviewSummary.SIDE_EFFECTS, new ArrayList<>(trsSideEffects.values()))
                .append(EntityUtils.MODIFIED_ON, new Date());
        BasicDBObject command = new BasicDBObject("$set", setCommand);

        if (ratingAvg != null) {
            setCommand.put(TreatmentReviewSummary.RATING, ratingAvg.doubleValue());
        } else {
            command.put("$unset", new BasicDBObject(TreatmentReviewSummary.RATING, ""));
        }

        int statsIncrement = 0;
        switch (reviewAction) {
        case CREATE:
            command.put("$unset", new BasicDBObject(TreatmentReviewSummary.SUGGESTION, ""));
            statsIncrement = 1;
            break;
        case DELETE:
            statsIncrement = -1;
            break;
        default:
            break;
        }

        if (statsIncrement != 0) {
            BasicDBObject incCommand = new BasicDBObject("reviewsCount", statsIncrement);
            if (user.get(User.ATTR_GENDER) != null) {
                incCommand.append("genderStatistics." + gender, statsIncrement);
            } else {
                incCommand.append("genderStatistics." + Gender.UNKNOWN.getValue(), statsIncrement);
            }

            command.append("$inc", incCommand);
        }

        getCollection(TreatmentReviewSummary.ENTITY_NAME).update(new BasicDBObject(EntityUtils.ID, trsid),
                command);

        for (Gender tmpgender : Gender.values()) {
            Query query = Query.query(Criteria.where("genderStatistics." + tmpgender.getValue()).lt(0));
            getCollection(TreatmentReviewSummary.ENTITY_NAME).update(query.getQueryObject(), new BasicDBObject(
                    "$set", new BasicDBObject("genderStatistics." + tmpgender.getValue(), 0)));
        }

        // handle YEAR_OF_BIRTH statistics - only in case CREATE or DELETE review
        if (statsIncrement != 0 && user.get(User.ATTR_YEAR_OF_BIRTH) != null) {
            boolean upsert = statsIncrement > 0;

            DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                    .is(trsid + user.get(User.ATTR_YEAR_OF_BIRTH) + gender).put("summaryId").is(trsid)
                    .and(User.ATTR_GENDER).is(gender).and(EntityUtils.NAME)
                    .is(user.get(User.ATTR_YEAR_OF_BIRTH)).get();

            command = new BasicDBObject("$inc", new BasicDBObject("count", statsIncrement));
            getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS).update(filter, command, upsert, false);
        }
    }

    return null;
}

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

License:Apache License

/** 
 * {@inheritDoc}//from  w ww. j a va  2s  .  co  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.user.impl.InvitationServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}/*from  w ww.j ava 2 s .co m*/
 * @see com.mobileman.kuravis.core.services.user.InvitationService#inviteeData(java.lang.String)
 */
@Override
public DBObject inviteeData(String email) {
    boolean userExists = userService.userExistsWithEmail(email);
    boolean invitationExists = count(new BasicDBObject("email", email)) > 0;
    boolean canBeregistered = invitationExists && !userExists;
    DBObject result = new BasicDBObject();
    result.put("canberegistered", canBeregistered);

    DBObject tempTreatmentReview = null;
    if (canBeregistered) {
        QueryBuilder query = QueryBuilder.start().put("subscription.email").is(email);
        List<DBObject> tempReviews = tempTreatmentReviewService.findAllByQuery(query.get());
        tempTreatmentReview = tempReviews.isEmpty() ? null : tempReviews.get(0);
    }

    result.put("treatmentReview", tempTreatmentReview);
    return result;
}

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

License:Apache License

/** 
 * {@inheritDoc}//from w  w  w  .  j  a  v a  2s.c o m
 * @see com.mobileman.kuravis.core.services.user.ReminderService#deleteAllRemindersOfEvent(java.lang.String)
 */
@Override
public void deleteAllRemindersOfEvent(String eventId) {
    QueryBuilder builder = QueryBuilder.start().put(Reminder.EVENT_ID).is(eventId);

    for (DBObject reminderData : findAllByQuery(builder.get())) {
        String quartzJobId = (String) reminderData.get(Reminder.QUARTZ_JOB_ID);
        try {
            this.schedulerFactoryBean.getScheduler().deleteJob(JobKey.jobKey(quartzJobId, ReminderJob.GROUP));
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        super.delete((String) reminderData.get(Reminder.ID));
    }
}

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

License:Apache License

/**
 * @param userId//  w  ww. jav  a  2s  .  co  m
 * @param newUserName
 */
private void applyUserNameUpdate(String userId, String newUserName) {

    String property = "author.name";

    DBObject filterUser = QueryBuilder.start().put("author." + EntityUtils.ID).is(userId).get();
    getCollection(TreatmentReview.ENTITY_NAME).update(filterUser,
            new BasicDBObject("$set", new BasicDBObject(property, newUserName)));
    getCollection(EntityUtils.TEMP_TREATMENT_REVIEW).update(filterUser,
            new BasicDBObject("$set", new BasicDBObject(property, newUserName)));

    for (String entityName : new String[] { TreatmentReview.ENTITY_NAME, EntityUtils.TEMP_TREATMENT_REVIEW,
            Event.ENTITY_NAME }) {
        getCollection(entityName).update(filterUser,
                new BasicDBObject("$set", new BasicDBObject(property, newUserName)));
    }

    filterUser = QueryBuilder.start().put("user." + EntityUtils.ID).is(userId).get();
    for (String entityName : new String[] { EntityUtils.TREATMENT_REVIEW_EVENT, UserNotification.ENTITY_NAME,
            Disease.ENTITY_NAME, EntityUtils.TREATMENT, EntityUtils.FRAUD_REPORT, EntityUtils.FRAUD_REPORT_ITEM,
            Event.ENTITY_NAME }) {
        getCollection(entityName).update(filterUser,
                new BasicDBObject("$set", new BasicDBObject("user.name", newUserName)));
    }
}

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

License:Apache License

/** 
 * {@inheritDoc}/*from   w  w  w.  ja  va 2s . c  o m*/
 * @see com.mobileman.kuravis.core.services.user.UserService#findUserSettings(java.lang.String)
 */
@Override
public DBObject findUserSettings(String userId) {
    DBObject filter = QueryBuilder.start().put(EntityUtils.ID).is(userId).get();
    DBObject userData = getCollection().findOne(filter, new BasicDBObject("settings", 1));
    return userData != null ? (DBObject) userData.get("settings") : null;
}