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

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

Introduction

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

Prototype

public JsonArray getJsonArray(String key) 

Source Link

Document

Get the JsonArray value with the specified key

Usage

From source file:org.entcore.directory.controllers.ShareBookmarkController.java

License:Open Source License

@Get("/sharebookmark/:id")
@SecuredAction(value = "", type = ActionType.AUTHENTICATED)
public void get(HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, user -> {
        if (user != null) {
            final String id = request.params().get("id");
            if ("all".equals(id)) {
                shareBookmarkService.list(user.getUserId(), arrayResponseHandler(request));
            } else {
                shareBookmarkService.get(user.getUserId(), id, r -> {
                    if (r.isRight()) {
                        final JsonObject res = r.right().getValue();
                        JsonArray members = res.getJsonArray("members");
                        if (members == null || members.isEmpty()) {
                            shareBookmarkService.delete(user.getUserId(), id, dres -> {
                                if (dres.isLeft()) {
                                    log.error("Error deleting sharebookmark " + id + " : "
                                            + dres.left().getValue());
                                }/*from  w w w.j  a v a 2s  . c  o  m*/
                            });
                            notFound(request, "empty.sharebookmark");
                            return;
                        }
                        res.mergeIn(UserUtils.translateAndGroupVisible(members, I18n.acceptLanguage(request),
                                true));
                        res.remove("members");
                        renderJson(request, res);
                    } else {
                        leftToResponse(request, r.left());
                    }
                });
            }
        } else {
            badRequest(request, "invalid.user");
        }
    });
}

From source file:org.entcore.directory.controllers.StructureController.java

License:Open Source License

@Get("/structure/:structureId/massMail/process/:type")
@SecuredAction(value = "", type = ActionType.RESOURCE)
public void performMassmail(final HttpServerRequest request) {
    final String structureId = request.params().get("structureId");
    final String type = request.params().get("type");
    final JsonObject filter = new JsonObject();
    final String filename = request.params().get("filename");
    final Boolean filterMail = request.params().contains("mail") ? new Boolean(request.params().get("mail"))
            : null;/* w w w  . ja  v a  2  s.  c  om*/

    filter.put("profiles", new fr.wseduc.webutils.collections.JsonArray(request.params().getAll("p")))
            .put("levels", new fr.wseduc.webutils.collections.JsonArray(request.params().getAll("l")))
            .put("classes", new fr.wseduc.webutils.collections.JsonArray(request.params().getAll("c")))
            .put("sort", new fr.wseduc.webutils.collections.JsonArray(request.params().getAll("s")));

    if (request.params().contains("a")) {
        filter.put("activated", request.params().get("a"));
    }

    this.assetsPath = (String) vertx.sharedData().getLocalMap("server").get("assetPath");
    this.skins = vertx.sharedData().getLocalMap("skins");

    final String assetsPath = this.assetsPath + "/assets/themes/" + this.skins.get(Renders.getHost(request));
    final String templatePath = assetsPath + "/template/directory/";
    final String baseUrl = getScheme(request) + "://" + Renders.getHost(request) + "/assets/themes/"
            + this.skins.get(Renders.getHost(request)) + "/img/";

    final boolean groupClasses = !filter.getJsonArray("sort").contains("classname");

    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        public void handle(final UserInfos infos) {

            //PDF
            if ("pdf".equals(type)) {
                structureService.massmailUsers(structureId, filter, groupClasses, false, filterMail, infos,
                        new Handler<Either<String, JsonArray>>() {
                            public void handle(Either<String, JsonArray> result) {
                                if (result.isLeft()) {
                                    forbidden(request);
                                    return;
                                }

                                massMailTypePdf(request, templatePath, baseUrl, filename,
                                        result.right().getValue());
                            }
                        });
            }
            //Mail
            else if ("mail".equals(type)) {
                structureService.massmailUsers(structureId, filter, true, true, filterMail, infos,
                        new Handler<Either<String, JsonArray>>() {
                            public void handle(final Either<String, JsonArray> result) {
                                if (result.isLeft()) {
                                    forbidden(request);
                                    return;
                                }

                                massMailTypeMail(request, templatePath, result.right().getValue());
                            }
                        });
            } else {
                badRequest(request);
            }

        }
    });
}

From source file:org.entcore.directory.controllers.StructureController.java

License:Open Source License

@Put("structure/:id/profile/block")
@SecuredAction(value = "", type = ActionType.RESOURCE)
@ResourceFilter(AdminStructureFilter.class)
public void blockUsers(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, new Handler<JsonObject>() {
        @Override/*from  ww w .  jav  a  2 s .c  o m*/
        public void handle(JsonObject json) {
            final String structureId = request.params().get("id");
            final String profile = json.getString("profile");
            final boolean block = json.getBoolean("block", true);
            structureService.blockUsers(structureId, profile, block, new Handler<JsonObject>() {
                @Override
                public void handle(JsonObject r) {
                    if ("ok".equals(r.getString("status"))) {
                        request.response().end();
                        JsonArray usersId = r.getJsonArray("result").getJsonObject(0).getJsonArray("usersId");
                        for (Object userId : usersId) {
                            UserUtils.deletePermanentSession(eb, (String) userId, null, new Handler<Boolean>() {
                                @Override
                                public void handle(Boolean event) {
                                    if (!event) {
                                        log.error("Error delete permanent session with userId : " + userId);
                                    }
                                }
                            });
                            UserUtils.deleteCacheSession(eb, (String) userId, new Handler<Boolean>() {
                                @Override
                                public void handle(Boolean event) {
                                    if (!event) {
                                        log.error("Error delete cache session with userId : " + userId);
                                    }
                                }
                            });
                        }
                    } else {
                        badRequest(request);
                    }
                }
            });
        }
    });
}

From source file:org.entcore.directory.controllers.UserController.java

License:Open Source License

@Post("/user/function/:userId")
@SecuredAction(value = "", type = ActionType.RESOURCE)
@ResourceFilter(AddFunctionFilter.class)
@IgnoreCsrf/*w ww  .ja  va 2s. c  o  m*/
public void addFunction(final HttpServerRequest request) {
    final String userId = request.params().get("userId");
    bodyToJson(request, pathPrefix + "addFunction", new Handler<JsonObject>() {
        @Override
        public void handle(JsonObject event) {
            userService.addFunction(userId, event.getString("functionCode"), event.getJsonArray("scope"),
                    event.getString("inherit", ""), r -> {
                        if (r.isRight()) {
                            final String groupId = (String) r.right().getValue().remove("groupId");
                            if (isNotEmpty(groupId)) {
                                JsonObject j = new JsonObject().put("action", "setCommunicationRules")
                                        .put("groupId", groupId);
                                eb.send("wse.communication", j);
                            }
                            renderJson(request, r.right().getValue());
                        } else {
                            badRequest(request, r.left().getValue());
                        }
                    });
        }
    });
}

From source file:org.entcore.directory.security.TeacherOfUser.java

License:Open Source License

@Override
public void authorize(final HttpServerRequest resourceRequest, Binding binding, final UserInfos user,
        final Handler<Boolean> handler) {
    RequestUtils.bodyToJson(resourceRequest, new Handler<JsonObject>() {
        @Override/*  ww w  . ja  va  2s .  c  o m*/
        public void handle(JsonObject event) {
            if (event != null) {
                JsonArray userIds = event.getJsonArray("users");
                if (userIds == null || userIds.size() == 0 || userIds.contains(user.getUserId())
                        || (!"Teacher".equals(user.getType()) && !"Personnel".equals(user.getType()))) {
                    handler.handle(false);
                    return;
                }
                String query = "MATCH (t:User { id : {teacherId}})-[:IN]->(g:ProfileGroup)-[:DEPENDS]->(c:Class) "
                        + "WITH c " + "MATCH c<-[:DEPENDS]-(og:ProfileGroup)<-[:IN]-(u:User) "
                        + "WHERE u.id IN {userIds} " + "RETURN count(distinct u) = {size} as exists ";
                JsonObject params = new JsonObject().put("userIds", userIds).put("teacherId", user.getUserId())
                        .put("size", userIds.size());
                validateQuery(resourceRequest, handler, query, params);
            } else {
                handler.handle(false);
            }
        }
    });

}

From source file:org.entcore.directory.services.impl.DefaultSchoolService.java

License:Open Source License

@Override
public void massmailUsers(String structureId, JsonObject filterObj, boolean groupClasses, boolean groupChildren,
        Boolean hasMail, UserInfos userInfos, Handler<Either<String, JsonArray>> results) {

    String filter = "MATCH (s:Structure {id: {structureId}})<-[:DEPENDS]-(g:ProfileGroup)<-[:IN]-(u:User), "
            + "(g)-[:HAS_PROFILE]-(p: Profile) ";
    String condition = "";
    String optional = "OPTIONAL MATCH (s)<-[:BELONGS]-(c:Class)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u) "
            + "OPTIONAL MATCH (u)<-[:RELATED]-(child: User)-[:IN]->(:ProfileGroup)-[:DEPENDS]->(c) ";

    JsonObject params = new JsonObject().put("structureId", structureId);

    //Activation//from  www  . j  av  a2  s.c o  m
    if (filterObj.containsKey("activated")) {
        String activated = filterObj.getString("activated", "false");
        if ("false".equals(activated.toLowerCase())) {
            condition = "WHERE NOT(u.activationCode IS NULL) ";
        } else if ("true".equals(activated.toLowerCase())) {
            condition = "WHERE (u.activationCode IS NULL) ";
        } else {
            condition = "WHERE 1 = 1 ";
        }
    } else {
        condition = "WHERE NOT(u.activationCode IS NULL) ";
    }

    //Profiles
    if (filterObj.getJsonArray("profiles").size() > 0) {
        condition += "AND p.name IN {profilesArray} ";
        params.put("profilesArray", filterObj.getJsonArray("profiles"));
    }

    //Levels
    if (filterObj.getJsonArray("levels").size() > 0) {
        condition += " AND u.level IN {levelsArray} ";
        params.put("levelsArray", filterObj.getJsonArray("levels"));
    }

    //Classes
    if (filterObj.getJsonArray("classes").size() > 0) {
        filter += ", (c:Class)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u) ";
        optional = "OPTIONAL MATCH (u)<-[:RELATED]-(child: User)-[:IN]->(:ProfileGroup)-[:DEPENDS]->(c) ";
        condition += " AND c.id IN {classesArray} ";
        params.put("classesArray", filterObj.getJsonArray("classes"));
    }

    //Email
    if (hasMail != null) {
        if (hasMail) {
            condition += " AND COALESCE(u.email, \"\") <> \"\" ";
        } else {
            condition += " AND COALESCE(u.email, \"\") = \"\" ";
        }

    }

    //Admin check
    if (!userInfos.getFunctions().containsKey(SUPER_ADMIN) && !userInfos.getFunctions().containsKey(ADMIN_LOCAL)
            && !userInfos.getFunctions().containsKey(CLASS_ADMIN)) {
        results.handle(new Either.Left<String, JsonArray>("forbidden"));
        return;
    } else if (userInfos.getFunctions().containsKey(ADMIN_LOCAL)) {
        UserInfos.Function f = userInfos.getFunctions().get(ADMIN_LOCAL);
        List<String> scope = f.getScope();
        if (scope != null && !scope.isEmpty()) {
            condition += "AND s.id IN {scope} ";
            params.put("scope", new fr.wseduc.webutils.collections.JsonArray(scope));
        }
    } else if (userInfos.getFunctions().containsKey(CLASS_ADMIN)) {
        if (filterObj.getJsonArray("classes").size() < 1) {
            results.handle(new Either.Left<String, JsonArray>("forbidden"));
            return;
        }

        UserInfos.Function f = userInfos.getFunctions().get(CLASS_ADMIN);
        List<String> scope = f.getScope();
        if (scope != null && !scope.isEmpty()) {
            condition = "AND c.id IN {scope} ";
            params.put("scope", new fr.wseduc.webutils.collections.JsonArray(scope));
        }
    }

    //With clause
    String withStr = "WITH u, p ";

    //Return clause
    String returnStr = "RETURN distinct collect(p.name)[0] as profile, "
            + "u.id as id, u.firstName as firstName, u.lastName as lastName, "
            + "u.email as email, CASE WHEN u.loginAlias IS NOT NULL THEN u.loginAlias ELSE u.login END as login, u.activationCode as activationCode ";

    if (groupClasses) {
        withStr += ", collect(distinct c.name) as classes, min(c.name) as classname, CASE count(c) WHEN 0 THEN false ELSE true END as isInClass ";
        returnStr += ", classes, classname, isInClass ";
    } else {
        withStr += ", c.name as classname, CASE count(c) WHEN 0 THEN false ELSE true END as isInClass ";
        returnStr += ", classname, isInClass ";
    }

    if (groupChildren) {
        withStr += ", CASE count(child) WHEN 0 THEN null ELSE collect(distinct {firstName: child.firstName, lastName: child.lastName, classname: c.name}) END as children ";
        returnStr += ", filter(c IN children WHERE not(c.firstName is null)) as children ";
    } else {
        if (groupClasses) {
            withStr = "WITH u, p, c, " + "CASE count(child) WHEN 0 THEN null "
                    + "ELSE {firstName: child.firstName, lastName: child.lastName, classname: c.name} "
                    + "END as child " + withStr + ", child ";
        } else {
            withStr += ", CASE count(child) WHEN 0 THEN null ELSE {firstName: child.firstName, lastName: child.lastName } END as child ";
        }
        returnStr += ", child ";
    }

    //Order by
    String sort = "ORDER BY ";
    for (Object sortObj : filterObj.getJsonArray("sort")) {
        String sortstr = (String) sortObj;
        sort += sortstr + ",";
    }
    sort += "lastName";

    String query = filter + condition + optional + withStr + returnStr + sort;

    neo.execute(query.toString(), params, validResultHandler(results));
}

From source file:org.entcore.directory.services.impl.DefaultShareBookmarkService.java

License:Open Source License

@Override
public void update(String userId, String id, JsonObject bookmark, Handler<Either<String, JsonObject>> handler) {
    final String query = "MATCH (u:User {id:{userId}}) " + "MERGE u-[:HAS_SB]->(sb:ShareBookmark) " + "SET sb."
            + cleanId(id) + " = {bookmark} ";
    JsonObject params = new JsonObject();
    params.put("userId", userId);
    params.put("bookmark", new JsonArray().add(bookmark.getString("name"))
            .addAll(getOrElse(bookmark.getJsonArray("members"), new JsonArray())));
    neo4j.execute(query, params, validEmptyHandler(handler));
}

From source file:org.entcore.directory.services.impl.DefaultShareBookmarkService.java

License:Open Source License

@Override
public void list(String userId, Handler<Either<String, JsonArray>> handler) {
    final String query = "MATCH (:User {id:{userId}})-[:HAS_SB]->(sb:ShareBookmark) return sb";
    JsonObject params = new JsonObject();
    params.put("userId", userId);
    neo4j.execute(query, params, fullNodeMergeHandler("sb", node -> {
        if (node.isRight()) {
            final JsonObject j = node.right().getValue();
            final JsonArray result = new JsonArray();
            for (String id : j.fieldNames()) {
                final JsonArray value = j.getJsonArray(id);
                if (value == null || value.size() < 2) {
                    delete(userId, id, dres -> {
                        if (dres.isLeft()) {
                            log.error("Error deleting sharebookmark " + id + " : " + dres.left().getValue());
                        }//from w w  w.  j av a2  s .c o m
                    });
                    continue;
                }
                final JsonObject r = new fr.wseduc.webutils.collections.JsonObject();
                r.put("id", id);
                r.put("name", value.remove(0));
                //r.put("membersIds", value);
                result.add(r);
            }
            handler.handle(new Either.Right<>(result));
        } else {
            handler.handle(new Either.Left<>(node.left().getValue()));
        }
    }));
}

From source file:org.entcore.directory.services.impl.DefaultTimetableService.java

License:Open Source License

@Override
public void updateClassesMapping(final String structureId, final JsonObject mapping,
        final Handler<Either<String, JsonObject>> handler) {

    classesMapping(structureId, new Handler<Either<String, JsonObject>>() {
        @Override/*from  w w w . j a v  a2 s .  c  om*/
        public void handle(Either<String, JsonObject> event) {
            if (event.isRight()) {
                final JsonObject cm = event.right().getValue();
                if (cm == null || cm.getJsonArray("unknownClasses") == null) {
                    handler.handle(new Either.Left<String, JsonObject>("missing.classes.mapping"));
                    return;
                }
                final JsonArray uc = cm.getJsonArray("unknownClasses");
                final JsonObject m = mapping.getJsonObject("mapping");
                for (String attr : m.copy().fieldNames()) {
                    if (!uc.contains(attr)) {
                        m.remove(attr);
                    }
                }
                mapping.put("mapping", m.encode());
                final String query = "MATCH (:Structure {id:{id}})<-[:MAPPING]-(cm:ClassesMapping) "
                        + "SET cm.mapping = {mapping} ";
                neo4j.execute(query, mapping.put("id", structureId), validEmptyHandler(handler));
            } else {
                handler.handle(event);
            }
        }
    });
}

From source file:org.entcore.directory.services.impl.DefaultUserBookService.java

License:Open Source License

@Override
public void update(String userId, JsonObject userBook, final Handler<Either<String, JsonObject>> result) {
    JsonObject u = Utils.validAndGet(userBook, UPDATE_USERBOOK_FIELDS, Collections.<String>emptyList());
    if (Utils.defaultValidationError(u, result, userId))
        return;//from   w  ww  . j av  a  2s  . com
    // OVERRIDE AVATAR URL
    Optional<String> pictureId = getPictureIdForUserbook(userBook);
    if (pictureId.isPresent()) {
        String fileId = avatarFileNameFromUserId(userId, Optional.empty());
        u.put("picture", "/userbook/avatar/" + fileId);
    }

    StatementsBuilder b = new StatementsBuilder();
    String query = "MATCH (u:`User` { id : {id}})-[:USERBOOK]->(ub:UserBook) WITH ub.picture as oldpic,ub,u SET "
            + nodeSetPropertiesFromJson("ub", u);
    query += " RETURN oldpic,ub.picture as picture";
    boolean updateUserBook = u.size() > 0;
    if (updateUserBook) {
        b.add(query, u.put("id", userId));
    }
    String q2 = "MATCH (u:`User` { id : {id}})-[:USERBOOK]->(ub:UserBook)"
            + "-[:PUBLIC|PRIVE]->(h:`Hobby` { category : {category}}) " + "SET h.values = {values} ";
    JsonArray hobbies = userBook.getJsonArray("hobbies");
    if (hobbies != null) {
        for (Object o : hobbies) {
            if (!(o instanceof JsonObject))
                continue;
            JsonObject j = (JsonObject) o;
            b.add(q2, j.put("id", userId));
        }
    }
    neo.executeTransaction(b.build(), null, true, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> r) {
            if ("ok".equals(r.body().getString("status"))) {
                if (updateUserBook) {
                    JsonArray results = r.body().getJsonArray("results", new JsonArray());
                    JsonArray firstStatement = results.getJsonArray(0);
                    if (firstStatement != null && firstStatement.size() > 0) {
                        JsonObject object = firstStatement.getJsonObject(0);
                        String picture = object.getString("picture", "");
                        cacheAvatarFromUserBook(userId, pictureId, StringUtils.isEmpty(picture))
                                .setHandler(e -> {
                                    if (e.succeeded()) {
                                        result.handle(new Either.Right<String, JsonObject>(new JsonObject()));
                                    } else {
                                        result.handle(new Either.Left<String, JsonObject>(
                                                r.body().getString("message", "update.error")));
                                    }
                                });
                    }
                } else {
                    result.handle(new Either.Right<String, JsonObject>(new JsonObject()));
                }
            } else {
                result.handle(
                        new Either.Left<String, JsonObject>(r.body().getString("message", "update.error")));
            }
        }
    });
}