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.common.notification.TimelineHelper.java

License:Open Source License

public void notifyTimeline(final HttpServerRequest req, final String notificationName, UserInfos sender,
        final List<String> recipients, String resource, String subResource, final JsonObject params,
        final boolean disableAntiFlood) {
    notificationsLoader.getNotification(notificationName, notification -> {
        JsonArray r = new fr.wseduc.webutils.collections.JsonArray();
        for (String userId : recipients) {
            r.add(new JsonObject().put("userId", userId).put("unread", 1));
        }/*from   w ww  . j  ava2 s.  com*/
        final JsonObject event = new JsonObject().put("action", "add")
                .put("type", notification.getString("type"))
                .put("event-type", notification.getString("event-type")).put("recipients", r)
                .put("recipientsIds", new fr.wseduc.webutils.collections.JsonArray(recipients));
        if (resource != null) {
            event.put("resource", resource);
        }
        if (sender != null) {
            event.put("sender", sender.getUserId());
        }
        if (subResource != null && !subResource.trim().isEmpty()) {
            event.put("sub-resource", subResource);
        }
        if (disableAntiFlood || params.getBoolean("disableAntiFlood", false)) {
            event.put("disableAntiFlood", true);
        }
        Long date = params.getLong("timeline-publish-date");
        if (date != null) {
            event.put("date", new JsonObject().put("$date", date));
            params.remove("timeline-publish-date");
        }

        event.put("pushNotif", params.remove("pushNotif"));

        HttpServerRequest request;
        if (req == null) {
            request = new JsonHttpServerRequest(new JsonObject());
        } else {
            request = req;
        }
        event.put("params", params).put("notificationName", notificationName).put("notification", notification)
                .put("request",
                        new JsonObject().put("headers",
                                new JsonObject().put("Host", Renders.getHost(request))
                                        .put("X-Forwarded-Proto", Renders.getScheme(request))
                                        .put("Accept-Language", request.headers().get("Accept-Language"))));
        eb.send(TIMELINE_ADDRESS, event, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
            public void handle(Message<JsonObject> event) {
                JsonObject result = event.body();
                if ("error".equals(result.getString("status", "error"))) {
                    log.error("Error in timeline notification : " + result.getString("message"));
                }
            }
        }));
    });
}

From source file:org.entcore.common.notification.TimelineHelper.java

License:Open Source License

/**
 * @deprecated/*from  w  ww.j a v  a2 s .c o  m*/
 * Notification system was refactored in version 1.16.1
 */
@Deprecated
public void notifyTimeline(HttpServerRequest request, UserInfos sender, String type, final String eventType,
        List<String> recipients, String resource, String subResource, String template, JsonObject params) {
    JsonArray r = new fr.wseduc.webutils.collections.JsonArray();
    for (String userId : recipients) {
        r.add(new JsonObject().put("userId", userId).put("unread", 1));
    }
    final JsonObject event = new JsonObject().put("action", "add").put("type", type)
            .put("event-type", eventType).put("recipients", r);
    if (resource != null) {
        event.put("resource", resource);
    }
    if (sender != null) {
        event.put("sender", sender.getUserId());
    }
    if (subResource != null && !subResource.trim().isEmpty()) {
        event.put("sub-resource", subResource);
    }
    Long date = params.getLong("timeline-publish-date");
    if (date != null) {
        event.put("date", new JsonObject().put("$date", date));
        params.remove("timeline-publish-date");
    }
    render.processTemplate(request, template, params, new Handler<String>() {
        @Override
        public void handle(String message) {
            if (message != null) {
                event.put("message", message);
                eb.send(TIMELINE_ADDRESS, event);
            } else {
                log.error("Unable to send timeline " + eventType + " notification.");
            }
        }
    });
}

From source file:org.entcore.common.notification.TimelineNotificationsLoader.java

License:Open Source License

private void processNotification(final String path, final String type) {
    final File pathFile = new File(path);
    final String notificationName = pathFile.getName().substring(0, pathFile.getName().lastIndexOf('.'));
    final String propsFilePath = path.substring(0, path.lastIndexOf(".")) + ".json";
    //final String templatePath = pathFile.getAbsolutePath().substring(pathFile.getAbsolutePath().indexOf("notify/"));

    vertx.fileSystem().readFile(path, new Handler<AsyncResult<Buffer>>() {
        public void handle(AsyncResult<Buffer> templateAsync) {
            if (templateAsync.failed()) {
                log.error("Cannot read template at path : " + path);
                return;
            }/*  ww  w .  j ava  2s.c  om*/

            final String fullName = (type + "." + notificationName).toLowerCase();

            //Default values
            final JsonObject notificationJson = new JsonObject().put("type", type.toUpperCase())
                    .put("event-type", notificationName.toUpperCase())
                    .put("app-name", Config.getConf().getString("app-name"))
                    .put("app-address", Config.getConf().getString("app-address", "/"))
                    .put("template", templateAsync.result().toString())
                    .put("defaultFrequency", Frequencies.defaultFrequency())
                    .put("restriction", Restrictions.defaultRestriction()).put("push-notif", false);

            vertx.fileSystem().exists(propsFilePath, new Handler<AsyncResult<Boolean>>() {
                public void handle(AsyncResult<Boolean> ar) {
                    if (ar.succeeded()) {
                        if (ar.result()) {
                            vertx.fileSystem().readFile(propsFilePath, new Handler<AsyncResult<Buffer>>() {
                                public void handle(AsyncResult<Buffer> ar) {
                                    if (ar.succeeded()) {
                                        JsonObject props = new JsonObject(ar.result().toString("UTF-8"));

                                        // Overrides
                                        registerNotification(fullName,
                                                notificationJson
                                                        .put("defaultFrequency",
                                                                props.getString("default-frequency",
                                                                        notificationJson
                                                                                .getString("defaultFrequency")))
                                                        .put("restriction",
                                                                props.getString("restrict",
                                                                        notificationJson
                                                                                .getString("restriction")))
                                                        .put("push-notif",
                                                                props.getBoolean("push-notif", false)));
                                    } else {
                                        registerNotification(fullName, notificationJson);
                                    }
                                }
                            });
                        } else {
                            registerNotification(fullName, notificationJson);
                        }
                    }
                }
            });
        }
    });

}

From source file:org.entcore.common.service.impl.MongoDbCrudService.java

License:Open Source License

@Override
public void create(JsonObject data, UserInfos user, Handler<Either<String, JsonObject>> handler) {
    JsonObject now = MongoDb.now();//from   ww w . j  av  a2 s  .c o  m
    data.put("owner", new JsonObject().put("userId", user.getUserId()).put("displayName", user.getUsername()))
            .put("created", now).put("modified", now);
    addPlainField(data);
    mongo.save(collection, data, validActionResultHandler(handler));
}

From source file:org.entcore.common.service.impl.MongoDbCrudService.java

License:Open Source License

private void addPlainField(JsonObject data) {
    if (!this.mongoDbConf.getSearchTextFields().isEmpty()) {
        for (final String field : this.mongoDbConf.getSearchTextFields()) {
            final List<String> decomposition = StringUtils.split(field, "\\.");
            final String collection = decomposition.get(0);
            if (this.collection.equals(collection)) {
                if (decomposition.size() == 2) {
                    //not an object or array
                    final String label = decomposition.get(1);
                    if (data.containsKey(label)) {
                        data.put(label + plainSuffixField, StringUtils.stripHtmlTag(data.getString(label)));
                    }//from  ww  w .  j a v a2  s .  c  om
                } else if (decomposition.size() == 3) {
                    final String label = decomposition.get(1);
                    final String deepLabel = decomposition.get(2);
                    final Object element = data.getValue(label);
                    if (element instanceof JsonArray) {
                        //not processed yet
                        log.error("the plain duplication d'ont support Json Array");
                    } else if (element instanceof JsonObject) {
                        final JsonObject jo = (JsonObject) element;
                        if (jo.containsKey(deepLabel)) {
                            jo.put(deepLabel + plainSuffixField,
                                    StringUtils.stripHtmlTag(jo.getString(deepLabel)));
                        }
                    }
                } else {
                    //object too complex : not treaty
                    log.error(
                            "the plain duplication only works for a string field or top-level field of an object : collection.field | collection.object.field");
                }
            } else {
                break;
            }
        }
    }
}

From source file:org.entcore.common.service.impl.MongoDbSearchService.java

License:Open Source License

@Override
public void search(String userId, List<String> groupIds, List<String> returnFields, List<String> searchWords,
        Integer page, Integer limit, Handler<Either<String, JsonArray>> handler) {
    final int skip = (0 == page) ? -1 : page * limit;

    final List<DBObject> groups = new ArrayList<DBObject>();
    groups.add(QueryBuilder.start("userId").is(userId).get());
    for (String gpId : groupIds) {
        groups.add(QueryBuilder.start("groupId").is(gpId).get());
    }/* w  w  w .j  a v a 2 s.  c o m*/

    final QueryBuilder worldsQuery = new QueryBuilder();
    //no stemming (in fact, stemming works only with words and for a given language) and no list of stop words
    worldsQuery.text(textSearchedComposition(searchWords));

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

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

    JsonObject sort = new JsonObject().put("modified", -1);
    final JsonObject projection = new JsonObject();
    for (String field : returnFields) {
        projection.put(field, 1);
    }

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

From source file:org.entcore.common.service.impl.SqlCrudService.java

License:Open Source License

@Override
public void create(JsonObject data, UserInfos user, final Handler<Either<String, JsonObject>> handler) {
    SqlStatementsBuilder s = new SqlStatementsBuilder();
    //      String userQuery = Sql.upsert(resourceTable,
    //            "UPDATE users SET username = '" + user.getUsername() + "' WHERE id = '" + user.getUserId() + "'",
    //            "INSERT INTO users (username, id) SELECT '" + user.getUsername() + "','" + user.getUserId() + "'"
    //      );/*from   ww  w .j av a 2 s .  c  o  m*/
    //      s.raw(userQuery);
    String userQuery = "SELECT " + schema + "merge_users(?,?)";
    s.prepared(userQuery,
            new fr.wseduc.webutils.collections.JsonArray().add(user.getUserId()).add(user.getUsername()));
    data.put("owner", user.getUserId());
    s.insert(resourceTable, data, "id");
    sql.transaction(s.build(), validUniqueResultHandler(1, handler));
}

From source file:org.entcore.common.share.impl.GenericShareService.java

License:Open Source License

protected JsonArray getResoureActions(Map<String, SecuredAction> securedActions) {
    if (resourceActions != null) {
        return resourceActions;
    }//from  www  .j  av a  2 s .c  o m
    JsonObject resourceActions = new JsonObject();
    for (SecuredAction action : securedActions.values()) {
        if (ActionType.RESOURCE.name().equals(action.getType()) && !action.getDisplayName().isEmpty()) {
            JsonObject a = resourceActions.getJsonObject(action.getDisplayName());
            if (a == null) {
                a = new JsonObject()
                        .put("name",
                                new fr.wseduc.webutils.collections.JsonArray()
                                        .add(action.getName().replaceAll("\\.", "-")))
                        .put("displayName", action.getDisplayName()).put("type", action.getType());
                resourceActions.put(action.getDisplayName(), a);
            } else {
                a.getJsonArray("name").add(action.getName().replaceAll("\\.", "-"));
            }
        }
    }
    this.resourceActions = new fr.wseduc.webutils.collections.JsonArray(
            new ArrayList<>(resourceActions.getMap().values()));
    return this.resourceActions;
}

From source file:org.entcore.common.share.impl.GenericShareService.java

License:Open Source License

protected void getShareInfos(final String userId, final JsonArray actions, final JsonObject groupCheckedActions,
        final JsonObject userCheckedActions, final String acceptLanguage, String search,
        final Handler<JsonObject> handler) {
    final JsonObject params = new JsonObject().put("groupIds",
            new fr.wseduc.webutils.collections.JsonArray(new ArrayList<>(groupCheckedActions.fieldNames())));
    final JsonObject params2 = new JsonObject().put("userIds",
            new fr.wseduc.webutils.collections.JsonArray(new ArrayList<>(userCheckedActions.fieldNames())));
    if (search != null && search.trim().isEmpty()) {
        final Neo4j neo4j = Neo4j.getInstance();
        neo4j.execute(GROUP_SHARED, params, validResultHandler(new Handler<Either<String, JsonArray>>() {
            @Override//from www  . j  av  a2  s.c o  m
            public void handle(Either<String, JsonArray> sg) {
                JsonArray visibleGroups;
                if (sg.isRight()) {
                    visibleGroups = sg.right().getValue();
                } else {
                    visibleGroups = new fr.wseduc.webutils.collections.JsonArray();
                }
                final JsonObject groups = new JsonObject();
                groups.put("visibles", visibleGroups);
                groups.put("checked", groupCheckedActions);
                for (Object u : visibleGroups) {
                    if (!(u instanceof JsonObject))
                        continue;
                    JsonObject group = (JsonObject) u;
                    UserUtils.groupDisplayName(group, acceptLanguage);
                }
                neo4j.execute(USER_SHARED, params2,
                        validResultHandler(new Handler<Either<String, JsonArray>>() {
                            @Override
                            public void handle(Either<String, JsonArray> event) {
                                JsonArray visibleUsers;
                                if (event.isRight()) {
                                    visibleUsers = event.right().getValue();
                                } else {
                                    visibleUsers = new fr.wseduc.webutils.collections.JsonArray();
                                }
                                JsonObject users = new JsonObject();
                                users.put("visibles", visibleUsers);
                                users.put("checked", userCheckedActions);
                                JsonObject share = new JsonObject().put("actions", actions)
                                        .put("groups", groups).put("users", users);
                                handler.handle(share);
                            }
                        }));
            }
        }));
    } else {
        final String preFilter;
        if (search != null) {
            preFilter = "AND m.displayNameSearchField CONTAINS {search} ";
            String sanitizedSearch = StringValidation.sanitize(search);
            params.put("search", sanitizedSearch);
            params2.put("search", sanitizedSearch);
        } else {
            preFilter = null;
        }

        final String q = "RETURN distinct profileGroup.id as id, profileGroup.name as name, "
                + "profileGroup.groupDisplayName as groupDisplayName, profileGroup.structureName as structureName "
                + "ORDER BY name " + "UNION " + GROUP_SHARED;

        final String q2 = "RETURN distinct visibles.id as id, visibles.login as login, visibles.displayName as username, "
                + "visibles.lastName as lastName, visibles.firstName as firstName, visibles.profiles[0] as profile "
                + "ORDER BY username " + "UNION " + USER_SHARED;

        UserUtils.findVisibleProfilsGroups(eb, userId, q, params, new Handler<JsonArray>() {
            @Override
            public void handle(JsonArray visibleGroups) {
                final JsonObject groups = new JsonObject();
                groups.put("visibles", visibleGroups);
                groups.put("checked", groupCheckedActions);
                for (Object u : visibleGroups) {
                    if (!(u instanceof JsonObject))
                        continue;
                    JsonObject group = (JsonObject) u;
                    UserUtils.groupDisplayName(group, acceptLanguage);
                }
                findVisibleUsers(eb, userId, false, preFilter, q2, params2, new Handler<JsonArray>() {
                    @Override
                    public void handle(JsonArray visibleUsers) {
                        JsonObject users = new JsonObject();
                        users.put("visibles", visibleUsers);
                        users.put("checked", userCheckedActions);
                        JsonObject share = new JsonObject().put("actions", actions).put("groups", groups)
                                .put("users", users);
                        handler.handle(share);
                    }
                });
            }
        });
    }
}

From source file:org.entcore.common.share.impl.GenericShareService.java

License:Open Source License

private void shareValidationVisible(String userId, String resourceId,
        Handler<Either<String, JsonObject>> handler, HashMap<String, Set<String>> membersActions,
        Set<String> shareBookmarkIds) {
    //      final String preFilter = "AND m.id IN {members} ";
    final Set<String> members = membersActions.keySet();
    final JsonObject params = new JsonObject().put("members", new JsonArray(new ArrayList<>(members)));
    //      final String customReturn = "RETURN DISTINCT visibles.id as id, has(visibles.login) as isUser";
    //      UserUtils.findVisibles(eb, userId, customReturn, params, true, true, false, null, preFilter, res -> {
    checkMembers(params, res -> {/*  w w  w.  ja v  a 2  s .com*/
        if (res != null) {
            final JsonArray users = new JsonArray();
            final JsonArray groups = new JsonArray();
            final JsonArray shared = new JsonArray();
            final JsonArray notifyMembers = new JsonArray();
            for (Object o : res) {
                JsonObject j = (JsonObject) o;
                final String attr = j.getString("id");
                if (Boolean.TRUE.equals(j.getBoolean("isUser"))) {
                    users.add(attr);
                    notifyMembers.add(new JsonObject().put("userId", attr));
                    prepareSharedArray(resourceId, "userId", shared, attr, membersActions.get(attr));
                } else {
                    groups.add(attr);
                    notifyMembers.add(new JsonObject().put("groupId", attr));
                    prepareSharedArray(resourceId, "groupId", shared, attr, membersActions.get(attr));
                }
            }
            handler.handle(new Either.Right<>(params.put("shared", shared).put("groups", groups)
                    .put("users", users).put("notify-members", notifyMembers)));
            if (shareBookmarkIds != null && res.size() < members.size()) {
                members.removeAll(groups.getList());
                members.removeAll(users.getList());
                resyncShareBookmark(userId, members, shareBookmarkIds);
            }
        } else {
            handler.handle(new Either.Left<>("Invalid members count."));
        }
    });
}