Example usage for io.vertx.core.json JsonArray add

List of usage examples for io.vertx.core.json JsonArray add

Introduction

In this page you can find the example usage for io.vertx.core.json JsonArray add.

Prototype

public JsonArray add(Object value) 

Source Link

Document

Add an Object to the JSON array.

Usage

From source file:org.entcore.registry.controllers.WidgetController.java

License:Open Source License

@BusAddress("wse.app.registry.widgets")
public void collectWidgets(final Message<JsonObject> message) {
    final JsonArray widgets = message.body().getJsonArray("widgets",
            new fr.wseduc.webutils.collections.JsonArray());
    if (widgets.size() == 0 && message.body().containsKey("widget")) {
        widgets.add(message.body().getJsonObject("widget"));
    } else if (widgets.size() == 0) {
        message.reply(new JsonObject().put("status", "error").put("message", "invalid.parameters"));
        return;//from  ww w.  ja v a 2  s.  c  o m
    }

    final AtomicInteger countdown = new AtomicInteger(widgets.size());
    final JsonObject reply = new JsonObject().put("status", "ok").put("errors",
            new fr.wseduc.webutils.collections.JsonArray());

    final Handler<JsonObject> replyHandler = new Handler<JsonObject>() {
        public void handle(JsonObject res) {
            if ("error".equals(res.getString("status"))) {
                reply.put("status", "error");
                reply.getJsonArray("errors").add(reply.getString("message"));
            }
            if (countdown.decrementAndGet() == 0) {
                message.reply(reply);
            }
        }
    };

    for (Object widgetObj : widgets) {
        registerWidget((JsonObject) widgetObj, replyHandler);
    }
}

From source file:org.entcore.registry.services.impl.DefaultAppRegistryService.java

License:Open Source License

@Override
public void listCasConnectors(final Handler<Either<String, JsonArray>> handler) {
    String query = "MATCH (app:Application) " + "WHERE has(app.casType) and app.casType <> '' "
            + "RETURN app.casType as service, app.address as address, COLLECT(app.pattern) as patterns";
    neo.execute(query, (JsonObject) null, validResultHandler(new Handler<Either<String, JsonArray>>() {
        public void handle(Either<String, JsonArray> event) {
            if (event.isLeft()) {
                handler.handle(event);/*  w w  w  .ja v a2  s.c o  m*/
                return;
            }
            JsonArray results = event.right().getValue();
            for (Object o : results) {
                JsonObject app = (JsonObject) o;
                String address = app.getString("address", "");
                JsonArray patterns = app.getJsonArray("patterns",
                        new fr.wseduc.webutils.collections.JsonArray());
                if (patterns.size() == 0 || patterns.size() > 0 && patterns.getString(0).isEmpty()) {
                    final URL addressURL = checkCasUrl(address);

                    if (addressURL != null) {
                        String pattern = "^\\Q" + addressURL.getProtocol() + "://" + addressURL.getHost()
                                + (addressURL.getPort() > 0 ? ":" + addressURL.getPort() : "") + "\\E.*";
                        patterns.add(pattern);
                    } else {
                        log.error("Url for registered service : " + app.getString("service", "")
                                + " is malformed : " + address);
                    }
                }
            }
            handler.handle(new Either.Right<String, JsonArray>(results));
        }
    }));
}

From source file:org.entcore.registry.services.impl.DefaultExternalApplicationService.java

License:Open Source License

@Override
public void listExternalApps(String structureId, final Handler<Either<String, JsonArray>> handler) {
    String filter = "";
    JsonObject params = null;//from w  w  w  .j  a  v  a  2s  .c  o  m
    if (structureId != null && !structureId.trim().isEmpty()) {
        filter = ", (s:Structure)-[:HAS_ATTACHMENT*0..]->(p:Structure) "
                + "WHERE HAS(app.structureId) AND s.id = {structure} AND p.id = app.structureId AND r.structureId = app.structureId "
                + "AND (app.inherits = true OR p = s) ";
        params = new JsonObject().put("structure", structureId);
    }
    String query = "MATCH (app:Application:External)-[:PROVIDE]->(act:Action)<-[:AUTHORIZE]-(r:Role) " + filter
            + "WITH app, r, collect(distinct act) as roleActions " + "MATCH (app)-[:PROVIDE]->(action:Action) "
            + "RETURN distinct app as application, collect(action) as actions, collect(distinct {role: r, actions: roleActions}) as roles";
    neo.execute(query, params, validResultHandler(new Handler<Either<String, JsonArray>>() {
        public void handle(Either<String, JsonArray> event) {
            if (event.isLeft()) {
                handler.handle(event);
                return;
            }
            JsonArray rows = event.right().getValue();
            for (Object objRow : rows) {
                JsonObject row = (JsonObject) objRow;
                JsonObject application = row.getJsonObject("application");
                JsonArray actions = row.getJsonArray("actions");
                JsonArray roles = row.getJsonArray("roles");

                JsonObject appData = application.getJsonObject("data");
                JsonArray scope = appData.getJsonArray("scope");
                if (scope != null && scope.size() > 0) {
                    appData.put("scope", Joiner.on(" ").join(scope));
                } else {
                    appData.put("scope", "");
                }
                row.put("data", appData);
                row.remove("application");

                JsonArray actionsCopy = new fr.wseduc.webutils.collections.JsonArray();
                for (Object actionObj : actions) {
                    JsonObject action = (JsonObject) actionObj;
                    JsonObject data = action.getJsonObject("data");
                    actionsCopy.add(data);
                }
                row.put("actions", actionsCopy);

                for (Object roleObj : roles) {
                    JsonObject role = (JsonObject) roleObj;
                    JsonObject data = role.getJsonObject("role").getJsonObject("data");
                    role.put("role", data);
                    JsonArray acts = role.getJsonArray("actions");
                    JsonArray actsCopy = new fr.wseduc.webutils.collections.JsonArray();
                    for (Object actionObj : acts) {
                        JsonObject action = (JsonObject) actionObj;
                        actsCopy.add(action.getJsonObject("data"));
                    }
                    role.put("actions", actsCopy);

                }
            }

            handler.handle(event);
        }
    }));
}

From source file:org.entcore.session.AuthManager.java

License:Open Source License

private void generateSessionInfos(final String userId, final Handler<JsonObject> handler) {
    final String query = "MATCH (n:User {id : {id}}) " + "WHERE HAS(n.login) "
            + "OPTIONAL MATCH n-[:IN]->(gp:Group) " + "OPTIONAL MATCH gp-[:DEPENDS]->(s:Structure) "
            + "OPTIONAL MATCH gp-[:DEPENDS]->(c:Class) "
            + "OPTIONAL MATCH n-[rf:HAS_FUNCTION]->fg-[:CONTAINS_FUNCTION*0..1]->(f:Function) "
            + "OPTIONAL MATCH n<-[:RELATED]-(child:User) " + "RETURN distinct "
            + "n.classes as classNames, n.level as level, n.login as login, COLLECT(distinct [c.id, c.name]) as classes, "
            + "n.lastName as lastName, n.firstName as firstName, n.externalId as externalId, n.federated as federated, "
            + "n.birthDate as birthDate, "
            + "n.displayName as username, HEAD(n.profiles) as type, COLLECT(distinct [child.id, child.lastName, child.firstName]) as childrenInfo, "
            + "COLLECT(distinct [s.id, s.name]) as structures, COLLECT(distinct [f.externalId, rf.scope]) as functions, "
            + "COLLECT(distinct s.UAI) as uai, "
            + "COLLECT(distinct gp.id) as groupsIds, n.federatedIDP as federatedIDP, n.functions as aafFunctions";
    final String query2 = "MATCH (n:User {id : {id}})-[:IN]->()-[:AUTHORIZED]->(:Role)-[:AUTHORIZE]->(a:Action)"
            + "<-[:PROVIDE]-(app:Application) " + "WHERE HAS(n.login) "
            + "RETURN DISTINCT COLLECT(distinct [a.name,a.displayName,a.type]) as authorizedActions, "
            + "COLLECT(distinct [app.name,app.address,app.icon,app.target,app.displayName,app.display,app.prefix]) as apps";
    final String query3 = "MATCH (u:User {id: {id}})-[:IN]->(g:Group)-[auth:AUTHORIZED]->(w:Widget) "
            + "WHERE HAS(u.login) "
            + "AND ( NOT(w<-[:HAS_WIDGET]-(:Application)-[:PROVIDE]->(:WorkflowAction)) "
            + "XOR w<-[:HAS_WIDGET]-(:Application)-[:PROVIDE]->(:WorkflowAction)<-[:AUTHORIZE]-(:Role)<-[:AUTHORIZED]-g )  "
            + "OPTIONAL MATCH (w)<-[:HAS_WIDGET]-(app:Application) "
            + "WITH w, app, collect(auth) as authorizations " + "RETURN DISTINCT COLLECT({"
            + "id: w.id, name: w.name, " + "path: coalesce(app.address, '') + w.path, "
            + "js: coalesce(app.address, '') + w.js, " + "i18n: coalesce(app.address, '') + w.i18n, "
            + "application: app.name, "
            + "mandatory: ANY(a IN authorizations WHERE HAS(a.mandatory) AND a.mandatory = true)"
            + "}) as widgets";
    final String query4 = "MATCH (s:Structure) return s.id as id, s.externalId as externalId";
    final String query5 = "MATCH (u:User {id: {id}})-[:PREFERS]->(uac:UserAppConf) RETURN uac AS preferences";
    JsonObject params = new JsonObject();
    params.put("id", userId);
    JsonArray statements = new fr.wseduc.webutils.collections.JsonArray()
            .add(new JsonObject().put("statement", query).put("parameters", params))
            .add(new JsonObject().put("statement", query2).put("parameters", params))
            .add(new JsonObject().put("statement", query3).put("parameters", params))
            .add(new JsonObject().put("statement", query4))
            .add(new JsonObject().put("statement", query5).put("parameters", params));
    neo4j.executeTransaction(statements, null, true, new Handler<Message<JsonObject>>() {

        @Override//w  w w  .j a  v a 2 s .  co  m
        public void handle(Message<JsonObject> message) {
            JsonArray results = message.body().getJsonArray("results");
            if ("ok".equals(message.body().getString("status")) && results != null && results.size() == 5
                    && results.getJsonArray(0).size() > 0 && results.getJsonArray(1).size() > 0) {
                JsonObject j = results.getJsonArray(0).getJsonObject(0);
                JsonObject j2 = results.getJsonArray(1).getJsonObject(0);
                JsonObject j3 = results.getJsonArray(2).getJsonObject(0);
                JsonObject structureMapping = new JsonObject();
                for (Object o : results.getJsonArray(3)) {
                    if (!(o instanceof JsonObject))
                        continue;
                    JsonObject jsonObject = (JsonObject) o;
                    structureMapping.put(jsonObject.getString("externalId"), jsonObject.getString("id"));
                }
                j.put("userId", userId);
                JsonObject functions = new JsonObject();
                JsonArray actions = new fr.wseduc.webutils.collections.JsonArray();
                JsonArray apps = new fr.wseduc.webutils.collections.JsonArray();
                for (Object o : getOrElse(j2.getJsonArray("authorizedActions"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    JsonArray a = (JsonArray) o;
                    actions.add(new JsonObject().put("name", a.getString(0)).put("displayName", a.getString(1))
                            .put("type", a.getString(2)));
                }
                for (Object o : getOrElse(j2.getJsonArray("apps"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    JsonArray a = (JsonArray) o;
                    apps.add(new JsonObject().put("name", (String) a.getString(0))
                            .put("address", (String) a.getString(1)).put("icon", (String) a.getString(2))
                            .put("target", (String) a.getString(3)).put("displayName", (String) a.getString(4))
                            .put("display", ((a.getValue(5) == null) || a.getBoolean(5)))
                            .put("prefix", (String) a.getString(6)));
                }
                for (Object o : getOrElse(j.getJsonArray("aafFunctions"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (o == null)
                        continue;
                    String[] sf = o.toString().split("\\$");
                    if (sf.length == 5) {
                        JsonObject jo = functions.getJsonObject(sf[1]);
                        if (jo == null) {
                            jo = new JsonObject().put("code", sf[1]).put("functionName", sf[2])
                                    .put("scope", new fr.wseduc.webutils.collections.JsonArray())
                                    .put("structureExternalIds", new fr.wseduc.webutils.collections.JsonArray())
                                    .put("subjects", new JsonObject());
                            functions.put(sf[1], jo);
                        }
                        JsonObject subject = jo.getJsonObject("subjects").getJsonObject(sf[3]);
                        if (subject == null) {
                            subject = new JsonObject().put("subjectCode", sf[3]).put("subjectName", sf[4])
                                    .put("scope", new fr.wseduc.webutils.collections.JsonArray())
                                    .put("structureExternalIds",
                                            new fr.wseduc.webutils.collections.JsonArray());
                            jo.getJsonObject("subjects").put(sf[3], subject);
                        }
                        jo.getJsonArray("structureExternalIds").add(sf[0]);
                        subject.getJsonArray("structureExternalIds").add(sf[0]);
                        String sid = structureMapping.getString(sf[0]);
                        if (sid != null) {
                            jo.getJsonArray("scope").add(sid);
                            subject.getJsonArray("scope").add(sid);
                        }
                    }
                }
                j.remove("aafFunctions");
                for (Object o : getOrElse(j.getJsonArray("functions"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    JsonArray a = (JsonArray) o;
                    String code = a.getString(0);
                    if (code != null) {
                        functions.put(code, new JsonObject().put("code", code).put("scope", a.getJsonArray(1)));
                    }
                }
                final JsonObject children = new JsonObject();
                final List<String> childrenIds = new ArrayList<String>();
                for (Object o : getOrElse(j.getJsonArray("childrenInfo"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    final JsonArray a = (JsonArray) o;
                    final String childId = a.getString(0);
                    if (childId != null) {
                        childrenIds.add(childId);
                        JsonObject jo = children.getJsonObject(childId);
                        if (jo == null) {
                            jo = new JsonObject().put("lastName", a.getString(1)).put("firstName",
                                    a.getString(2));
                            children.put(childId, jo);
                        }
                    }
                }
                j.remove("childrenInfo");
                final List<String> classesIds = new ArrayList<String>();
                final List<String> classesNames = new ArrayList<String>();
                for (Object o : getOrElse(j.getJsonArray("classes"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    final JsonArray c = (JsonArray) o;
                    if (c.getString(0) != null) {
                        classesIds.add(c.getString(0));
                        classesNames.add(c.getString(1));
                    }
                }
                j.remove("classes");
                final List<String> structureIds = new ArrayList<String>();
                final List<String> structureNames = new ArrayList<String>();
                for (Object o : getOrElse(j.getJsonArray("structures"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    final JsonArray s = (JsonArray) o;
                    if (s.getString(0) != null) {
                        structureIds.add(s.getString(0));
                        structureNames.add(StringUtils.trimToBlank(s.getString(1)));
                    }
                }
                j.remove("structures");
                j.put("structures", new fr.wseduc.webutils.collections.JsonArray(structureIds));
                j.put("structureNames", new fr.wseduc.webutils.collections.JsonArray(structureNames));
                j.put("classes", new fr.wseduc.webutils.collections.JsonArray(classesIds));
                j.put("realClassesNames", new fr.wseduc.webutils.collections.JsonArray(classesNames));
                j.put("functions", functions);
                j.put("authorizedActions", actions);
                j.put("apps", apps);
                j.put("childrenIds", new fr.wseduc.webutils.collections.JsonArray(childrenIds));
                j.put("children", children);
                final JsonObject cache = (results.getJsonArray(4) != null && results.getJsonArray(4).size() > 0
                        && results.getJsonArray(4).getJsonObject(0) != null)
                                ? results.getJsonArray(4).getJsonObject(0)
                                : new JsonObject();
                j.put("cache", cache);
                j.put("widgets",
                        getOrElse(j3.getJsonArray("widgets"), new fr.wseduc.webutils.collections.JsonArray()));
                handler.handle(j);
            } else {
                handler.handle(null);
            }
        }
    });
}

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/registeredNotifications")
@SecuredAction(value = "", type = ActionType.AUTHENTICATED)
public void registeredNotifications(HttpServerRequest request) {
    JsonArray reply = new fr.wseduc.webutils.collections.JsonArray();
    for (String key : registeredNotifications.keySet()) {
        JsonObject notif = new JsonObject(registeredNotifications.get(key)).put("key", key);
        notif.remove("template");
        reply.add(notif);
    }//  w w  w .  j ava2 s  . c om
    renderJson(request, reply);
}

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/lastNotifications")
@SecuredAction(value = "timeline.events", type = ActionType.AUTHENTICATED)
public void lastEvents(final HttpServerRequest request) {
    final boolean mine = request.params().contains("mine");

    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {

        @Override//from w  ww .  j a v a  2s  .com
        public void handle(final UserInfos user) {
            if (user != null) {
                getExternalNotifications(new Handler<Either<String, JsonObject>>() {
                    public void handle(Either<String, JsonObject> notifs) {
                        if (notifs.isLeft()) {
                            badRequest(request, notifs.left().getValue());
                            return;
                        }

                        String page = request.params().get("page");
                        List<String> types = request.params().getAll("type");
                        int offset = 0;
                        try {
                            offset = 25 * Integer.parseInt(page);
                        } catch (NumberFormatException e) {
                        }

                        store.get(user, types, offset, 25, notifs.right().getValue(), mine,
                                new Handler<JsonObject>() {
                                    public void handle(final JsonObject res) {
                                        if (res != null && "ok".equals(res.getString("status"))) {
                                            JsonArray results = res.getJsonArray("results",
                                                    new fr.wseduc.webutils.collections.JsonArray());
                                            final JsonArray compiledResults = new fr.wseduc.webutils.collections.JsonArray();

                                            final AtomicInteger countdown = new AtomicInteger(results.size());
                                            final Handler<Void> endHandler = new Handler<Void>() {
                                                public void handle(Void v) {
                                                    if (countdown.decrementAndGet() <= 0) {
                                                        res.put("results", compiledResults);
                                                        renderJson(request, res);
                                                    }
                                                }
                                            };
                                            if (results.size() == 0)
                                                endHandler.handle(null);

                                            for (Object notifObj : results) {
                                                final JsonObject notif = (JsonObject) notifObj;
                                                if (!notif.getString("message", "").isEmpty()) {
                                                    compiledResults.add(notif);
                                                    endHandler.handle(null);
                                                    continue;
                                                }

                                                String key = notif.getString("type", "").toLowerCase() + "."
                                                        + notif.getString("event-type", "").toLowerCase();

                                                String stringifiedRegisteredNotif = registeredNotifications
                                                        .get(key);
                                                if (stringifiedRegisteredNotif == null) {
                                                    log.error(
                                                            "Failed to retrieve registered from the shared map notification with key : "
                                                                    + key);
                                                    endHandler.handle(null);
                                                    continue;
                                                }
                                                JsonObject registeredNotif = new JsonObject(
                                                        stringifiedRegisteredNotif);

                                                StringReader reader = new StringReader(
                                                        registeredNotif.getString("template", ""));
                                                processTemplate(request,
                                                        notif.getJsonObject("params", new JsonObject()), key,
                                                        reader, new Handler<Writer>() {
                                                            public void handle(Writer writer) {
                                                                notif.put("message", writer.toString());
                                                                compiledResults.add(notif);
                                                                endHandler.handle(null);
                                                            }
                                                        });
                                            }
                                        } else {
                                            renderError(request, res);
                                        }
                                    }
                                });
                    }
                });

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

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/notifications-defaults")
@SecuredAction("timeline.external.notifications")
public void mixinConfig(final HttpServerRequest request) {
    configService.list(new Handler<Either<String, JsonArray>>() {
        public void handle(Either<String, JsonArray> event) {
            if (event.isLeft()) {
                badRequest(request);/*  w ww  .  j  av a 2 s. co m*/
                return;
            }
            JsonArray admcDefaults = event.right().getValue();
            JsonArray reply = new fr.wseduc.webutils.collections.JsonArray();

            for (String key : registeredNotifications.keySet()) {
                JsonObject notif = new JsonObject(registeredNotifications.get(key)).put("key", key);
                notif.remove("template");
                for (Object admcDefaultObj : admcDefaults) {
                    JsonObject admcDefault = (JsonObject) admcDefaultObj;
                    if (admcDefault.getString("key", "").equals(key)) {
                        notif.mergeIn(admcDefault);
                        notif.remove("_id");
                        break;
                    }
                }
                reply.add(notif);
            }
            renderJson(request, reply);
        }
    });

}

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/reported")
@SecuredAction(type = ActionType.RESOURCE, value = "")
@ResourceFilter(AdmlOfStructures.class)
public void listReportedNotifications(final HttpServerRequest request) {
    final String structure = request.params().get("structure");
    final boolean pending = Boolean.parseBoolean(request.params().get("pending"));
    int page = 0;
    if (request.params().contains("page")) {
        try {/* ww w  .  ja  va2s  . co  m*/
            page = Integer.parseInt(request.params().get("page"));
        } catch (NumberFormatException e) {
            //silent
        }
    }
    store.listReported(structure, pending, PAGELIMIT * page, PAGELIMIT,
            new Handler<Either<String, JsonArray>>() {
                public void handle(Either<String, JsonArray> event) {
                    if (event.isLeft()) {
                        renderError(request);
                        return;
                    }

                    final JsonArray results = event.right().getValue();
                    final JsonArray compiledResults = new fr.wseduc.webutils.collections.JsonArray();

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

                    for (Object notifObj : results) {
                        final JsonObject notif = (JsonObject) notifObj;
                        if (!notif.getString("message", "").isEmpty()) {
                            compiledResults.add(notif);
                            endHandler.handle(null);
                            continue;
                        }

                        String key = notif.getString("type", "").toLowerCase() + "."
                                + notif.getString("event-type", "").toLowerCase();

                        String stringifiedRegisteredNotif = registeredNotifications.get(key);
                        if (stringifiedRegisteredNotif == null) {
                            log.error(
                                    "Failed to retrieve registered from the shared map notification with key : "
                                            + key);
                            endHandler.handle(null);
                            continue;
                        }
                        JsonObject registeredNotif = new JsonObject(stringifiedRegisteredNotif);

                        StringReader reader = new StringReader(registeredNotif.getString("template", ""));
                        processTemplate(request, notif.getJsonObject("params", new JsonObject()), key, reader,
                                new Handler<Writer>() {
                                    public void handle(Writer writer) {
                                        notif.put("message", writer.toString());
                                        compiledResults.add(notif);
                                        endHandler.handle(null);
                                    }
                                });
                    }
                }
            });
}

From source file:org.entcore.timeline.events.DefaultTimelineEventStore.java

License:Open Source License

@Override
public void get(final UserInfos user, List<String> types, int offset, int limit, JsonObject restrictionFilter,
        boolean mine, final Handler<JsonObject> result) {
    final String recipient = user.getUserId();
    final String externalId = user.getExternalId();
    if (recipient != null && !recipient.trim().isEmpty()) {
        final JsonObject query = new JsonObject().put("deleted", new JsonObject().put("$exists", false))
                .put("date", new JsonObject().put("$lt", MongoDb.now()));
        if (externalId == null || externalId.trim().isEmpty()) {
            query.put(mine ? "sender" : "recipients.userId", recipient);
        } else {/*from  w ww.j  a v  a2s.c  o  m*/
            query.put(mine ? "sender" : "recipients.userId", new JsonObject().put("$in",
                    new fr.wseduc.webutils.collections.JsonArray().add(recipient).add(externalId)));
        }
        query.put("reportAction.action", new JsonObject().put("$ne", "DELETE"));
        if (types != null && !types.isEmpty()) {
            if (types.size() == 1) {
                query.put("type", types.get(0));
            } else {
                JsonArray typesFilter = new fr.wseduc.webutils.collections.JsonArray();
                for (String t : types) {
                    typesFilter.add(new JsonObject().put("type", t));
                }
                query.put("$or", typesFilter);
            }
        }
        if (restrictionFilter != null && restrictionFilter.size() > 0) {
            JsonArray nor = new fr.wseduc.webutils.collections.JsonArray();
            for (String type : restrictionFilter.getMap().keySet()) {
                for (Object eventType : restrictionFilter.getJsonArray(type,
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    nor.add(new JsonObject().put("type", type).put("event-type", eventType.toString()));
                }
                query.put("$nor", nor);
            }
        }
        JsonObject sort = new JsonObject().put("created", -1);
        JsonObject keys = new JsonObject().put("message", 1).put("params", 1).put("date", 1).put("sender", 1)
                .put("comments", 1).put("type", 1).put("event-type", 1).put("resource", 1)
                .put("sub-resource", 1).put("add-comment", 1);
        if (!mine) {
            keys.put("recipients",
                    new JsonObject().put("$elemMatch", new JsonObject().put("userId", user.getUserId())));
            keys.put("reporters",
                    new JsonObject().put("$elemMatch", new JsonObject().put("userId", user.getUserId())));
        }

        mongo.find(TIMELINE_COLLECTION, query, sort, keys, offset, limit, 100,
                new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> message) {
                        result.handle(message.body());
                    }
                });
    } else {
        result.handle(invalidArguments());
    }
}

From source file:org.entcore.timeline.events.DefaultTimelineEventStore.java

License:Open Source License

private void markEventsAsRead(Message<JsonObject> message, String recipient) {
    JsonArray events = message.body().getJsonArray("results");
    if (events != null && "ok".equals(message.body().getString("status"))) {
        JsonArray ids = new fr.wseduc.webutils.collections.JsonArray();
        for (Object o : events) {
            if (!(o instanceof JsonObject))
                continue;
            JsonObject json = (JsonObject) o;
            ids.add(json.getString("_id"));
        }//from   w w  w.j a v  a2 s.  co  m
        JsonObject q = new JsonObject().put("_id", new JsonObject().put("$in", ids)).put("recipients",
                new JsonObject().put("$elemMatch", new JsonObject().put("userId", recipient).put("unread", 1)));
        mongo.update(TIMELINE_COLLECTION, q,
                new JsonObject().put("$set", new JsonObject().put("recipients.$.unread", 0)), false, true);
    }
}