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.tlantic.integration.authentication.service.security.TokenStoreService.java

@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    String authenticationId = authenticationKeyGenerator.extractKey(authentication);
    if (null == authenticationId) {
        return null;
    }//  w  w w.ja va  2  s  .c  o m
    Query query = new Query();
    query.addCriteria(Criteria.where("authenticationId").is(authenticationId));
    OAuth2AuthenticationAccessToken token = mongoTemplate.findOne(query, OAuth2AuthenticationAccessToken.class,
            "oauth2_access_token");
    return token == null ? null : token.getoAuth2AccessToken();
}

From source file:things.mongo.MongoConnector.java

@Override
public Observable<? extends Thing<?>> getChildrenForId(String id) {

    Query q = new Query();

    q.addCriteria(Criteria.where("parents").is(id));

    List<Thing> result = mongoTemplate.find(q, Thing.class);
    return Observable.from(result).map(t -> (Thing<?>) t);
}

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

@Override
@RabbitListener(queues = "youtube_check")
public void onMessage(Message msg) {
    try {//from w  w w .j  av  a 2 s. c  om
        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.enitalk.controllers.OpentokSessionController.java

public void enter(@RequestBody ObjectNode json) throws IOException {
    try {//  w  w  w . ja  va 2  s.c o m
        logger.info("Joined video session {}", json);
        String ev = json.path("i").asText();
        String dest = json.path("dest").asText();

        HashMap<String, Object> jev = new HashMap<>();
        jev.put("time", new Date());
        jev.put("dest", dest);

        mongo.updateFirst(Query.query(Criteria.where("ii").is(ev)), new Update().push("joins", jev), "events");
    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

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

@SuppressWarnings("unchecked")
@RequestMapping(value = "/api/child/{ownerId}/{instituteId}/{schoolId}/classroom", method = RequestMethod.GET)
public @ResponseBody List<Child> searchChildByClassroom(@PathVariable String ownerId,
        @PathVariable String instituteId, @PathVariable String schoolId, @RequestParam String classRoom,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (!validateAuthorization(ownerId, instituteId, schoolId, null, null, Const.AUTH_RES_Child,
            Const.AUTH_ACTION_READ, request)) {
        throw new UnauthorizedException("Unauthorized Exception: token not valid");
    }/*from   w  ww  .j  av a2 s . co m*/
    Criteria criteria = Criteria.where("instituteId").is(instituteId).and("schoolId").is(schoolId)
            .and("classRoom").is(classRoom);
    List<Child> result = (List<Child>) storage.findData(Child.class, criteria, null, ownerId);
    if (logger.isInfoEnabled()) {
        logger.info(String.format("searchChildByClassroom[%s]:%d", ownerId, result.size()));
    }
    return result;
}

From source file:quanlyhocvu.api.mongodb.DAO.AuthorityDAO.java

/**
 * remove user by id//w w w.  ja  va2 s.  c o m
 *
 * @param userIds
 */
public void removeUserByUserId(String... userIds) {
    for (String id : userIds) {
        mongoOperation.remove(Query.query(Criteria.where("userId").is(userIds)), UserDTO.class);
    }
}

From source file:com.sangupta.dryrun.mongo.DryRunGridFSTemplate.java

@Override
public GridFsResource[] getResources(String filenamePattern) {
    if (AssertUtils.isEmpty(filenamePattern)) {
        return new GridFsResource[0];
    }/*from   www  .  j  a  v a  2s. co  m*/

    DryRunAntPath path = new DryRunAntPath(filenamePattern);

    if (path.isPattern()) {
        Query query = Query.query(Criteria.where("filename").regex(path.toRegex()));
        List<GridFSDBFile> files = this.findObjects(query.getQueryObject(), -1);
        List<GridFsResource> resources = new ArrayList<GridFsResource>(files.size());

        for (GridFSDBFile file : files) {
            resources.add(new GridFsResource(file));
        }

        return resources.toArray(new GridFsResource[resources.size()]);
    }

    return new GridFsResource[] { getResource(filenamePattern) };
}

From source file:com.epam.ta.reportportal.core.admin.ServerAdminHandlerImpl.java

public OperationCompletionRS deleteEmailSettings(String profileId) {
    WriteResult result = mongoOperations.updateFirst(query(Criteria.where("_id").is(profileId)),
            Update.update("serverEmailDetails", null), ServerSettings.class);
    BusinessRule.expect(result.getN(), not(equalTo(0))).verify(ErrorType.SERVER_SETTINGS_NOT_FOUND, profileId);

    return new OperationCompletionRS(
            "Server Settings with profile '" + profileId + "' is successfully updated.");
}

From source file:no.nlf.dal.ParachutistController.java

public Parachutist delete(int id) {
    searchPerson = new Query(Criteria.where("id").is(id));
    mongoParachutist = appContext.mongoOperation().findOne(searchPerson, MongoParachutist.class);
    appContext.mongoOperation().remove(mongoParachutist);

    return mongoParachutist.toParachutist();
}

From source file:org.craftercms.commerce.server.mongo.AbstractMongoCRUDService.java

public ServiceResponse<T> deleteAll() throws CrafterCommerceException {
    try {//  w w w.  j a  v a2s  .  c o  m
        Query query = new Query(Criteria.where("_class").is(getTypeArgument().getName()));
        mongoTemplate.remove(query, getTypeArgument().getName());
        return new ServiceResponse<T>(getTypeArgument(), true,
                ReturnMessageProvider.deleteAllMessage(getTypeArgument()));
    } catch (Exception e) {
        return new ServiceResponse<T>(getTypeArgument(), false, e.getMessage());
    }
}