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.gongpingjia.carplay.service.impl.ActivityServiceImpl.java

private Set<String> getSubscribeUsers(User user) {
    LOG.debug("Get subscribed users");
    List<Subscriber> subscriberList = subscriberDao
            .find(Query.query(Criteria.where("toUser").is(user.getUserId())));
    Set<String> subUserIdSet = new HashSet<>(subscriberList.size());
    for (Subscriber item : subscriberList) {
        subUserIdSet.add(item.getFromUser());
    }//  w w w.  j  a v  a  2s. co  m
    return subUserIdSet;
}

From source file:com.charmyin.shiro.realm.jdbc.JMongodbRealm.java

private String[] getPasswordForUser(String username) throws MongoException {

    String[] result;/*from ww w. j av a2  s .  c  o  m*/
    switch (saltStyle) {
    case NO_SALT:
    case CRYPT:
    case EXTERNAL:
        result = new String[1];
        break;
    default:
        result = new String[2];
    }

    try {
        // "select passphrase, CONCAT('${shiro.applicationSalt}', ':', salt) as salt from shiro_user where login_id = ?"
        User user = mongoOperations.findOne(new Query(Criteria.where("loginId").is(username)), User.class,
                "shiro_user");
        result[0] = user.getPassphrase();
        result[1] = shiroSalt + ":" + user.getSalt();
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        throw new MongoException("Mongo query exception when get PasswordForUser");
    }

    return result;
}

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

public List<Truck> getNonApprovedTrucks() {
    Query findNonApprovedTrucks = new Query()
            .addCriteria(Criteria.where("registrationStatus").is(TruckRegistrationStatus.REGISTERED));
    findNonApprovedTrucks.fields().exclude("vehicleLicensePhoto");
    findNonApprovedTrucks.fields().exclude("truckPhoto");
    findNonApprovedTrucks.with(new Sort("creationDate"));
    return mongoTemplate.find(findNonApprovedTrucks, Truck.class);
}

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

@RequestMapping(value = "/api/child/image/upload/{ownerId}/{objectId}", method = RequestMethod.POST)
public @ResponseBody void uploadAvatar(@PathVariable String ownerId, @PathVariable String objectId,
        @RequestParam("data") MultipartFile data, 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");
    }//w w w.  j  ava2s  .c o  m
    if (!validateAuthorization(ownerId, child.getInstituteId(), child.getSchoolId(), null, null,
            Const.AUTH_RES_Image, Const.AUTH_ACTION_ADD, 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) {
        avatar = new Avatar();
        avatar.setOwnerId(ownerId);
        avatar.setObjectId(Utils.getUUID());
        avatar.setResourceId(objectId);
        avatar.setResourceType(Const.AUTH_RES_Child);
    }
    avatar.setContentType(data.getContentType());
    avatar.setImage(new Binary(data.getBytes()));
    if (logger.isInfoEnabled()) {
        logger.info(String.format("uploadAvatar[%s]:%s", ownerId, objectId));
    }
    storage.saveAvatar(avatar);
}

From source file:de.steilerdev.myVerein.server.controller.admin.SettingsController.java

/**
 * This function is saving the settings for the system durable. In case the database connection changed, the system is restarted. The function is invoked by POSTing the parameters to the URI /api/admin/settings.
 * NOTE: At the moment the restarting of the application is not working correctly. To apply changed database settings the application needs to be redeployed manually from the management interface.
 * @param currentAdmin If the logged in user is a super admin, this field specifies the new super admin. If the logged in user is a normal admin, this field needs to contain his email.
 * @param adminPasswordNew The new password for the currently logged in admin.
 * @param adminPasswordNewRe The retyped new password for the currently logged in admin.
 * @param clubName The club name./*  ww w.j a v  a2  s.  c o m*/
 * @param clubLogo The club logo. If this parameter is present the former club logo is going to be replaced.
 * @param databaseHost The hostname of the used MongoDB server.
 * @param databasePort The port of the used MongoDB server.
 * @param databaseUser The username, used to authenticate against the MongoDB server.
 * @param databasePassword The password, used to authenticate against the MongoDB server.
 * @param databaseCollection The name of the database collection, where the data of this system is stored in.
 * @param rememberMeTokenKey The phrase used to secure the remember me cookies.
 * @param parameters The complete map of all parameters, containing the custom user fields.
 * @param currentAdminPassword The password of the currently logged in user, used to authenticate the changes.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveSettings(@RequestParam(required = false) String currentAdmin,
        @RequestParam(required = false) String adminPasswordNew,
        @RequestParam(required = false) String adminPasswordNewRe,
        @RequestParam(required = false) String clubName, @RequestParam(required = false) MultipartFile clubLogo,
        @RequestParam(required = false) String databaseHost,
        @RequestParam(required = false) String databasePort,
        @RequestParam(required = false) String databaseUser,
        @RequestParam(required = false) String databasePassword,
        @RequestParam(required = false) String databaseCollection, @RequestParam Map<String, String> parameters,
        @RequestParam String currentAdminPassword, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Starting to save settings");
    Settings settings = Settings.loadSettings(settingsRepository);
    if (!passwordEncoder.isPasswordValid(currentUser.getPassword(), currentAdminPassword,
            currentUser.getSalt())) {
        logger.warn("[" + currentUser + "] The stated password is invalid");
        return new ResponseEntity<>("The stated password is incorrect, please try again", HttpStatus.FORBIDDEN);
    } else if (currentUser.isAdmin()) {
        if (currentUser.isSuperAdmin()) {
            logger.debug("[" + currentUser + "] The user is a super admin");
            if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) {
                logger.warn("[" + currentUser + "] The super admin user is changing to " + currentAdmin);
                Division rootDivision = divisionRepository.findByName(settings.getClubName());
                if (rootDivision == null) {
                    logger.warn("[" + currentUser + "] Unable to find root division " + settings.getClubName());
                    return new ResponseEntity<>("Unable to find root division",
                            HttpStatus.INTERNAL_SERVER_ERROR);
                }

                User newSuperAdmin = userRepository.findByEmail(currentAdmin);
                if (newSuperAdmin == null) {
                    logger.warn("[" + currentUser + "] Unable to find new super admin " + currentAdmin);
                    return new ResponseEntity<>("Unable to find new super admin",
                            HttpStatus.INTERNAL_SERVER_ERROR);
                }

                logger.debug("[" + currentUser + "] Saving new super admin");
                rootDivision.setAdminUser(newSuperAdmin);
                divisionRepository.save(rootDivision);
                logger.info("[" + currentUser + "] Successfully saved " + currentAdmin + " as new super admin");
            }
            try {
                if (clubName != null && !clubName.isEmpty()) {
                    logger.debug("[" + currentUser + "] Setting club name to " + clubName);
                    Division rootDivision = divisionRepository.findByName(settings.getClubName());
                    if (rootDivision == null) {
                        logger.warn("[" + currentUser + "] Unable to find former root division.");
                        return new ResponseEntity<>("Unable to find former root division",
                                HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                    //Changing and saving the root division
                    rootDivision.setName(clubName);
                    divisionRepository.save(rootDivision);
                    settings.setClubName(clubName);
                }

                if (clubLogo != null && !clubLogo.isEmpty()) {
                    logger.debug("[" + currentUser + "] Saving club logo");
                    try {
                        gridFSRepository.storeClubLogo(clubLogo);
                    } catch (MongoException e) {
                        logger.warn("[" + currentUser + "] Problem while saving club logo: " + e.getMessage());
                        return new ResponseEntity<>("Problem while saving club logo: " + e.getMessage(),
                                HttpStatus.BAD_REQUEST);
                    }
                }

                if (databaseHost != null && !databaseHost.isEmpty()) {
                    logger.debug("[" + currentUser + "] Setting database host to " + databaseHost);
                    settings.setDatabaseHost(databaseHost);
                }

                if (databasePort != null && !databasePort.isEmpty()) {
                    logger.debug("[" + currentUser + "] Setting database port to " + databasePort);
                    settings.setDatabasePort(databasePort);
                }

                if (databaseUser != null) {
                    logger.debug("[" + currentUser + "] Setting database user to " + databaseUser);
                    settings.setDatabaseUser(databaseUser);
                }

                if (databasePassword != null) {
                    logger.debug("[" + currentUser + "] Setting database password");
                    settings.setDatabasePassword(databasePassword);
                }

                if (databaseCollection != null && !databaseCollection.isEmpty()) {
                    logger.debug(
                            "[" + currentUser + "] Setting database collection name " + databaseCollection);
                    settings.setDatabaseName(databaseCollection);
                }

                logger.debug("[" + currentUser + "] Gathering all custom user fields");
                //Reducing parameters to custom user field parameters only and the value of the input
                List<String> reducedValues = parameters.keySet().parallelStream()
                        .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty())
                        .distinct() //Only allowing distinct keys
                        .map(key -> key.substring(4)) //Reducing the key to the initial 'name' value, used to create the fields by jQuery
                        .collect(Collectors.toList());

                //Analysing the values and checking, if
                if (!reducedValues.isEmpty()) {
                    logger.debug("[" + currentUser + "] There are custom user fields available");
                    ArrayList<String> customUserFieldValues = new ArrayList<>();
                    reducedValues.parallelStream().forEach(key -> {
                        if (parameters.get("delete" + key) != null) {
                            logger.warn("[" + currentUser + "] Deleting custom user field " + key);
                            if (parameters.get("deleteContent" + key) != null) {
                                logger.warn("[" + currentUser + "] Deleting content of custom user field " + key
                                        + " on every user object");
                                List<User> user = mongoTemplate.find(
                                        new Query(Criteria.where("customUserField." + key).exists(true)),
                                        User.class);
                                if (user != null && !user.isEmpty()) {
                                    user.parallelStream().forEach(thisUser -> {
                                        thisUser.removeCustomUserField(key);
                                        try {
                                            logger.trace(
                                                    "[" + currentUser + "] Deleting custom user field content "
                                                            + key + " for user " + thisUser.getEmail());
                                            userRepository.save(thisUser);
                                        } catch (ConstraintViolationException e) {
                                            logger.warn("[" + currentUser
                                                    + "] A database constraint was violated while trying to delete the custom user field "
                                                    + key + " for user " + thisUser.getEmail() + ": "
                                                    + e.getMessage());
                                        }
                                    });
                                }
                            }
                        } else {
                            String value = parameters.get("cuf_" + key).trim();
                            if (!key.equals(value) && settings.getCustomUserFields().contains(key)) //The key was renamed
                            {
                                logger.debug("[" + currentUser + "] The custom user field " + key
                                        + " changed to " + value);
                                List<User> user = mongoTemplate.find(
                                        new Query(Criteria.where("customUserField." + key).exists(true)),
                                        User.class);
                                if (user != null && !user.isEmpty()) {
                                    user.parallelStream().forEach(thisUser -> {
                                        thisUser.renameCustomUserField(key, value);
                                        try {
                                            logger.trace("[" + currentUser + "] Renaming custom user field "
                                                    + key + " to " + value + " for user "
                                                    + thisUser.getEmail());
                                            userRepository.save(thisUser);
                                        } catch (ConstraintViolationException e) {
                                            logger.warn("[" + currentUser
                                                    + "] A database constraint was violated while trying to rename the custom user field "
                                                    + key + " for user " + thisUser.getEmail() + ": "
                                                    + e.getMessage());
                                        }
                                    });
                                }
                            }
                            logger.debug("[" + currentUser + "] Adding " + value + " as custom user field");
                            customUserFieldValues.add(value);
                        }
                    });
                    settings.setCustomUserFields(customUserFieldValues);
                }

                logger.debug("[" + currentUser + "] Saving updated settings file");
                settings.saveSettings(currentUser, settingsRepository);
                logger.info("[" + currentUser + "] Successfully saved updated settings file");
            } catch (IOException e) {
                logger.warn("[" + currentUser + "] Unable to update settings file: " + e.getMessage());
                return new ResponseEntity<>("Unable to update settings file", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else {
            logger.debug("[" + currentUser + "] The user is an admin");
            if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) {
                logger.warn("[" + currentUser + "] The current user differs from the stated user");
                return new ResponseEntity<>("The current user differs from the stated user",
                        HttpStatus.BAD_REQUEST);
            }
        }

        if (adminPasswordNew != null && adminPasswordNewRe != null && !adminPasswordNew.isEmpty()
                && !adminPasswordNewRe.isEmpty()) {
            logger.info("[" + currentUser + "] The user wants to change his password.");
            if (!adminPasswordNew.equals(adminPasswordNewRe)) {
                logger.warn("[" + currentUser + "] The stated passwords did not match");
                return new ResponseEntity<>("The stated passwords did not match", HttpStatus.BAD_REQUEST);
            } else {
                currentUser.setPassword(adminPasswordNew);
                try {
                    logger.debug("[" + currentUser + "] Saving new user password.");
                    userRepository.save(currentUser);
                    logger.info("[" + currentUser + "] Successfully saved new user password");
                } catch (ConstraintViolationException e) {
                    logger.warn("[" + currentUser
                            + "] A database constraint was violated while saving the user: " + e.getMessage());
                    return new ResponseEntity<>("A database constraint was violated while saving the user.",
                            HttpStatus.BAD_REQUEST);
                }
            }
        }
    } else {
        logger.warn("[" + currentUser + "] A user who is not an admin tries to change the settings ");
        return new ResponseEntity<>("You are not allowed to change these settings", HttpStatus.FORBIDDEN);
    }
    logger.info("[" + currentUser + "] Successfully updated all settings");
    return new ResponseEntity<>("Successfully updated settings", HttpStatus.OK);
}

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

/**
 * ?Id//ww  w.j  a va2s.  co  m
 *
 * @param userId Id
 * @return Id
 */
private List<String> buildUserSubscribers(String userId) {
    //??
    List<Subscriber> subscribers = subscriberDao.find(Query.query(Criteria.where("toUser").is(userId)));
    List<String> userIds = new ArrayList<>(subscribers.size());
    for (Subscriber subscriber : subscribers) {
        userIds.add(subscriber.getFromUser());
    }

    List<User> users = userDao.find(Query.query(Criteria.where("userId").in(userIds)));
    List<String> emchatNames = new ArrayList<>(users.size());
    for (User user : users) {
        emchatNames.add(user.getEmchatName());
    }
    return emchatNames;
}

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

public void insertServerStatusInfo(ServerStatus serverStatusInfo) {
    try {/*from ww w  .  j a v a  2  s . c om*/
        Query query = new Query(Criteria.where(DEVICECODE).is(serverStatusInfo.getDeviceCode()));

        Update update = new Update();
        ObjectMapper converter = new ObjectMapper();
        Map<String, Object> props = converter.convertValue(serverStatusInfo, Map.class);

        Set<String> keys = props.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            Object value = props.get(key);

            if (value != null)
                update.set(key, value);
        }

        WriteResult wr = operations.updateMulti(query, update, COLL_DASHBOARD, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.cit.tetrad.dao.management.impl.SubDaoImpl.java

public Object getIncludeOptionResult(CommonDto dto) {
    dhtmlxLogger.info("start getIncludeOptionResult");
    String dsname = dto.getDsname();

    Query query = new Query(
            Criteria.where(SERVERSTATUS_REGTIME).gt(dto.getSearch_sdate()).lte(dto.getSearch_edate()));
    query.addCriteria(Criteria.where(COL_DEVICECODE).is(dto.getDeviceCode()));
    if (dto.getCollname().equals(COLL_DBSTATUS))
        query.addCriteria(Criteria.where(DBSTATUS_DBNAME).is(dto.getDbname()));
    query.sort().on(SERVERSTATUS_REGTIME, Order.ASCENDING);
    query.fields().include("_id").include(SERVERSTATUS_REGTIME).include(dsname).include(COL_DEVICECODE);

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

    long start = System.currentTimeMillis();
    List<Object> serverStatusList = monadService.getListWithStrCollName(query, Map.class, dto.getCollname());
    double old = -1;
    for (Object obj : serverStatusList) {
        Map<String, Object> setInfo = new HashMap<String, Object>();
        Map<String, Object> statusInfo = (Map<String, Object>) obj;
        double recent = CriticalHelper.convertToDouble(statusInfo.get(dsname));
        String regtime = (String) statusInfo.get(SERVERSTATUS_REGTIME);
        int deviceCode = (Integer) statusInfo.get(COL_DEVICECODE);
        if (old == -1) {
            setInfo.put(dsname, 0);/* ww  w  .java  2 s.co m*/
        } else {
            setInfo.put(dsname, recent - old);
        }
        setInfo.put(COL_DEVICECODE, deviceCode);
        setInfo.put(SERVERSTATUS_REGTIME, regtime);
        old = recent;
        result.add(setInfo);
    }
    long end = System.currentTimeMillis();
    dhtmlxLogger.info("    getDiff Data : " + (end - start));
    String collname = "temp_" + TimestampUtil.readTimestamp();
    start = System.currentTimeMillis();
    monadService.insert(result, collname);
    end = System.currentTimeMillis();
    dhtmlxLogger.info("    insertDiff Data : " + (end - start));
    dto.setCollname(collname);
    Object obj = getCurrentResult(dto);

    //   
    dhtmlxLogger.info("drop temp collection!");
    monadService.dropCollection(collname);
    dhtmlxLogger.info("end getIncludeOptionResult");
    return obj;
}

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

@Override
public void checkRegisterParameters(User user, JSONObject json) throws ApiException {
    LOG.debug("Begin check input parameters of register");

    Landmark landmark = user.getLandmark();
    if (landmark == null || !user.getLandmark().correct()) {
        LOG.warn("Input parameter landmark error, out of range, landmark:{}", landmark);
        throw new ApiException("?");
    }/*from   w  w  w  . j av  a 2 s.  c om*/

    String phone = json.getString("phone");
    User phoneUser = userDao.findOne(Query.query(Criteria.where("phone").is(phone)));
    if (phoneUser != null) {
        LOG.warn("User phone is already register , phone:{}", phone);
        throw new ApiException("?");
    }

    //????
    if (!StringUtils.isEmpty(user.getAvatar())) {
        user.setAvatar(MessageFormat.format(Constants.PhotoKey.AVATAR_KEY, user.getAvatar()));
        // ?
        if (!localFileManager.isExist(user.getAvatar())) {
            LOG.warn("avatar not exist, avatar{}", user.getAvatar());
            throw new ApiException("?");
        }
    }

    boolean snsRegister = isSnsRegister(json);

    checkPhoneRegister(true, json);

    refreshUserBySnsRegister(user, snsRegister, json);
}

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

public Truck getTruckByUserAndLicensePlate(String username, String licensePlateNumber) {
    Query truckBelongsToUserQuery = new Query()
            .addCriteria(Criteria.where("licensePlateNumber").is(licensePlateNumber))
            .addCriteria(Criteria.where("username").is(username));
    return mongoTemplate.findOne(truckBelongsToUserQuery, Truck.class);
}