Example usage for org.springframework.data.mongodb.core.query Update set

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

Introduction

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

Prototype

public Update set(String key, Object value) 

Source Link

Document

Update using the $set update modifier

Usage

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogService.java

@Override
public ShsMessageEntry loadEntryAndLockForFetching(String shsTo, String txId) {

    Query query = new Query(Criteria.where("label.txId").is(txId).and("state").is(MessageState.RECEIVED)
            .and("archived").in(false, null).and("label.to.value").is(shsTo));

    Update update = new Update();
    update.set("stateTimeStamp", new Date());
    update.set("state", MessageState.FETCHING_IN_PROGRESS);

    // Enforces that the found object is returned by findAndModify(), i.e. not the original input object
    // It returns null if no document could be updated
    FindAndModifyOptions options = new FindAndModifyOptions().returnNew(true);

    ShsMessageEntry entry = mongoTemplate.findAndModify(query, update, options, ShsMessageEntry.class);

    if (entry == null) {
        throw new MessageNotFoundException("Message entry not found in message log: " + txId);
    }/* www  .  j ava  2  s. c o m*/

    return entry;
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogService.java

@Override
public int archiveMessages(long messageAgeInSeconds) {

    //check the timestamp for old messages
    Date dateTime = new Date(System.currentTimeMillis() - messageAgeInSeconds * 1000);

    //criteria for automatic archiving
    Query query = new Query();
    query.addCriteria(Criteria.where("arrivalTimeStamp").lt(dateTime).and("archived").in(false, null)
            .orOperator(Criteria.where("state").in("NEW", "SENT", "FETCHED", "QUARANTINED"),
                    Criteria.where("label.transferType").is("SYNCH")));

    //update the archived flag and stateTimestamp value
    Update update = new Update();

    update.set("stateTimeStamp", new Date());
    update.set("archived", true);

    //update all matches in the mongodb
    WriteResult wr = mongoTemplate.updateMulti(query, update, ShsMessageEntry.class);

    log.debug("Archived {} messages modified before {}", wr.getN(), dateTime);
    return wr.getN();
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogService.java

@Override
public int releaseStaleFetchingInProgress() {
    // Anything older than one hour
    Date dateTime = new Date(System.currentTimeMillis() - 3600 * 1000);

    // List all FETCHING_IN_PROGRESS messages
    Query queryList = Query.query(
            Criteria.where("state").is(MessageState.FETCHING_IN_PROGRESS).and("stateTimeStamp").lt(dateTime));
    List<ShsMessageEntry> list = mongoTemplate.find(queryList, ShsMessageEntry.class);

    for (ShsMessageEntry item : list) {

        // Double check that it is still FETCHING_IN_PROGRESS
        Query queryItem = new Query(Criteria.where("label.txId").is(item.getLabel().getTxId()).and("state")
                .is(MessageState.FETCHING_IN_PROGRESS).and("stateTimeStamp").lt(dateTime));

        Update update = new Update();
        update.set("stateTimeStamp", new Date());
        update.set("state", MessageState.RECEIVED);

        // Enforces that the found object is returned by findAndModify(), i.e. not the original input object
        // It returns null if no document could be updated
        FindAndModifyOptions options = new FindAndModifyOptions().returnNew(true);

        ShsMessageEntry entry = mongoTemplate.findAndModify(queryItem, update, options, ShsMessageEntry.class);

        if (entry != null) {
            log.info("ShsMessageEntry with state FETCHING_IN_PROGRESS moved back to RECEIVED [txId: "
                    + entry.getLabel().getTxId() + "]");
        }/*from w  w w .j  av a  2  s  .co  m*/
    }

    return list.size();
}

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

/**
 * ?JSONuserId ??//from   www . java  2s. c  o m
 *
 * @param json
 * @param userId
 */
private void updateUserAuthenticationInfo(JSONObject json, String userId) {
    UserAuthentication userAuthentication = userAuthenticationDao.findById(userId);
    if (userAuthentication == null) {
        LOG.warn("User authentication is not exist with userId:{}", userId);
        return;
    }
    Update update = new Update();
    if (!StringUtils.isEmpty(json.getString("driver"))) {
        DriverLicense driver = (DriverLicense) JSONObject.toBean(json.getJSONObject("driver"),
                DriverLicense.class);
        update.set("driver", driver);
        //            userAuthentication.setDriver(driver);
    }

    if (!StringUtils.isEmpty(json.getString("license"))) {
        DrivingLicense license = (DrivingLicense) JSONObject.toBean(json.getJSONObject("license"),
                DrivingLicense.class);
        //            userAuthentication.setLicense(license);
        update.set("license", license);
    }

    userAuthenticationDao.update(userAuthentication.getUserId(), update);
}

From source file:com.enitalk.controllers.youtube.processor.Y2BeProcessor.java

public void run() {
    try {//from  w w w .j  av a  2  s . co  m
        logger.info("Running processor");

        //TO-DO make it work only for 30+ minutes after the 
        Query q = Query.query(Criteria.where("").is(""));
        List<HashMap> items = mongo.find(q, HashMap.class, "events");
        ArrayNode its = jackson.convertValue(items, ArrayNode.class);

        final List<JsonNode> allEvents = its.findParents("ii");

        allEvents.forEach((JsonNode el) -> {
            try {

                List<String> ids = jackson.convertValue(el.path("liveId"), List.class);
                Credential credential = flow.loadCredential(el.at("/teacher/dest/sendTo").toString());
                YouTube youtube = new YouTube.Builder(new NetHttpTransport(),
                        JacksonFactory.getDefaultInstance(), credential).setApplicationName("enitalk").build();
                boolean refreshed = credential.refreshToken();
                logger.info("Token refreshed {} id {}", refreshed);

                YouTube.Videos.List list = youtube.videos()
                        .list("id,liveStreamingDetails,recordingDetails,status,statistics");
                list.setId(StringUtils.join(ids, ','));
                logger.info("Video param query {}", list.buildHttpRequestUrl());

                byte[] response = IOUtils.toByteArray(list.executeUnparsed().getContent());

                JsonNode r = jackson.readTree(response);
                logger.info("Yt response {}", r);
                Update u = new Update().set("records", jackson.convertValue(r, HashMap.class));

                long finishedItems = r.path("items").findParents("id").stream().filter((JsonNode yt) -> {
                    return yt.at("/status/uploadStatus").asText().equals("processed");
                }).count();

                logger.info("Finished items {}", finishedItems);

                if (finishedItems == ids.size()) {
                    logger.info("All items finished, shall sent links to user");

                } else {
                    u.set("nextCheck", new DateTime(DateTimeZone.UTC).plusMinutes(15).toDate());
                }

                mongo.updateFirst(Query.query(Criteria.where("ii").is(el.path("ii").asText())), u, "events");

            } catch (Exception e) {
                logger.error(ExceptionUtils.getFullStackTrace(e));
            }

        });

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

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

@Override
public void partialUpdate(T t) {
    ID id = getEntityInformation().getId(t);
    if (null == id) {
        throw new IllegalArgumentException("ID property should not be null");
    }/*  ww w. ja  v a2s  .  c om*/

    Update update = new Update();
    final MongoPersistentEntity<?> persistentEntity = mongoOperations.getConverter().getMappingContext()
            .getPersistentEntity(getEntityInformation().getJavaType());
    persistentEntity.doWithProperties((PropertyHandler<MongoPersistentProperty>) persistentProperty -> {
        if (!persistentEntity.isIdProperty(persistentProperty)) {
            Object value = Accessible.on(t).field(persistentProperty.getField()).getValue();
            if (null != value) {
                update.set(persistentProperty.getFieldName(), value);
            }
        }
    });

    WriteResult writeResult = mongoOperations.updateFirst(
            query(where(persistentEntity.getIdProperty().getFieldName()).is(id)), update,
            getEntityInformation().getCollectionName());
    if (1 != writeResult.getN()) {
        throw new IncorrectResultSizeDataAccessException(1, writeResult.getN());
    }
}

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

public void insertServerStatusInfo(ServerStatus serverStatusInfo) {
    try {/*from w  w  w .  j ava 2s  . c o m*/
        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:org.starfishrespect.myconsumption.server.business.repositories.repositoriesimpl.ValuesRepositoryImpl.java

@Override
public void insertOrUpdate(SensorDataset value) throws DaoException {
    Update update = new Update();
    Query existingQuery = new Query(new Criteria("timestamp").is(value.getTimestamp()));

    if (mongoOperation.exists(existingQuery, SensorDataset.class, collectionName)) {
        TreeMap<Integer, MinuteValues> minuteValues = value.getValues();
        for (Integer minuteTs : minuteValues.keySet()) {
            Query existingMinute = new Query(
                    new Criteria().andOperator(Criteria.where("timestamp").is(value.getTimestamp()),
                            Criteria.where("values." + minuteTs)));
            MinuteValues minute;//from w  w  w  .j av a2  s  .co  m
            if (mongoOperation.exists(existingMinute, MinuteValues.class, collectionName)) {
                minute = mongoOperation.findOne(existingMinute, MinuteValues.class, collectionName);
                minute.merge(minuteValues.get(minuteTs));
            } else {
                minute = minuteValues.get(minuteTs);
            }
            update.set("values." + minuteTs, minute);
        }
        mongoOperation.updateFirst(existingQuery, update, collectionName);
    } else {
        mongoOperation.save(value, collectionName);
    }
}

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

private void saveUserActivity(String userId, Activity activity, Long current) {
    Activity oldActivity = activityDao.findOne(Query
            .query(Criteria.where("userId").is(userId).and("deleteFlag").is(false).and("majorType")
                    .is(activity.getMajorType()).and("type").is(activity.getType()))
            .with(new Sort(new Sort.Order(Sort.Direction.DESC, "createTime"))));

    if (oldActivity == null) {
        LOG.debug("Old activity is not exist, create a new");
        //??/*from   w ww .  ja  v  a  2  s. co  m*/
        activity.setActivityId(null);
        //ID
        activity.setUserId(userId);
        List<String> memberIds = new ArrayList<String>(1);
        //?
        memberIds.add(userId);
        activity.setMembers(memberIds);
        activity.setCreateTime(current);
        activity.setDeleteFlag(false);

        activityDao.save(activity);
    } else {
        LOG.debug("Old activity is exist, update activity info, activityId:{}", activity.getActivityId());
        //??
        Update update = new Update();
        update.set("pay", activity.getPay());
        update.set("destPoint", activity.getDestPoint());
        update.set("destination", activity.getDestination());
        update.set("estabPoint", activity.getEstabPoint());
        update.set("establish", activity.getEstablish());
        update.set("transfer", activity.isTransfer());
        update.set("createTime", current);
        update.set("applyIds", new ArrayList<>(0));
        update.set("cover", activity.getCover());
        activityDao.update(Query.query(Criteria.where("activityId").is(oldActivity.getActivityId())), update);

        activity.setActivityId(oldActivity.getActivityId());
    }
}