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:no.nlf.dal.ParachutistController.java

public Parachutist update(Parachutist parachutist) {
    MongoParachutist mongoParachutist = new MongoParachutist(parachutist);

    Update updateMongoParacutist = new Update();

    Query queryMongoParachutists = new Query(Criteria.where("melwinId").is(mongoParachutist.getMelwinId()));

    updateMongoParacutist.set("memberclubs", mongoParachutist.getMemberclubs());
    updateMongoParacutist.set("licenses", mongoParachutist.getLicenses());
    updateMongoParacutist.set("firstname", mongoParachutist.getFirstname());
    updateMongoParacutist.set("lastname", mongoParachutist.getLastname());
    updateMongoParacutist.set("bithdate", mongoParachutist.getBirthdate());
    updateMongoParacutist.set("street", mongoParachutist.getStreet());
    updateMongoParacutist.set("gender", mongoParachutist.getGender());
    updateMongoParacutist.set("phone", mongoParachutist.getPhone());
    updateMongoParacutist.set("mail", mongoParachutist.getMail());
    updateMongoParacutist.set("postnumber", mongoParachutist.getPostnumber());
    updateMongoParacutist.set("postplace", mongoParachutist.getPostplace());

    mongoParachutist = appContext.mongoOperation().findAndModify(queryMongoParachutists, updateMongoParacutist,
            new FindAndModifyOptions().returnNew(true), MongoParachutist.class);

    if (mongoParachutist != null) {
        return mongoParachutist.toParachutist();
    }/*from ww  w  .  j  a va2 s  . c o m*/

    return new Parachutist();
}

From source file:eu.trentorise.game.managers.DBPlayerManager.java

private StatePersistence persist(String gameId, String playerId, List<GenericObjectPersistence> concepts,
        CustomData customData, Map<String, Object> metadata) {
    if (StringUtils.isBlank(gameId) || StringUtils.isBlank(playerId)) {
        throw new IllegalArgumentException("field gameId and playerId of PlayerState MUST be set");
    }//from w ww .j a v  a  2  s .  c  om

    Criteria criteria = new Criteria();
    criteria = criteria.and("gameId").is(gameId).and("playerId").is(playerId);
    Query query = new Query(criteria);
    Update update = new Update();
    if (concepts != null) {
        update.set("concepts", concepts);
    }
    if (customData != null) {
        update.set("customData", customData);
    }
    if (metadata != null) {
        update.set("metadata", metadata);
    }
    FindAndModifyOptions options = new FindAndModifyOptions();
    options.upsert(true);
    options.returnNew(true);
    return mongoTemplate.findAndModify(query, update, options, StatePersistence.class);
}

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

public void enableViewingLoads(String username) {
    Query query = new Query().addCriteria(Criteria.where("username").is(username));
    Update update = new Update();
    update.set("allowLoadDetails", Boolean.TRUE);
    mongoTemplate.upsert(query, update, LoadsUser.class);
}

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

public void updateTruck(Truck truck) {
    Query findtruckToUpdate = new Query().addCriteria(Criteria.where("_id").is(truck.getId()));
    Update update = new Update();
    update.set("registrationStatus", truck.getRegistrationStatus());
    update.set("type", truck.getType());
    update.set("ownerName", truck.getOwnerName());
    update.set("ownerId", truck.getOwnerId());
    update.set("ownerAddress", truck.getOwnerAddress());
    update.set("maxWeight", truck.getMaxWeight());
    update.set("maxVolume", truck.getMaxVolume());
    update.set("acceptableLoadTypes", truck.getAcceptableLoadTypes());
    update.set("acceptableLiftTypes", truck.getAcceptableLiftTypes());
    mongoTemplate.upsert(findtruckToUpdate, update, Truck.class);
}

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

public void updateLoad(Load load) {
    Query q = new Query();
    q.addCriteria(Criteria.where("_id").is(load.getId()));
    Update update = new Update();
    update.set("source", load.getSource());
    update.set("sourceLocation", load.getSourceLocation());
    update.set("destinationLocation", load.getDestinationLocation());
    update.set("destination", load.getDestination());
    update.set("driveDate", load.getDriveDate());
    update.set("suggestedQuote", load.getSuggestedQuote());
    update.set("weight", load.getWeight());
    update.set("volume", load.getVolume());
    update.set("comments", load.getComments());
    update.set("comments", load.getComments());
    update.set("quantity", load.getQuantity());
    update.set("loadingType", load.getLoadingType());
    update.set("downloadingType", load.getDownloadingType());
    update.set("name", load.getName());
    update.set("waitingTime", load.getWaitingTime());
    if (load.getHasPhoto()) {
        update.set("loadPhoto", load.getLoadPhoto());
        update.set("hasPhoto", load.getHasPhoto());
    }/*  w  ww.java  2 s  .c o m*/
    mongoTemplate.updateFirst(q, update, Load.class);
}

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

@Override
public ResponseDo approveUserPhotoAuthentication(String userId, JSONObject json) throws ApiException {
    String applicationId = json.getString("applicationId");
    AuthApplication application = authApplicationDao.findById(applicationId);
    if (application == null) {
        LOG.warn("authApplication is not exit with applicationId:{}", applicationId);
        throw new ApiException("?");
    }//w  ww .j av  a  2 s .c o m

    String status = getStatus(json.getBoolean("accept"));
    String remarks = getRemarks(json);

    LOG.debug("Begin update data");
    Long current = DateUtil.getTime();
    Update update = new Update();
    update.set("authTime", current);
    update.set("authUserId", userId);
    update.set("status", status);
    if (Constants.AuthStatus.ACCEPT.equals(status)) {
        update.set("remarks", "");
    } else {
        update.set("remarks", remarks);
    }

    authApplicationDao.update(applicationId, update);

    userDao.update(application.getApplyUserId(), Update.update("photoAuthStatus", status));

    recordHistory(userId, application, current, status, remarks);

    sendEmchatMessage(userId, application, status, remarks, Constants.MessageType.PHOTO_AUTH_MSG);

    LOG.debug("Finished approved user photo authentication apply");
    return ResponseDo.buildSuccessResponse();
}

From source file:com.enitalk.opentok.CheckAvailabilityRunnable.java

@Override
@RabbitListener(queues = "youtube_check")
public void onMessage(Message msg) {
    try {//from   w  w  w  .  jav a 2 s  .  co  m
        JsonNode event = jackson.readTree(msg.getBody());
        String ii = event.path("ii").asText();
        logger.info("Check youtube came {}", ii);

        List<String> videos = jackson.convertValue(event.path("yt"), List.class);
        List<String> parts = new ArrayList<>();
        videos.stream().forEach((String link) -> {
            parts.add(StringUtils.substringAfterLast(link, "/"));
        });

        Credential credential = flow.loadCredential("yt");
        YouTube youtube = new YouTube.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
                credential).setApplicationName("enitalk").build();
        boolean refreshed = credential.refreshToken();
        logger.info("Yt refreshed {}", refreshed);

        HttpResponse rs = youtube.videos().list("processingDetails").setId(StringUtils.join(parts, ','))
                .executeUnparsed();
        InputStream is = rs.getContent();
        byte[] b = IOUtils.toByteArray(is);
        IOUtils.closeQuietly(is);

        JsonNode listTree = jackson.readTree(b);
        logger.info("List tree {}", listTree);

        List<JsonNode> items = listTree.path("items").findParents("id");
        long finished = items.stream().filter((JsonNode j) -> {
            return j.at("/processingDetails/processingStatus").asText().equals("succeeded");
        }).count();

        Query q = Query.query(Criteria.where("ii").is(ii));
        if (finished == parts.size()) {
            logger.info("Processing finished {}", ii);

            //send notification and email
            ObjectNode tree = (ObjectNode) jackson
                    .readTree(new ClassPathResource("emails/videoUploaded.json").getInputStream());
            tree.put("To", event.at("/student/email").asText());
            //                String text = tree.path("HtmlBody").asText() + StringUtils.join(videos, "\n");

            StringWriter writer = new StringWriter(29 * 1024);
            Template t = engine.getTemplate("video.html");
            VelocityContext context = new VelocityContext();
            context.put("video", videos.iterator().next());
            t.merge(context, writer);

            tree.put("HtmlBody", writer.toString());

            //make chat and attach it
            String chatTxt = makeChat(event);
            if (StringUtils.isNotBlank(chatTxt)) {
                ArrayNode attachments = jackson.createArrayNode();
                ObjectNode a = attachments.addObject();
                a.put("Name", "chat.txt");
                a.put("ContentType", "text/plain");
                a.put("Content", chatTxt.getBytes("UTF-8"));

                tree.set("Attachments", attachments);
            } else {
                logger.info("No chat available for {}", event.path("ii").asText());
            }

            logger.info("Sending video and chat {} to student", ii);

            org.apache.http.HttpResponse response = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r = EntityUtils.toByteArray(response.getEntity());
            JsonNode emailResp = jackson.readTree(r);

            Update u = new Update().set("video", 4);
            if (StringUtils.isNotBlank(chatTxt)) {
                u.set("chat", chatTxt);
            }

            u.set("student.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("student.uploader.rs", jackson.convertValue(emailResp, HashMap.class));

            tree.put("To", event.at("/teacher/email").asText());
            logger.info("Sending video and chat {} to teacher", ii);

            org.apache.http.HttpResponse response2 = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r2 = EntityUtils.toByteArray(response2.getEntity());
            JsonNode emailResp2 = jackson.readTree(r2);

            u.set("teacher.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("teacher.uploader.rs", jackson.convertValue(emailResp2, HashMap.class));
            u.set("f", 1);

            mongo.updateFirst(q, u, "events");

            //                JsonNode dest = event.at("/student/dest");
            //
            //                ArrayNode msgs = jackson.createArrayNode();
            //                ObjectNode o = msgs.addObject();
            //                o.set("dest", dest);
            //                ObjectNode m = jackson.createObjectNode();
            //                o.set("message", m);
            //                m.put("text", "0x1f3a5 We have uploaded your lesson to Youtube. It is available to you and the teacher only. \n"
            //                        + "Please, do not share it with anyone\n Also, we sent the video link and the text chat to your email.");
            //
            //                ArrayNode buttons = jackson.createArrayNode();
            //                m.set("buttons", buttons);
            //                m.put("buttonsPerRow", 1);
            //
            //                if (videos.size() == 1) {
            //                    botController.makeButtonHref(buttons, "Watch on Youtube", videos.get(0));
            //                } else {
            //                    AtomicInteger cc = new AtomicInteger(1);
            //                    videos.stream().forEach((String y) -> {
            //                        botController.makeButtonHref(buttons, "Watch on Youtube, part " + cc.getAndIncrement(), y);
            //                    });
            //                }
            //
            //                botController.sendMessages(msgs);
            //
            //                sendFeedback(dest, event);

        } else {
            logger.info("{} parts only finished for {}", finished, ii);
            mongo.updateFirst(q,
                    new Update().inc("check", 1).set("checkDate", new DateTime().plusMinutes(12).toDate()),
                    "events");
        }

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

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

public void default_log_retention_period_update() {
    Query query = new Query();
    Update update = new Update();
    String[] essentialGlobalVariable = Config.getConfig("essentialGlobalVariable").split(";");
    query = setUid(essentialGlobalVariable[0]);
    update.set("value", RrdUtil.readLogRetentionPeriod());
    monadService.update(query, update, Global.class);
}

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

@Override
public ResponseDo approveUserDrivingAuthentication(String userId, JSONObject json) throws ApiException {
    LOG.debug("approveUserAuthentication start");

    String applicationId = json.getString("applicationId");
    AuthApplication application = authApplicationDao.findById(applicationId);
    if (application == null) {
        LOG.warn("Approved auth application is not exist, applicationId:{}", applicationId);
        throw new ApiException("?");
    }//w  w w  .  j  a  v a  2s.  c o m

    String status = getStatus(json.getBoolean("accept"));
    String remarks = getRemarks(json);

    Long current = DateUtil.getTime();
    Update update = Update.update("authUserId", userId).set("authTime", current);
    if (Constants.AuthStatus.ACCEPT.equals(status)) {
        update.set("remarks", "");
    } else {
        update.set("remarks", remarks);
    }
    update.set("status", status);

    updateUserAuthenticationInfo(json, application.getApplyUserId());

    authApplicationDao.update(applicationId, update);

    userDao.update(application.getApplyUserId(), Update.update("licenseAuthStatus", status));

    recordHistory(userId, application, current, status, remarks);
    sendEmchatMessage(userId, application, status, remarks, Constants.MessageType.LICENSE_AUTH_MSG);

    LOG.debug("Finished approved user driving authentication apply");
    return ResponseDo.buildSuccessResponse();
}

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

public void updateServerStatusInfo(int deviceCode) {
    try {/*from  www  .  ja  v  a  2s. 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();
    }
}