List of usage examples for org.springframework.data.mongodb.core.query Update Update
Update
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 w w .j ava 2 s. c o m mongoTemplate.updateFirst(q, update, Load.class); }
From source file:com.bosch.iot.things.example.historian.Collector.java
/** * Write history to the the MongoDB/*from w w w . ja v a 2 s . com*/ */ private void storeHistory(History h) { LOGGER.trace("Store history: {}", h); // do combined update query: add newest value+timestamp to the array property and slice array if too long String id = h.thingId + "/features/" + h.featureId + h.path; Update update = new Update() .push("values", new BasicDBObject("$each", Arrays.asList(getJavaValue(h.value))).append("$slice", -HISTORY_SIZE)) .push("timestamps", new BasicDBObject("$each", Arrays.asList(h.timestamp)).append("$slice", -HISTORY_SIZE)); // update or create document for this specific property in this thing/feature mongoTemplate.upsert(Query.query(Criteria.where("_id").is(id)), update, String.class, "history"); }
From source file:com.enitalk.controllers.bots.EniWordController.java
@RabbitListener(queues = "eniwords") public void consume(Message msg) { try {/* w w w .j av a 2s . c o m*/ JsonNode user = jackson.readTree(msg.getBody()); logger.info("Sending eniword to student {}", user); Integer lastWord = user.at("/eniword/wc").asInt(0) + 1; HashMap word = mongo.findOne(Query.query(Criteria.where("i").gt(lastWord)), HashMap.class, "words"); if (word == null) { return; } ObjectNode wToSend = jackson.convertValue(word, ObjectNode.class); String text = "0x1f4d8 <b>EniWord</b>\n"; text += "0x1f4e2 Word: <b>" + wToSend.path("word").asText() + "</b>\n"; text += "0x1f4cb Part of speech: <b>" + parts.get(wToSend.path("type").asInt()) + "</b>\n"; text += "0x1f6a9 <b>Usage:</b>\n"; JsonNode exs = wToSend.at("/def/examples"); Iterator<JsonNode> els = exs.elements(); int i = 1; while (els.hasNext() && i < 2) { text += i++ + ". " + els.next().path("text").asText() + "\n"; } text += "---------\nWe will send you another awesome word in 40 minutes.\nPress /recommend to get back to the menu and browse teachers."; logger.info("Text to send {}", text); ArrayNode tg = jackson.createArrayNode(); ObjectNode o = tg.addObject(); o.set("dest", user.path("dest")); ObjectNode message = jackson.createObjectNode(); o.set("message", message); message.put("text", text); //make unsubscribe button ArrayNode a = jackson.createArrayNode(); // String buttonUrl = env.getProperty("self.url") + "/eniword/cancel/" + user.at("/dest/sendTo").asLong(); // logger.info("Button url {}", buttonUrl); // makeButtonHref(a, "Stop sending words", buttonUrl); message.set("buttons", a); rate.acquire(); sendMessages(tg); mongo.updateFirst(Query.query(Criteria.where("dest.sendTo").is(user.at("/dest/sendTo").asLong())), new Update().set("eniword.wc", wToSend.path("i").asLong()).inc("eniword.points", -1), "leads"); } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); } }
From source file:quanlyhocvu.api.mongodb.DAO.AuthorityDAO.java
/** * update user by current user//from w ww . j a v a 2s .c o m * @param user */ public void updateUser(UserDTO user) { Query query = Query.query(Criteria.where("username").is(user.getUsername())); Update update = new Update(); update.set("enabled", user.isEnabled()); update.set("nonlocked", user.isNonlocked()); if (user.getRoles().size() > 0) { update.set("roles", user.getRoles()); } if (!"".equals(user.getPassword())) { update.set("password", MD5.getMD5(user.getPassword())); } mongoOperation.findAndModify(query, update, UserDTO.class); }
From source file:com.gongpingjia.carplay.official.service.impl.OfficialApproveServiceImpl.java
/** * ?JSONuserId ??/*from w w w . j a v a2 s. com*/ * * @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:org.ow2.play.metadata.service.MetadataServiceImpl.java
@Override @WebMethod//from w w w .j a v a2 s . c o m public boolean deleteMetaData(Resource resource) throws MetadataException { Update update = new Update(); update.unset("metadata"); mongoTemplate.updateFirst( query(where("resource.name").is(resource.getName()).and("resource.url").is(resource.getUrl())), update, org.ow2.play.metadata.service.document.MetaResource.class); return true; }
From source file:com.enitalk.opentok.CheckAvailabilityRunnable.java
@Override @RabbitListener(queues = "youtube_check") public void onMessage(Message msg) { try {// w ww. j av a2 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: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 w w . j av a 2 s . c o 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()); } }
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); }