Example usage for org.springframework.data.mongodb.core.query Criteria Criteria

List of usage examples for org.springframework.data.mongodb.core.query Criteria Criteria

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.query Criteria Criteria.

Prototype

public Criteria() 

Source Link

Usage

From source file:com.epam.ta.reportportal.database.dao.ReportPortalRepositoryImpl.java

@Override
public long getPageNumber(String entityId, Filter filterable, Pageable pageable) {
    Class<T> javaType = this.getEntityInformation().getJavaType();
    ImmutableList.Builder<AggregationOperation> pipelineBuilder = ImmutableList.<AggregationOperation>builder()
            .add(new MatchOperation(
                    new Criteria().andOperator(toArray(toCriteriaList(filterable), Criteria.class))) {
                @Override// w  w w  .j  a v a 2 s . co m
                public DBObject toDBObject(AggregationOperationContext context) {
                    return super.toDBObject(new TypeBasedAggregationOperationContext(javaType,
                            mongoOperations.getConverter().getMappingContext(), queryMapper));
                }
            });

    if (null != pageable.getSort()) {
        pipelineBuilder.add(
                /* sort results as requested */
                sort(pageable.getSort()));
    }

    pipelineBuilder.add(
            /* group items into one field pushing all results into one array */
            group("result").push("$_id").as("array"),
            /* unwind array adding index to each result */
            unwind("array", "ind", false),
            /* find needed item. How we know its index in query result */
            match(where("array").is(ObjectId.isValid(entityId) ? new ObjectId(entityId) : entityId)),
            /* grab index only */
            project("ind"));

    /* find items matching an provided filter */
    Aggregation a = Aggregation.newAggregation(toArray(pipelineBuilder.build(), AggregationOperation.class));

    final AggregationResults<Map> aggregate = mongoOperations.aggregate(a,
            getEntityInformation().getCollectionName(), Map.class);

    if (!aggregate.getUniqueMappedResult().containsKey("ind")) {
        throw new ReportPortalException(ErrorType.INCORRECT_FILTER_PARAMETERS,
                "Unable to calculate page number. Check your input parameters");
    }

    /* result returned as long. Calculate page number */
    return (long) Math.ceil((((Long) aggregate.getUniqueMappedResult().get("ind")).doubleValue() + 1d)
            / (double) pageable.getPageSize());
}

From source file:com.epam.ta.reportportal.database.dao.TestItemRepositoryCustomImpl.java

@Override
public List<TestItem> findTestItemWithInvestigated(String launchId) {
    Criteria internalIssues = new Criteria().andOperator(where(LAUNCH_REFERENCE).is(launchId),
            where(ISSUE_TYPE).ne(TestItemIssueType.TO_INVESTIGATE.name()),
            where(ISSUE_DESCRIPTION).exists(true));

    Criteria externalIssues = new Criteria().andOperator(where(LAUNCH_REFERENCE).is(launchId),
            where(ISSUE_TYPE).exists(true), where(ISSUE_TICKET).exists(true));

    Query query = query(new Criteria().orOperator(internalIssues, externalIssues));

    query.limit(HISTORY_LIMIT);//from  w  w w .  ja  v a2 s . com
    query.fields().include("name");
    query.fields().include("launchRef");
    query.fields().include("issue");
    query.fields().include("status");
    query.fields().include(ID_REFERENCE);

    query.fields().include("start_time");

    return mongoTemplate.find(query, TestItem.class);
}

From source file:com.seajas.search.profiler.service.repository.RepositoryService.java

/**
 * Create a query given any or all of the provided parameters.
 *
 * @param allStates/*from  w  w  w  .  j a v a  2  s.  c  o  m*/
 * @param collection
 * @param sourceId
 * @param taxonomyMatch
 * @param startDate
 * @param endDate
 * @param url
 * @return Query
 */
private Query createQuery(final Boolean allStates, final String collection, final Integer sourceId,
        final String taxonomyMatch, final Date startDate, final Date endDate, final String url,
        final Map<String, String> parameters) {
    Query query = new Query();

    if (!allStates)
        query.addCriteria(
                new Criteria().orOperator(where("currentState").is(CompositeState.CompletedDocument.name()),
                        where("currentState").is(CompositeState.InitialDocument.name())));

    if (collection != null)
        query.addCriteria(where("source.collection").is(collection));
    if (sourceId != null)
        query.addCriteria(where("source.id").is(sourceId));
    if (taxonomyMatch != null)
        query.addCriteria(where("originalContent.hostname").is(taxonomyMatch));

    if (startDate != null || endDate != null) {
        Criteria dateCriteria = where("originalContent.dateSubmitted");

        if (startDate != null)
            dateCriteria = dateCriteria.gte(startDate);
        if (endDate != null)
            dateCriteria = dateCriteria.lt(endDate);

        query.addCriteria(dateCriteria);
    }

    if (parameters != null && parameters.size() > 0)
        for (Map.Entry<String, String> parameter : parameters.entrySet()) {
            if (parameter.getKey().contains(".") || parameter.getKey().contains("$"))
                throw new IllegalStateException("Can't add criteria for parameter '" + parameter.getKey()
                        + "' because it contains invalid characters");

            query.addCriteria(
                    where("source.resultParameters." + StringEscapeUtils.escapeJavaScript(parameter.getKey()))
                            .is(parameter.getValue()));
        }

    if (url != null)
        query.addCriteria(where("originalContent.uri").is(url));

    return query;
}

From source file:com.epam.ta.reportportal.database.dao.TestItemRepositoryCustomImpl.java

/**
 * Create {@link Criteria} object for items history selecting Define name
 * type conditions./*  w  w w  .j ava  2  s. co  m*/
 *
 * @param testItems
 * @return
 */
private Criteria getItemsHistoryCriteria(List<TestItem> testItems) {
    Criteria criteria = new Criteria();
    Criteria[] itemCriteries = new Criteria[testItems.size()];

    for (int i = 0; i < testItems.size(); i++) {
        TestItem testItem = testItems.get(i);
        Criteria one = where("name").is(testItem.getName()).and("type").is(testItem.getType().toString());
        if (null != testItem.getItemDescription())
            one.and("itemDescription").is(testItem.getItemDescription());
        if (null != testItem.getTags())
            one.and("tags").is(testItem.getTags());
        itemCriteries[i] = one;
    }

    criteria.orOperator(itemCriteries);
    return criteria;
}

From source file:com.epam.ta.reportportal.database.dao.TestItemRepositoryCustomImpl.java

@Override
public List<TestItem> findTestItemWithIssues(String launchId) {
    Criteria externalIssues = new Criteria().andOperator(where(LAUNCH_REFERENCE).is(launchId),
            where(ISSUE).exists(true));/*from   ww  w  .  j  a v  a 2  s.  c  om*/
    Query query = query(externalIssues);
    return mongoTemplate.find(query, TestItem.class);
}

From source file:com.gongpingjia.carplay.service.impl.UserServiceImpl.java

@Override
public ResponseDo getMyActivityAppointments(String userId, String token, Integer[] status, Integer limit,
        Integer ignore) throws ApiException {

    LOG.info("getMyActivityAppointments userId {}", userId);

    checker.checkUserInfo(userId, token);
    //???//from  w w  w  . j  a  v  a2s . c om
    Criteria criteria = new Criteria().orOperator(Criteria.where("invitedUserId").is(userId),
            Criteria.where("applyUserId").is(userId));
    if (status != null && status.length > 0) {
        criteria.andOperator(Criteria.where("status").in(Arrays.asList(status)));
    }
    List<Appointment> appointments = appointmentDao.find(Query.query(criteria)
            .with(new Sort(new Sort.Order(Sort.Direction.DESC, "modifyTime"))).skip(ignore).limit(limit));

    return ResponseDo.buildSuccessResponse(buildUserActivities(userId, appointments));
}

From source file:com.gongpingjia.carplay.service.impl.ActivityServiceImpl.java

/**
 * ???   /*from ww w .  ja v  a 2  s  . com*/
 * <p/>
 * criteria:
 * city    estabPoint.city
 * phone ? phone user  ? userId   activity
 * fromDate  toDate           createTime
 * pay  -1 ??               ? AA
 * type -1            type ? type
 * transfer  -1       true  false
 *
 * @param json
 * @return
 * @throws ApiException
 */
@Override
public ResponseDo getUserActivityList(JSONObject json, String userId) throws ApiException {
    //TODO?
    int draw = json.getInt("draw");
    int start = json.getInt("start");
    int length = json.getInt("length");

    JSONObject resultJson = new JSONObject();

    Query query = new Query();
    Criteria criteria = new Criteria();

    String startTimeStr = json.getString("fromTime");
    String endTimeStr = json.getString("toTime");
    if (StringUtils.isNotEmpty(startTimeStr) && StringUtils.isNotEmpty(endTimeStr)) {
        long startTime = TypeConverUtil.convertToLong("fromTime", startTimeStr, true);
        long endTime = TypeConverUtil.convertToLong("toTime", endTimeStr, true) + 24 * 60 * 60 * 1000;
        criteria.and("createTime").gte(startTime).lte(endTime);
    }

    String phone = json.getString("phone");
    if (StringUtils.isNotEmpty(phone)) {
        User user = userDao.findOne(Query.query(Criteria.where("phone").is(phone)));
        if (null == user || StringUtils.isEmpty(user.getUserId())) {
            throw new ApiException("???");
        }
        criteria.and("userId").is(user.getUserId());
    }

    criteria.and("deleteFlag").is(false);

    String province = json.getString("province");
    if (StringUtils.isNotEmpty(province)) {
        criteria.and("destination.province").is(province);
    }

    String city = json.getString("city");
    if (StringUtils.isNotEmpty(city)) {
        criteria.and("destination.city").is(city);
    }

    String majorType = json.getString("majorType");
    if (StringUtils.isNotEmpty(majorType)) {
        criteria.and("majorType").is(majorType);
    }

    String type = json.getString("type");
    if (StringUtils.isNotEmpty(type) && !StringUtils.equals(type, "-1")) {
        criteria.and("type").is(type);
    }

    String pay = json.getString("pay");
    if (StringUtils.isNotEmpty(pay) && !StringUtils.equals(pay, "-1")) {
        criteria.and("pay").is(pay);
    }

    String transferStr = json.getString("transfer");
    if (StringUtils.isNotEmpty(transferStr) && !StringUtils.equals(transferStr, "-1")) {
        criteria.and("transfer").is(TypeConverUtil.convertToBoolean("transfer", transferStr, true));
    }

    query.addCriteria(criteria);

    long totalNum = activityDao.count(query);

    query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")));
    query.skip(start).limit(length);
    List<Activity> activityList = activityDao.find(query);

    resultJson.put("draw", draw);
    resultJson.put("recordsFiltered", totalNum);
    resultJson.put("recordsTotal", totalNum);

    if (null == activityList || activityList.isEmpty()) {
        return ResponseDo.buildSuccessResponse(resultJson);
    }

    Set<String> userIdSet = new HashSet<>(activityList.size());
    for (Activity activity : activityList) {
        userIdSet.add(activity.getUserId());
    }

    List<User> userList = userDao.findByIds(userIdSet);

    Map<String, User> userMap = new HashMap<>(userList.size());
    if (null == userList || userList.isEmpty()) {
        throw new ApiException(" ??");
    }
    for (User user : userList) {
        userMap.put(user.getUserId(), user);
    }

    JSONArray jsonArray = new JSONArray();
    for (Activity activity : activityList) {
        JSONObject item = new JSONObject();
        item.put("activityId", activity.getActivityId());
        item.put("nickname", userMap.get(activity.getUserId()).getNickname());
        item.put("phone", userMap.get(activity.getUserId()).getPhone());
        item.put("establish", activity.getEstablish());
        item.put("destination", activity.getDestination());
        item.put("type", activity.getType());
        item.put("pay", activity.getPay());
        item.put("transfer", activity.isTransfer());
        item.put("createTime", activity.getCreateTime());
        item.put("cover", userDao.getCover(activity.getCover(), activity.getUserId()));

        jsonArray.add(item);
    }
    resultJson.put("activityList", jsonArray);

    return ResponseDo.buildSuccessResponse(resultJson);
}

From source file:com.gongpingjia.carplay.service.impl.ActivityServiceImpl.java

@Override
public ResponseDo viewUserActivity(String activityId) throws ApiException {
    Activity activity = activityDao.findById(activityId);
    if (null == activity) {
        throw new ApiException("?");
    }//  ww w. ja  va2 s .com
    User organizer = userDao.findById(activity.getUserId());
    if (null == organizer || StringUtils.isEmpty(organizer.getUserId())) {
        throw new ApiException("");
    }
    activity.setOrganizer(organizer.buildCommonUserMap());

    Criteria criteria = new Criteria();
    criteria.and("activityId").is(activity.getActivityId());
    Query query = Query.query(criteria);
    query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")));
    List<Appointment> appointmentList = appointmentDao.find(query);
    if (null != appointmentList && !appointmentList.isEmpty()) {
        activity.setAppointmentList(appointmentList);
    }
    return ResponseDo.buildSuccessResponse(activity);
}

From source file:com.gongpingjia.carplay.service.impl.UserServiceImpl.java

/**
 * ????//from  w ww  . java2s  .  c  o m
 *
 * @param viewUserId
 * @param userId
 * @param limit
 * @param ignore
 * @return
 * @throws ApiException
 */
@Override
public ResponseDo getUserActivityList(String viewUserId, String userId, int limit, int ignore)
        throws ApiException {
    User viewUser = userDao.findById(viewUserId);
    User nowUser = userDao.findById(userId);
    if (null == viewUser) {
        LOG.error("the view user not exist userId is:{}", viewUserId);
        throw new ApiException("?");
    }
    //
    if (viewUserId.equals(userId)) {
        LOG.warn("view self:viewUserId:{} userId:{}", viewUserId, userId);
    }

    //       ???
    Criteria criteria = new Criteria();
    criteria.and("userId").is(viewUserId);
    criteria.and("deleteFlag").is(false);
    Query query = Query.query(criteria);
    query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")));
    query.skip(ignore).limit(limit);
    List<Activity> activityList = activityDao.find(query);

    if (null == activityList || activityList.isEmpty()) {
        return ResponseDo.buildSuccessResponse("[]");
    }

    //? activityIds applyUserId(userId)    ? appointment
    List<String> activityIds = new ArrayList<>(activityList.size());
    for (Activity activity : activityList) {
        activityIds.add(activity.getActivityId());
    }
    Criteria appointCriteria = new Criteria();
    appointCriteria.and("applyUserId").is(userId);
    appointCriteria.and("activityId").in(activityIds);
    appointCriteria.and("activityCategory").is(Constants.ActivityCatalog.COMMON);
    List<Appointment> appointmentList = appointmentDao.find(Query.query(appointCriteria));
    if (null == appointmentList) {
        appointmentList = new ArrayList<>();
    }

    //AppointmentList ?Appointment applyUserId=userId invitedUserId=viewUserId
    // activityId ?  AppointmentList Appointment
    Map<String, Appointment> activityIdToAppointmentMap = new HashMap<>(appointmentList.size());
    for (Appointment appointment : appointmentList) {
        activityIdToAppointmentMap.put(appointment.getActivityId(), appointment);
    }

    Map<String, Object> resultMap = new HashMap<>();
    //
    //        resultMap.put("cover", userDao.getCover(viewUser.getUserId()));
    //        resultMap.put("distance", DistanceUtil.getDistance(viewUser.getLandmark(), nowUser.getLandmark()));

    //??+?
    ArrayList<Map<String, Object>> activityInfoList = new ArrayList<>(activityList.size());

    for (Activity activity : activityList) {
        Map<String, Object> itemMap = new HashMap<>();
        itemMap.put("activityId", activity.getActivityId());
        itemMap.put("establish", activity.getEstablish());
        itemMap.put("estabPoint", activity.getEstabPoint());
        itemMap.put("type", activity.getType());
        itemMap.put("pay", activity.getPay());
        itemMap.put("transfer", activity.isTransfer());
        itemMap.put("destination", activity.getDestination());
        itemMap.put("destPoint", activity.getDestPoint());
        itemMap.put("createTime", activity.getCreateTime());
        itemMap.put("distance", DistanceUtil.getDistance(nowUser.getLandmark(), activity.getEstabPoint()));

        //? ? 0  1  3 ??? 4 ?
        int applyStatus = Constants.AppointmentStatus.INITIAL;
        Appointment appointment = activityIdToAppointmentMap.get(activity.getActivityId());
        if (null != appointment) {
            applyStatus = appointment.getStatus();
        }
        itemMap.put("status", applyStatus);
        itemMap.put("cover", userDao.getCover(activity.getCover(), viewUser.getUserId()));

        activityInfoList.add(itemMap);
    }

    resultMap.put("activities", activityInfoList);

    return ResponseDo.buildSuccessResponse(resultMap);
}

From source file:org.opentestsystem.authoring.testauth.persistence.BlueprintElementRepositoryImpl.java

@Override
public List<BlueprintElement> findAllChildrenByAssessmentIdAndGradeAndParentKey(final String assessmentId,
        final String grade, final String inParentKey) {
    final Query query = new Query();

    // search for blueprint elements within the given assessment and grade
    query.addCriteria(Criteria.where("assessmentId").is(assessmentId));
    query.addCriteria(Criteria.where("grade").is(grade));

    // if parentKey provided, filter to include only elements under the given parentKey tree
    // e.g. parentKey == inParentKey || parentKey starts with inParentKey|
    if (StringUtils.isNotBlank(inParentKey)) {
        final Criteria searchValCriteria = new Criteria().orOperator(
                Criteria.where("parentKey").is(inParentKey), Criteria.where("standardKey").is(inParentKey),
                Criteria.where("parentKey").regex("^" + escapeString(inParentKey) + "\\|"));

        query.addCriteria(searchValCriteria);
    }/*from ww w  . j av a2 s . co  m*/

    return this.mongoOperations.find(query, BlueprintElement.class);
}