Example usage for io.vertx.core.json JsonObject put

List of usage examples for io.vertx.core.json JsonObject put

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject put.

Prototype

public JsonObject put(String key, Object value) 

Source Link

Document

Put an Object into the JSON object with the specified key.

Usage

From source file:org.entcore.auth.users.DefaultUserAuthAccount.java

License:Open Source License

@Override
public void findByLogin(final String login, final String resetCode, boolean checkFederatedLogin,
        final Handler<Either<String, JsonObject>> handler) {
    boolean setResetCode = resetCode != null && !resetCode.trim().isEmpty();

    String basicQuery = "MATCH (n:User) " + "WHERE (n.login={login} OR n.loginAlias={login}) "
            + "AND n.activationCode IS NULL "
            + (checkFederatedLogin ? "AND (NOT(HAS(n.federated)) OR n.federated = false) " : "")
            + (setResetCode ? "SET n.resetCode = {resetCode}, n.resetDate = {today} " : "")
            + "RETURN n.email as email, n.mobile as mobile";

    final String teacherQuery = "MATCH (n:User)-[:IN]->(sg:ProfileGroup)-[:DEPENDS]->(m:Class)"
            + "<-[:DEPENDS]-(tg:ProfileGroup)<-[:IN]-(p:User), "
            + "sg-[:DEPENDS]->(psg:ProfileGroup)-[:HAS_PROFILE]->(sp:Profile {name:'Student'}), "
            + "tg-[:DEPENDS]->(ptg:ProfileGroup)-[:HAS_PROFILE]->(tp:Profile {name:'Teacher'}) "
            + "WHERE (n.login={login} OR n.loginAlias={login}) AND NOT(p.email IS NULL) AND n.activationCode IS NULL AND "
            + "(NOT(HAS(n.federated)) OR n.federated = false) "
            + (setResetCode ? "SET n.resetCode = {resetCode}, n.resetDate = {today} " : "")
            + "RETURN p.email as email";

    final JsonObject params = new JsonObject().put("login", login);
    if (setResetCode)
        params.put("resetCode", resetCode).put("today", new Date().getTime());

    neo.execute(basicQuery, params,//from  w w w . j a  v a  2  s .c om
            Neo4jResult.validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                public void handle(Either<String, JsonObject> result) {
                    if (result.isLeft()) {
                        handler.handle(result);
                        return;
                    }

                    final String mail = result.right().getValue().getString("email");
                    final String mobile = result.right().getValue().getString("mobile");

                    if (mail != null && config.getBoolean("teacherForgotPasswordEmail", false)) {
                        neo.execute(teacherQuery, params,
                                Neo4jResult.validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                                    public void handle(Either<String, JsonObject> resultTeacher) {
                                        if (resultTeacher.isLeft()) {
                                            handler.handle(resultTeacher);
                                            return;
                                        }

                                        resultTeacher.right().getValue().put("mobile", mobile);
                                        handler.handle(resultTeacher);
                                    }
                                }));
                    }
                    handler.handle(result);
                }
            }));
}

From source file:org.entcore.blog.controllers.BlogController.java

License:Open Source License

@Get("/counter/:blogId")
@SecuredAction(value = "blog.posts.counter", type = ActionType.AUTHENTICATED)
public void postCounter(final HttpServerRequest request) {
    final String blogId = request.params().get("blogId");
    if (StringUtils.isEmpty(blogId)) {
        badRequest(request);//from  w w w  .j  av  a  2s. c om
        return;
    }

    getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override
        public void handle(final UserInfos user) {
            if (user != null) {
                postService.counter(blogId, user, new Handler<Either<String, JsonArray>>() {
                    public void handle(Either<String, JsonArray> event) {
                        if (event.isLeft()) {
                            arrayResponseHandler(request).handle(event);
                            ;
                            return;
                        }

                        final JsonArray blogs = event.right().getValue();

                        int countPublished = 0;
                        int countDraft = 0;
                        int countSubmitted = 0;
                        int countAll = 0;

                        final JsonObject result = new JsonObject();

                        for (Object blogObj : blogs) {
                            final String blogState = ((JsonObject) blogObj).getString("state");
                            if (PostService.StateType.DRAFT.name().equals(blogState)) {
                                countDraft++;
                            } else if (PostService.StateType.PUBLISHED.name().equals(blogState)) {
                                countPublished++;
                            } else if (PostService.StateType.SUBMITTED.name().equals(blogState)) {
                                countSubmitted++;
                            }
                        }

                        countAll = countDraft + countPublished + countSubmitted;

                        result.put("countPublished", countPublished);
                        result.put("countDraft", countDraft);
                        result.put("countSubmitted", countSubmitted);
                        result.put("countAll", countAll);

                        Renders.renderJson(request, result);
                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.blog.controllers.BlogController.java

License:Open Source License

@Get("/list/all")
@SecuredAction("blog.list")
public void list(final HttpServerRequest request) {
    getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override/*from w w  w .j  ava 2s .c  o m*/
        public void handle(final UserInfos user) {
            if (user != null) {
                final Integer page;

                try {
                    page = (request.params().get("page") != null)
                            ? Integer.parseInt(request.params().get("page"))
                            : null;
                } catch (NumberFormatException e) {
                    badRequest(request, e.getMessage());
                    return;
                }

                final String search = request.params().get("search");

                blog.list(user, page, search, new Handler<Either<String, JsonArray>>() {
                    public void handle(Either<String, JsonArray> event) {
                        if (event.isLeft()) {
                            arrayResponseHandler(request).handle(event);
                            ;
                            return;
                        }

                        final JsonArray blogs = event.right().getValue();

                        if (blogs.size() < 1) {
                            renderJson(request, new JsonArray());
                            return;
                        }

                        final AtomicInteger countdown = new AtomicInteger(blogs.size());
                        final Handler<Void> finalHandler = new Handler<Void>() {
                            public void handle(Void v) {
                                if (countdown.decrementAndGet() <= 0) {
                                    renderJson(request, blogs);
                                }
                            }
                        };

                        for (Object blogObj : blogs) {
                            final JsonObject blog = (JsonObject) blogObj;

                            postService.list(blog.getString("_id"), PostService.StateType.PUBLISHED, user, null,
                                    2, null, new Handler<Either<String, JsonArray>>() {
                                        public void handle(Either<String, JsonArray> event) {
                                            if (event.isRight()) {
                                                blog.put("fetchPosts", event.right().getValue());
                                            }
                                            finalHandler.handle(null);
                                        }
                                    });
                        }

                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.blog.controllers.BlogController.java

License:Open Source License

@Get("/linker")
public void listBlogsIds(final HttpServerRequest request) {
    getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override//from w  w w. ja  v  a 2 s.c  o  m
        public void handle(final UserInfos user) {
            if (user != null) {
                blog.list(user, null, null, new Handler<Either<String, JsonArray>>() {
                    public void handle(Either<String, JsonArray> event) {
                        if (event.isLeft()) {
                            arrayResponseHandler(request).handle(event);
                            return;
                        }

                        final JsonArray blogs = event.right().getValue();

                        if (blogs.size() < 1) {
                            renderJson(request, new JsonArray());
                            return;
                        }

                        final AtomicInteger countdown = new AtomicInteger(blogs.size());
                        final Handler<Void> finalHandler = new Handler<Void>() {
                            public void handle(Void v) {
                                if (countdown.decrementAndGet() <= 0) {
                                    renderJson(request, blogs);
                                }
                            }
                        };

                        for (Object blogObj : blogs) {
                            final JsonObject blog = (JsonObject) blogObj;

                            postService.list(blog.getString("_id"), PostService.StateType.PUBLISHED, user, null,
                                    0, null, new Handler<Either<String, JsonArray>>() {
                                        public void handle(Either<String, JsonArray> event) {
                                            if (event.isRight()) {
                                                blog.put("fetchPosts", event.right().getValue());
                                            }
                                            finalHandler.handle(null);
                                        }
                                    });
                        }

                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.blog.events.BlogSearchingEvents.java

License:Open Source License

@Override
public void searchResource(List<String> appFilters, String userId, JsonArray groupIds,
        final JsonArray searchWords, final Integer page, final Integer limit, final JsonArray columnsHeader,
        final String locale, final Handler<Either<String, JsonArray>> handler) {
    if (appFilters.contains(BlogSearchingEvents.class.getSimpleName())) {

        final List<String> groupIdsLst = groupIds.getList();
        final List<DBObject> groups = new ArrayList<DBObject>();
        groups.add(QueryBuilder.start("userId").is(userId).get());
        for (String gpId : groupIdsLst) {
            groups.add(QueryBuilder.start("groupId").is(gpId).get());
        }// ww w .  j ava  2  s  .  c  om

        final QueryBuilder rightsQuery = new QueryBuilder().or(
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("author.userId").is(userId).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());

        final JsonObject projection = new JsonObject();
        projection.put("_id", 1);
        //search all blogs of user
        mongo.find(Blog.BLOGS_COLLECTION, MongoQueryBuilder.build(rightsQuery), null, projection,
                new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        final Either<String, JsonArray> ei = validResults(event);
                        if (ei.isRight()) {
                            final JsonArray blogsResult = ei.right().getValue();

                            final Set<String> setIds = new HashSet<String>();
                            for (int i = 0; i < blogsResult.size(); i++) {
                                final JsonObject j = blogsResult.getJsonObject(i);
                                setIds.add(j.getString("_id"));
                            }

                            //search posts for the blogs found
                            searchPosts(page, limit, searchWords.getList(), setIds,
                                    new Handler<Either<String, JsonArray>>() {
                                        @Override
                                        public void handle(Either<String, JsonArray> event) {
                                            if (event.isRight()) {
                                                if (log.isDebugEnabled()) {
                                                    log.debug(
                                                            "[BlogSearchingEvents][searchResource] The resources searched by user are found");
                                                }
                                                final JsonArray res = formatSearchResult(
                                                        event.right().getValue(), columnsHeader,
                                                        searchWords.getList());
                                                handler.handle(new Right<String, JsonArray>(res));
                                            } else {
                                                handler.handle(new Either.Left<String, JsonArray>(
                                                        event.left().getValue()));
                                            }
                                        }
                                    });
                        } else {
                            handler.handle(new Either.Left<String, JsonArray>(ei.left().getValue()));
                        }
                    }
                });
    } else {
        handler.handle(new Right<String, JsonArray>(new JsonArray()));
    }
}

From source file:org.entcore.blog.events.BlogSearchingEvents.java

License:Open Source License

private void searchPosts(int page, int limit, List<String> searchWords, final Set<String> setIds,
        Handler<Either<String, JsonArray>> handler) {
    final int skip = (0 == page) ? -1 : page * limit;

    final QueryBuilder worldsQuery = new QueryBuilder();
    worldsQuery.text(MongoDbSearchService.textSearchedComposition(searchWords));

    final QueryBuilder blogQuery = new QueryBuilder().start("blog.$id").in(setIds);
    final QueryBuilder publishedQuery = new QueryBuilder().start("state").is(PUBLISHED_STATE);

    final QueryBuilder query = new QueryBuilder().and(worldsQuery.get(), blogQuery.get(), publishedQuery.get());

    JsonObject sort = new JsonObject().put("modified", -1);
    final JsonObject projection = new JsonObject();
    projection.put("title", 1);
    projection.put("content", 1);
    projection.put("blog.$id", 1);
    projection.put("modified", 1);
    projection.put("author.userId", 1);
    projection.put("author.username", 1);

    mongo.find(Blog.POSTS_COLLECTION, MongoQueryBuilder.build(query), sort, projection, skip, limit,
            Integer.MAX_VALUE, validResultsHandler(handler));
}

From source file:org.entcore.blog.events.BlogSearchingEvents.java

License:Open Source License

private JsonArray formatSearchResult(final JsonArray results, final JsonArray columnsHeader,
        final List<String> words) {
    final List<String> aHeader = columnsHeader.getList();
    final JsonArray traity = new JsonArray();

    for (int i = 0; i < results.size(); i++) {
        final JsonObject j = results.getJsonObject(i);
        final JsonObject jr = new JsonObject();
        if (j != null) {
            final String blogId = j.getJsonObject("blog").getString("$id");
            jr.put(aHeader.get(0), j.getString("title"));
            jr.put(aHeader.get(1), j.getString("content", ""));
            jr.put(aHeader.get(2), j.getJsonObject("modified"));
            jr.put(aHeader.get(3), j.getJsonObject("author").getString("username"));
            jr.put(aHeader.get(4), j.getJsonObject("author").getString("userId"));
            jr.put(aHeader.get(5), "/blog#/view/" + blogId + "/" + j.getString("_id"));
            traity.add(jr);/*from ww  w.ja v  a 2  s  .  c o m*/
        }
    }
    return traity;
}

From source file:org.entcore.blog.services.impl.DefaultBlogService.java

License:Open Source License

@Override
public void create(JsonObject blog, UserInfos author, final Handler<Either<String, JsonObject>> result) {
    CommentType commentType = Utils.stringToEnum(blog.getString("comment-type", "").toUpperCase(),
            CommentType.NONE, CommentType.class);
    PublishType publishType = Utils.stringToEnum(blog.getString("publish-type", "").toUpperCase(),
            PublishType.RESTRAINT, PublishType.class);
    JsonObject now = MongoDb.now();//w  ww .j a v a 2s  . c  o  m
    JsonObject owner = new JsonObject().put("userId", author.getUserId()).put("username", author.getUsername())
            .put("login", author.getLogin());
    blog.put("created", now).put("modified", now).put("author", owner).put("comment-type", commentType.name())
            .put("publish-type", publishType.name()).put("shared", new JsonArray());
    JsonObject b = Utils.validAndGet(blog, FIELDS, FIELDS);
    if (validationError(result, b))
        return;
    mongo.save(BLOG_COLLECTION, b, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> res) {
            result.handle(Utils.validResult(res));
        }
    });
}

From source file:org.entcore.blog.services.impl.DefaultBlogService.java

License:Open Source License

@Override
public void update(String blogId, JsonObject blog, final Handler<Either<String, JsonObject>> result) {
    blog.put("modified", MongoDb.now());
    if (blog.getString("comment-type") != null) {
        try {// w ww. j  a  va 2 s.co  m
            CommentType.valueOf(blog.getString("comment-type").toUpperCase());
            blog.put("comment-type", blog.getString("comment-type").toUpperCase());
        } catch (IllegalArgumentException | NullPointerException e) {
            blog.remove("comment-type");
        }
    }
    if (blog.getString("publish-type") != null) {
        try {
            PublishType.valueOf(blog.getString("publish-type").toUpperCase());
            blog.put("publish-type", blog.getString("publish-type").toUpperCase());
        } catch (IllegalArgumentException | NullPointerException e) {
            blog.remove("publish-type");
        }
    }
    JsonObject b = Utils.validAndGet(blog, UPDATABLE_FIELDS, Collections.<String>emptyList());
    if (validationError(result, b))
        return;
    QueryBuilder query = QueryBuilder.start("_id").is(blogId);
    MongoUpdateBuilder modifier = new MongoUpdateBuilder();
    for (String attr : b.fieldNames()) {
        modifier.set(attr, b.getValue(attr));
    }
    mongo.update(BLOG_COLLECTION, MongoQueryBuilder.build(query), modifier.build(),
            new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> event) {
                    result.handle(Utils.validResult(event));
                }
            });
}

From source file:org.entcore.blog.services.impl.DefaultPostService.java

License:Open Source License

@Override
public void create(String blogId, JsonObject post, UserInfos author,
        final Handler<Either<String, JsonObject>> result) {
    JsonObject now = MongoDb.now();/*from   w  w  w  .j  ava2  s .c o  m*/
    JsonObject blogRef = new JsonObject().put("$ref", "blogs").put("$id", blogId);
    JsonObject owner = new JsonObject().put("userId", author.getUserId()).put("username", author.getUsername())
            .put("login", author.getLogin());
    post.put("created", now).put("modified", now).put("author", owner).put("state", StateType.DRAFT.name())
            .put("comments", new JsonArray()).put("views", 0).put("blog", blogRef);
    JsonObject b = Utils.validAndGet(post, FIELDS, FIELDS);
    if (validationError(result, b))
        return;
    b.put("sorted", now);
    if (b.containsKey("content")) {
        b.put("contentPlain", StringUtils.stripHtmlTag(b.getString("content", "")));
    }
    mongo.save(POST_COLLECTION, b,
            MongoDbResult.validActionResultHandler(new Handler<Either<String, JsonObject>>() {
                public void handle(Either<String, JsonObject> event) {
                    if (event.isLeft()) {
                        result.handle(event);
                        return;
                    }
                    mongo.findOne(POST_COLLECTION,
                            new JsonObject().put("_id", event.right().getValue().getString("_id")),
                            MongoDbResult.validResultHandler(result));
                }
            }));
}