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

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

Introduction

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

Prototype

public static Criteria where(String key) 

Source Link

Document

Static factory method to create a Criteria using the provided key

Usage

From source file:com.traffitruck.service.MongoDAO.java

public LoadsUser getUser(String username) {
    Query query = new Query().addCriteria(Criteria.where("username").is(username));
    query.fields().exclude("password");
    return mongoTemplate.findOne(query, LoadsUser.class);
}

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

@Override
public ResponseDo getActivityInfo(String userId, String activityId, Landmark landmark) throws ApiException {
    LOG.debug("getActivityInfo");

    Criteria criteria = Criteria.where("activityId").is(activityId);
    criteria.and("deleteFlag").is(false);
    Activity activity = activityDao.findOne(Query.query(criteria));
    if (null == activity) {
        LOG.warn("activity not exist");
        throw new ApiException("id ?");
    }/*from   w w w.  j  av a 2s. com*/
    User organizer = userDao.findById(activity.getUserId());
    if (null == organizer) {
        LOG.error("the activity {} cannot found the organizer user {}", activityId, userId);
        throw new ApiException("? User");
    }
    Map<String, Object> map = organizer.buildCommonUserMap();
    User.appendCover(map, userDao.getCover(activity.getCover(), organizer.getUserId()));
    activity.setOrganizer(map);
    if (landmark.getLatitude() != null && landmark.getLongitude() != null) {
        activity.setDistance(DistanceUtil.getDistance(landmark, activity.getEstabPoint()));
    }
    return ResponseDo.buildSuccessResponse(activity);
}

From source file:com.traffitruck.service.MongoDAO.java

public LoadsUser getUserByEmail(String email) {
    Query query = new Query().addCriteria(Criteria.where("email").is(email));
    query.fields().exclude("password");
    return mongoTemplate.findOne(query, LoadsUser.class);
}

From source file:net.cit.tetrad.rrd.dao.DataAccessObjectForMongoImpl.java

public void updateServerStatusInfo(int deviceCode) {
    try {/*w ww.  j a  v a2 s  .c o  m*/
        Query query = new Query(Criteria.where(DEVICECODE).is(deviceCode));
        Update update = new Update();
        update.set(SERVERSTATUS_OK, 0);
        update.set(SERVERSTATUS_ERROR, 0);

        operations.updateMulti(query, update, COLL_DASHBOARD);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:it.smartcommunitylab.climb.domain.controller.ChildController.java

@RequestMapping(value = "/api/child/image/info/{ownerId}/{objectId}", method = RequestMethod.GET)
public @ResponseBody Avatar getAvatarInfo(@PathVariable String ownerId, @PathVariable String objectId,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Criteria criteria = Criteria.where("objectId").is(objectId);
    Child child = storage.findOneData(Child.class, criteria, ownerId);
    if (child == null) {
        throw new EntityNotFoundException("child not found");
    }/*from  w ww .j  a  v  a 2 s.c  o  m*/
    if (!validateAuthorization(ownerId, child.getInstituteId(), child.getSchoolId(), null, null,
            Const.AUTH_RES_Image, Const.AUTH_ACTION_READ, request)) {
        throw new UnauthorizedException("Unauthorized Exception: token not valid");
    }
    criteria = Criteria.where("resourceId").is(objectId).and("resourceType").is(Const.AUTH_RES_Child);
    Avatar avatar = storage.findOneData(Avatar.class, criteria, ownerId);
    if (avatar == null) {
        throw new EntityNotFoundException("avatar not found");
    }
    avatar.setImage(null);
    return avatar;
}

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

@Override
public ResponseDo forgetPassword(User user, String code) throws ApiException {
    LOG.debug("Begin reset password by forget password");

    // ??/*from   w  w  w.ja  v  a 2 s  .  c  om*/
    if (!CommonUtil.isPhoneNumber(user.getPhone())) {
        LOG.warn("invalid params");
        throw new ApiException("?");
    }

    // ???
    checker.checkPhoneVerifyCode(user.getPhone(), code);

    // ?
    User userData = userDao.findOne(Query.query(Criteria.where("phone").is(user.getPhone())));
    if (userData == null) {
        LOG.warn("Fail to find user");
        throw new ApiException("?");
    }

    // ?
    chatThirdService.alterUserPassword(chatCommonService.getChatToken(), userData.getEmchatName(),
            user.getPassword());

    LOG.debug("Begin reset emchat account password by forget password");

    userDao.update(Query.query(Criteria.where("userId").is(userData.getUserId())),
            Update.update("password", user.getPassword()));

    Map<String, Object> map = userData.buildFullUserMap();
    User.appendToken(map, refreshUserToken(userData.getUserId()));
    User.appendAlbum(map, photoDao.getUserAlbum(userData.getUserId()));

    return ResponseDo.buildSuccessResponse(map);
}

From source file:net.cit.tetrad.rrd.dao.DataAccessObjectForMongoImpl.java

public void setGloballLockPageFaults(Map<String, Object> serverStatusFromMongo) {
    logger.info("\t start settingGloballLock and PageFaults");
    try {//from  w w w  . j a  v  a2s.c o  m
        Query query = new Query(Criteria.where(COL_DEVICECODE).is(serverStatusFromMongo.get(COL_DEVICECODE)));
        query.sort().on(SERVERSTATUS_REGTIME, Order.DESCENDING);

        ServerStatus recentServerStatus = operations.findOne(query, ServerStatus.class, COLL_DASHBOARD);

        if (recentServerStatus != null) {
            double recentGloballlocktime = recentServerStatus.getGlobalLock_lockTime();
            double recentPagefaults = recentServerStatus.getExtra_info_page_faults();
            double recentGlobalLocksLocked_R = recentServerStatus.getLocks_timeLockedMicros_R();
            double recentGlobalLocksLocked_W = recentServerStatus.getLocks_timeLockedMicros_W();
            double recentDbSumLocksLocked_r = recentServerStatus.getDb_sum_locks_timeLockedMicros_r();
            double recentDbSumLocksLocked_w = recentServerStatus.getDb_sum_locks_timeLockedMicros_w();

            double currentGloballLocktime = CriticalHelper
                    .convertToDouble(serverStatusFromMongo.get(SERVERSTATUS_GLOBALLLOCKTIME));
            double currentPagefaults = CriticalHelper
                    .convertToDouble(serverStatusFromMongo.get(SERVERSTATUS_PAGEFAULTS));
            double currentGlobalLocksLocked_R = CriticalHelper
                    .convertToDouble(serverStatusFromMongo.get(SERVERSTATUS_LOCKSTIMELOCKEDMICROS_R));
            double currentGlobalLocksLocked_W = CriticalHelper
                    .convertToDouble(serverStatusFromMongo.get(SERVERSTATUS_LOCKSTIMELOCKEDMICROS_W));
            double currentDbSumLocksLocked_r = CriticalHelper
                    .convertToDouble(serverStatusFromMongo.get(SERVERSTATUS_DBSUMLOCKSLOCKED_R));
            double currentDbSumLocksLocked_w = CriticalHelper
                    .convertToDouble(serverStatusFromMongo.get(SERVERSTATUS_DBSUMLOCKSLOCKED_W));

            double diffGlobalLockTime = currentGloballLocktime - recentGloballlocktime;
            double diffPageFaults = currentPagefaults - recentPagefaults;
            double diffGlobalLocksLocked_R = currentGlobalLocksLocked_R - recentGlobalLocksLocked_R;
            double diffGlobalLocksLocked_W = currentGlobalLocksLocked_W - recentGlobalLocksLocked_W;
            double diffDbSumLocksLocked_r = currentDbSumLocksLocked_r - recentDbSumLocksLocked_r;
            double diffDbSumLocksLocked_w = currentDbSumLocksLocked_w - recentDbSumLocksLocked_w;

            logger.debug("GlobalLockTime : " + currentGloballLocktime + " - " + recentGloballlocktime + " = "
                    + diffGlobalLockTime);
            logger.debug(
                    "PageFaults : " + currentPagefaults + " - " + recentPagefaults + " = " + diffPageFaults);

            serverStatusFromMongo.put(SERVERSTATUS_DIFF_GLOBALLLOCKTIME, diffGlobalLockTime);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_PAGEFAULTS, diffPageFaults);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_LOCKSTIMELOCKEDMICROS_R, diffGlobalLocksLocked_R);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_LOCKSTIMELOCKEDMICROS_W, diffGlobalLocksLocked_W);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_DBSUMLOCKSLOCKED_R, diffDbSumLocksLocked_r);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_DBSUMLOCKSLOCKED_W, diffDbSumLocksLocked_w);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("\t end settingGloballLock and PageFaults");
}

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

@Override
public ResponseDo sendAppointment(String activityId, String userId, Appointment appointment)
        throws ApiException {
    Activity activity = activityDao.findOne(Query.query(Criteria.where("activityId").is(activityId)));
    if (activity == null) {
        LOG.warn("No activity exist : {}", activityId);
        throw new ApiException("");
    }//from www  .j av  a  2 s  . com

    List<String> members = activity.getMembers();
    for (String member : members) {
        if (member.equals(userId)) {
            LOG.warn("Already be a member");
            throw new ApiException("????");
        }
    }

    Appointment appointmentData = appointmentDao.findOne(Query.query(Criteria.where("activityId").is(activityId)
            .and("applyUserId").is(userId).and("status").is(Constants.AppointmentStatus.APPLYING)));
    if (appointmentData != null) {
        LOG.warn("already applying for this activity");
        throw new ApiException("??");
    }

    User user = userDao.findById(userId);

    Long current = DateUtil.getTime();
    appointment.setActivityId(activity.getActivityId());
    appointment.setApplyUserId(userId);
    appointment.setInvitedUserId(activity.getUserId());
    appointment.setCreateTime(current);
    appointment.setStatus(Constants.AppointmentStatus.APPLYING);
    appointment.setModifyTime(current);
    appointment.setActivityCategory(Constants.ActivityCatalog.COMMON);
    //appointment destination activity destination  destPoint   estabPoint
    //appointment  estabPoint  applyUserId ? landmark
    appointment.setDestPoint(activity.getEstabPoint());
    appointment.setDestination(activity.getDestination());
    appointment.setEstabPoint(user.getLandmark());
    appointment.setDistance(DistanceUtil.getDistance(appointment.getEstabPoint(), appointment.getDestPoint()));
    appointmentDao.save(appointment);

    //?ID
    Update update = new Update();
    update.addToSet("applyIds", userId);
    activityDao.update(activityId, update);

    //????
    User organizer = userDao.findById(activity.getUserId());
    User applier = userDao.findById(userId);
    String message = MessageFormat.format(
            PropertiesUtil.getProperty("dynamic.format.activity.invite", "{0}{1}"),
            applier.getNickname(), activity.getType());
    chatThirdPartyService.sendUserGroupMessage(chatCommonService.getChatToken(),
            Constants.EmchatAdmin.ACTIVITY_STATE, organizer.getEmchatName(), message);

    return ResponseDo.buildSuccessResponse();
}

From source file:it.smartcommunitylab.climb.domain.controller.ChildController.java

@RequestMapping(value = "/api/child/image/download/{ownerId}/{objectId}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<byte[]> downloadAvatar(@PathVariable String ownerId,
        @PathVariable String objectId, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Criteria criteria = Criteria.where("objectId").is(objectId);
    Child child = storage.findOneData(Child.class, criteria, ownerId);
    if (child == null) {
        throw new EntityNotFoundException("child not found");
    }//from   w w w.ja  v  a 2s  .c  om
    if (!validateAuthorization(ownerId, child.getInstituteId(), child.getSchoolId(), null, null,
            Const.AUTH_RES_Image, Const.AUTH_ACTION_READ, request)) {
        throw new UnauthorizedException("Unauthorized Exception: token not valid");
    }
    criteria = Criteria.where("resourceId").is(objectId).and("resourceType").is(Const.AUTH_RES_Child);
    Avatar avatar = storage.findOneData(Avatar.class, criteria, ownerId);
    if (avatar == null) {
        throw new EntityNotFoundException("avatar not found");
    }
    byte[] data = avatar.getImage().getData();
    if (logger.isInfoEnabled()) {
        logger.info(String.format("downloadAvatar[%s]:%s", ownerId, objectId));
    }
    response.setHeader("Cache-Control", "public, max-age=86400");
    return ResponseEntity.ok().contentType(MediaType.parseMediaType(avatar.getContentType()))
            .contentLength(data.length).body(data);
}

From source file:com.gongpingjia.carplay.official.service.impl.OfficialApproveServiceImpl.java

@Override
public ResponseDo authUserAlbum(String userId, JSONObject json) throws ApiException {
    LOG.debug("Auth user album, delete users:{}", json);
    JSONArray deleteIds = json.getJSONArray("deleteIds");
    JSONArray remainIds = json.getJSONArray("remainIds");

    LOG.debug("Delete photo file on remote server");
    List<Photo> deletePhotos = photoDao.findByIds(deleteIds);
    Set<String> userIds = new HashSet<>(deletePhotos.size(), 1);
    for (Photo item : deletePhotos) {
        userIds.add(item.getUserId());/* www  .j ava  2  s .co  m*/
        try {
            thirdPhotoService.delete(item.getKey());
        } catch (ApiException e) {
            LOG.warn("Delete user photo failure with key:{}", item.getKey());
        }
    }

    LOG.debug("Delete photo record and update checked info on database");
    photoDao.deleteByIds(deleteIds);
    photoDao.update(Query.query(Criteria.where("id").in(remainIds)),
            Update.update("checked", Constants.Flag.POSITIVE));

    AlbumAuthHistory history = new AlbumAuthHistory();
    history.setAuthUserId(userId);
    if (json.containsKey("remark")) {
        history.setRemark(json.getString("remark"));
    }
    history.setAuthTime(DateUtil.getTime());
    history.setDeleteUsers(userIds.toArray(new String[0]));
    albumAuthHistoryDao.save(history);

    List<User> users = userDao.findByIds(userIds);
    List<String> emchatNames = new ArrayList<>(users.size());
    for (User item : users) {
        emchatNames.add(item.getEmchatName());
    }

    LOG.debug("Send users emcahat message");
    String message = PropertiesUtil.getProperty("dynamic.format.delete.album.notice",
            "????");
    chatThirdPartyService.sendUserGroupMessage(chatCommonService.getChatToken(), Constants.EmchatAdmin.OFFICIAL,
            emchatNames, message, new Object());

    return ResponseDo.buildSuccessResponse();
}