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

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

Introduction

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

Prototype

public String getString(String key) 

Source Link

Document

Get the string value with the specified key, special cases are addressed for extended JSON types Instant , byte[] and Enum which can be converted to String.

Usage

From source file:org.entcore.conversation.filters.VisiblesFilter.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void authorize(HttpServerRequest request, Binding binding, final UserInfos user,
        final Handler<Boolean> handler) {

    final String parentMessageId = request.params().get("In-Reply-To");
    final Set<String> ids = new HashSet<>();
    final String customReturn = "WHERE visibles.id IN {ids} RETURN DISTINCT visibles.id";
    final JsonObject params = new JsonObject();

    RequestUtils.bodyToJson(request, new Handler<JsonObject>() {
        public void handle(final JsonObject message) {
            ids.addAll(message.getJsonArray("to", new fr.wseduc.webutils.collections.JsonArray()).getList());
            ids.addAll(message.getJsonArray("cc", new fr.wseduc.webutils.collections.JsonArray()).getList());

            final Handler<Void> checkHandler = new Handler<Void>() {
                public void handle(Void v) {
                    params.put("ids", new fr.wseduc.webutils.collections.JsonArray(new ArrayList<>(ids)));
                    findVisibles(neo.getEventBus(), user.getUserId(), customReturn, params, true, true, false,
                            new Handler<JsonArray>() {
                                public void handle(JsonArray visibles) {
                                    handler.handle(visibles.size() == ids.size());
                                }/*  w  w  w .  j  a va 2 s. c  om*/
                            });
                }
            };

            if (parentMessageId == null || parentMessageId.trim().isEmpty()) {
                checkHandler.handle(null);
                return;
            }

            sql.prepared("SELECT m.*  " + "FROM conversation.messages m " + "WHERE m.id = ?",
                    new fr.wseduc.webutils.collections.JsonArray().add(parentMessageId),
                    SqlResult.validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                        public void handle(Either<String, JsonObject> parentMsgEvent) {
                            if (parentMsgEvent.isLeft()) {
                                handler.handle(false);
                                return;
                            }

                            JsonObject parentMsg = parentMsgEvent.right().getValue();
                            ids.remove(parentMsg.getString("from"));
                            ids.removeAll(
                                    parentMsg.getJsonArray("to", new fr.wseduc.webutils.collections.JsonArray())
                                            .getList());
                            ids.removeAll(
                                    parentMsg.getJsonArray("cc", new fr.wseduc.webutils.collections.JsonArray())
                                            .getList());

                            checkHandler.handle(null);
                        }
                    }, "cc", "to"));
        }
    });

}

From source file:org.entcore.conversation.service.impl.DefaultConversationService.java

License:Open Source License

private void addDisplayNames(final JsonObject message, final Handler<JsonObject> handler) {
    String query = "MATCH (v:Visible) " + "WHERE v.id IN {ids} "
            + "RETURN COLLECT(distinct (v.id + '$' + coalesce(v.displayName, ' ') + '$' + "
            + "coalesce(v.name, ' ') + '$' + coalesce(v.groupDisplayName, ' '))) as displayNames ";
    Set<String> ids = new HashSet<>();
    ids.addAll(message.getJsonArray("to", new fr.wseduc.webutils.collections.JsonArray()).getList());
    ids.addAll(message.getJsonArray("cc", new fr.wseduc.webutils.collections.JsonArray()).getList());
    if (message.containsKey("from")) {
        ids.add(message.getString("from"));
    }/*from  w ww .  ja v a  2  s.c o  m*/
    neo.execute(query,
            new JsonObject().put("ids", new fr.wseduc.webutils.collections.JsonArray(new ArrayList<>(ids))),
            new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> m) {
                    JsonArray r = m.body().getJsonArray("result");
                    if ("ok".equals(m.body().getString("status")) && r != null && r.size() == 1) {
                        JsonObject j = r.getJsonObject(0);
                        JsonArray d = j.getJsonArray("displayNames");
                        if (d != null && d.size() > 0) {
                            message.put("displayNames", d);
                        }
                    }
                    handler.handle(message);
                }
            });
}

From source file:org.entcore.conversation.service.impl.DefaultConversationService.java

License:Open Source License

private boolean displayNamesCondition(JsonObject message) {
    return message != null && ((message.containsKey("from") && !message.getString("from").trim().isEmpty())
            || (message.containsKey("to") && message.getJsonArray("to").size() > 0)
            || (message.containsKey("cc") && message.getJsonArray("cc").size() > 0));
}

From source file:org.entcore.conversation.service.impl.DefaultConversationService.java

License:Open Source License

private void sendWithAttachments(final String parentMessageId, final String messageId, JsonArray attachments,
        final UserInfos user, final Handler<Either<String, JsonObject>> result) {
    long totalAttachmentsSize = 0l;
    for (Object o : attachments) {
        totalAttachmentsSize = totalAttachmentsSize + ((JsonObject) o).getLong("size", 0l);
    }//www.  j  a  va  2s.c  o m

    final String usersQuery;
    JsonObject params = new JsonObject().put("userId", user.getUserId()).put("messageId", messageId)
            .put("draft", State.DRAFT.name()).put("outbox", "OUTBOX").put("inbox", "INBOX")
            .put("sent", State.SENT.name()).put("attachmentsSize", totalAttachmentsSize).put("true", true);
    if (parentMessageId != null && !parentMessageId.trim().isEmpty()) { // reply
        usersQuery = "MATCH (m:ConversationMessage { id : {parentMessageId}}) "
                + "WITH (COLLECT(visibles.id) + coalesce(m.to, '') + coalesce(m.cc, '') + coalesce(m.from, '')) as vis "
                + "MATCH (v:Visible) " + "WHERE v.id IN vis " + "WITH DISTINCT v ";
        params.put("parentMessageId", parentMessageId);
    } else {
        usersQuery = "WITH visibles as v ";
    }

    String query = usersQuery
            + "MATCH v<-[:IN*0..1]-(u:User), (message:ConversationMessage)-[:HAS_ATTACHMENT]->(attachment: MessageAttachment) "
            + "WHERE (v: User or v:Group) "
            + "AND message.id = {messageId} AND message.state = {draft} AND message.from = {userId} AND "
            + "(v.id IN message.to OR v.id IN message.cc) "
            + "WITH DISTINCT u, message, (v.id + '$' + coalesce(v.displayName, ' ') + '$' + "
            + "coalesce(v.name, ' ') + '$' + coalesce(v.groupDisplayName, ' ')) as dNames, COLLECT(distinct attachment.id) as attachments "
            + "MATCH (ub: UserBook)<-[:USERBOOK]-(u)-[:HAS_CONVERSATION]->(c:Conversation {active:{true}})"
            + "-[:HAS_CONVERSATION_FOLDER]->(f:ConversationSystemFolder {name:{inbox}}) "
            + "WHERE (ub.quota - ub.storage) >= {attachmentsSize} "
            + "CREATE UNIQUE f-[:HAS_CONVERSATION_MESSAGE { unread: {true}, attachments: attachments }]->message "
            + "SET ub.storage = ub.storage + {attachmentsSize} "
            + "WITH message, COLLECT(c.userId) as sentIds, COLLECT(distinct u) as users, "
            + "COLLECT(distinct dNames) as displayNames "
            + "MATCH (s:User {id : {userId}})-[:HAS_CONVERSATION]->(:Conversation)"
            + "-[:HAS_CONVERSATION_FOLDER]->(fOut:ConversationSystemFolder {name : {outbox}}), "
            + "message<-[r:HAS_CONVERSATION_MESSAGE]-(fDraft:ConversationSystemFolder {name : {draft}}) "
            + "SET message.state = {sent}, "
            + "message.displayNames = displayNames + (s.id + '$' + coalesce(s.displayName, ' ') + '$ $ ') "
            + "CREATE UNIQUE fOut-[:HAS_CONVERSATION_MESSAGE { insideFolder: r.insideFolder, attachments: r.attachments }]->message "
            + "DELETE r " + "RETURN sentIds, message.id as id";

    findVisibles(eb, user.getUserId(), query, params, true, true, false, new Handler<JsonArray>() {
        @Override
        public void handle(JsonArray event) {
            if (event != null && event.size() == 1 && (event.getValue(0) instanceof JsonObject)) {

                JsonObject resultObj = event.getJsonObject(0);
                JsonArray sentIds = resultObj.getJsonArray("sentIds");
                String messageId = resultObj.getString("id");

                String query = usersQuery + "MATCH v<-[:IN*0..1]-(u:User), (message:ConversationMessage) "
                        + "WHERE (v: User or v:Group) "
                        + "AND message.id = {messageId} AND message.from = {userId} AND "
                        + "(v.id IN message.to OR v.id IN message.cc) "
                        + "RETURN EXTRACT(user IN FIlTER(x IN COLLECT(u) WHERE NOT(x.id IN {sentIds}))|user.displayName) as undelivered, {sentIds} as sentIds, [] as inactive, "
                        + "{sentIdsLength} as sent, message.id as id, message.subject as subject";

                JsonObject params = new JsonObject().put("userId", user.getUserId()).put("messageId", messageId)
                        .put("sentIds", sentIds).put("sentIdsLength", sentIds.size());
                if (parentMessageId != null && !parentMessageId.trim().isEmpty()) {
                    params.put("parentMessageId", parentMessageId);
                }

                findVisibles(eb, user.getUserId(), query, params, true, true, false, new Handler<JsonArray>() {
                    @Override
                    public void handle(JsonArray event) {
                        if (event != null && event.size() == 1 && (event.getValue(0) instanceof JsonObject)) {
                            result.handle(new Either.Right<String, JsonObject>(event.getJsonObject(0)));
                        } else {
                            result.handle(new Either.Left<String, JsonObject>("conversation.send.error"));
                        }
                    }
                });
            } else {
                result.handle(new Either.Left<String, JsonObject>("conversation.send.error"));
            }
        }
    });
}

From source file:org.entcore.conversation.service.impl.DefaultConversationService.java

License:Open Source License

@Override
public void findVisibleRecipients(final String parentMessageId, final UserInfos user,
        final String acceptLanguage, String search, final Handler<Either<String, JsonObject>> result) {
    if (validationParamsError(user, result))
        return;/*w  w w .ja  va 2s .  c  o m*/
    final JsonObject visible = new JsonObject();
    String replyGroupQuery;
    final JsonObject params = new JsonObject();
    if (parentMessageId != null && !parentMessageId.trim().isEmpty()) {
        params.put("conversation", applicationName);
        replyGroupQuery = ", (m:ConversationMessage)<-[:HAS_CONVERSATION_MESSAGE]-f"
                + "<-[:HAS_CONVERSATION_FOLDER]-(c:Conversation) "
                + "WHERE m.id = {parentMessageId} AND c.userId = {userId} "
                + "AND (pg.id = visibles.id OR pg.id IN m.to OR pg.id IN m.cc) ";
        params.put("userId", user.getUserId()).put("parentMessageId", parentMessageId);
        String groups = "MATCH (app:Application)-[:PROVIDE]->(a:Action)<-[:AUTHORIZE]-(r:Role)"
                + "<-[:AUTHORIZED]-(g:Group)<-[:DEPENDS*0..1]-(pg:Group) " + replyGroupQuery
                + " AND app.name = {conversation} "
                + "RETURN DISTINCT pg.id as id, pg.name as name, pg.groupDisplayName as groupDisplayName, pg.structureName as structureName ";
        findVisibles(eb, user.getUserId(), groups, params, false, true, false, acceptLanguage,
                new Handler<JsonArray>() {
                    @Override
                    public void handle(JsonArray visibleGroups) {
                        visible.put("groups", visibleGroups);
                        String replyUserQuery;
                        replyUserQuery = ", (m:ConversationMessage)<-[:HAS_CONVERSATION_MESSAGE]-f"
                                + "<-[:HAS_CONVERSATION_FOLDER]-(c:Conversation) "
                                + "WHERE m.id = {parentMessageId} AND c.userId = {userId} "
                                + "AND (u.id = visibles.id OR u.id IN m.to OR u.id IN m.cc) ";
                        String users = "MATCH (app:Application)-[:PROVIDE]->(a:Action)<-[:AUTHORIZE]-(r:Role)"
                                + "<-[:AUTHORIZED]-(pg:Group)<-[:IN]-(u:User) " + replyUserQuery
                                + "AND app.name = {conversation} "
                                + "RETURN DISTINCT u.id as id, u.displayName as displayName, "
                                + "visibles.profiles[0] as profile";
                        findVisibleUsers(eb, user.getUserId(), true, true, users, params,
                                new Handler<JsonArray>() {
                                    @Override
                                    public void handle(JsonArray visibleUsers) {
                                        visible.put("users", visibleUsers);
                                        result.handle(new Either.Right<String, JsonObject>(visible));
                                    }
                                });
                    }
                });
    } else {
        params.put("true", true);
        String groups = "MATCH visibles<-[:IN*0..1]-(u:User)-[:HAS_CONVERSATION]->(c:Conversation {active:{true}}) "
                + "RETURN DISTINCT visibles.id as id, visibles.name as name, "
                + "visibles.displayName as displayName, visibles.groupDisplayName as groupDisplayName, "
                + "visibles.profiles[0] as profile, visibles.structureName as structureName";
        findVisibles(eb, user.getUserId(), groups, params, true, true, false, new Handler<JsonArray>() {
            @Override
            public void handle(JsonArray visibles) {
                JsonArray users = new fr.wseduc.webutils.collections.JsonArray();
                JsonArray groups = new fr.wseduc.webutils.collections.JsonArray();
                visible.put("groups", groups).put("users", users);
                for (Object o : visibles) {
                    if (!(o instanceof JsonObject))
                        continue;
                    JsonObject j = (JsonObject) o;
                    if (j.getString("name") != null) {
                        j.remove("displayName");
                        UserUtils.groupDisplayName(j, acceptLanguage);
                        groups.add(j);
                    } else {
                        j.remove("name");
                        users.add(j);
                    }
                }
                result.handle(new Either.Right<String, JsonObject>(visible));
            }
        });
    }
}

From source file:org.entcore.conversation.service.impl.DefaultConversationService.java

License:Open Source License

@Override
public void updateFolder(String folderId, JsonObject data, UserInfos user,
        Handler<Either<String, JsonObject>> result) {
    final String name = data.getString("name");

    JsonObject params = new JsonObject().put("userId", user.getUserId()).put("true", true).put("targetId",
            folderId);/*  www.  j a  v  a 2s  .  c  o m*/

    if (name != null && name.trim().length() > 0) {
        params.put("newName", name);
    }

    String query = "MATCH (c:Conversation)-[:HAS_CONVERSATION_FOLDER]->(f:ConversationUserFolder)"
            + "-[:HAS_CHILD_FOLDER*0.." + (maxFolderDepth - 1) + "]->(target: ConversationUserFolder) "
            + "WHERE c.userId = {userId} AND c.active = {true} AND target.id = {targetId}"
            + "SET target.name = {newName}";

    neo.execute(query, params, validEmptyHandler(result));
}

From source file:org.entcore.conversation.service.impl.DefaultConversationService.java

License:Open Source License

@Override
public void addAttachment(String messageId, UserInfos user, JsonObject uploaded,
        Handler<Either<String, JsonObject>> result) {
    if (validationParamsError(user, result, messageId))
        return;/*from w w  w.jav  a  2 s . c  o  m*/

    String query = "MATCH (m:ConversationMessage)<-[r:HAS_CONVERSATION_MESSAGE]-(f:ConversationSystemFolder)"
            + "<-[:HAS_CONVERSATION_FOLDER]-(c:Conversation) "
            + "WHERE m.id = {messageId} AND c.userId = {userId} AND c.active = {true} AND m.state = {draft} "
            + "CREATE (m)-[:HAS_ATTACHMENT]->(attachment: MessageAttachment {attachmentProps}) "
            + "SET r.attachments = coalesce(r.attachments, []) + {fileId} " + "RETURN attachment.id as id";

    JsonObject params = new JsonObject().put("userId", user.getUserId()).put("messageId", messageId)
            .put("attachmentProps",
                    new JsonObject().put("id", uploaded.getString("_id"))
                            .put("name", uploaded.getJsonObject("metadata").getString("name"))
                            .put("filename", uploaded.getJsonObject("metadata").getString("filename"))
                            .put("contentType", uploaded.getJsonObject("metadata").getString("content-type"))
                            .put("contentTransferEncoding",
                                    uploaded.getJsonObject("metadata").getString("content-transfer-encoding"))
                            .put("charset", uploaded.getJsonObject("metadata").getString("charset"))
                            .put("size", uploaded.getJsonObject("metadata").getLong("size")))
            .put("fileId", uploaded.getString("_id")).put("true", true).put("trash", "TRASH")
            .put("draft", "DRAFT");

    neo.execute(query, params, validUniqueResultHandler(result));
}

From source file:org.entcore.conversation.service.impl.DeleteOrphan.java

License:Open Source License

@Override
public void handle(Long event) {
    final Sql sql = Sql.getInstance();
    final SqlStatementsBuilder builder = new SqlStatementsBuilder();
    builder.raw(DELETE_ORPHAN_MESSAGE);// ww  w. j  a  v a  2  s. c  om
    builder.raw(SELECT_ORPHAN_ATTACHMENT);
    sql.transaction(builder.build(), new DeliveryOptions().setSendTimeout(TIMEOUT),
            SqlResult.validResultHandler(1, new Handler<Either<String, JsonArray>>() {
                @Override
                public void handle(Either<String, JsonArray> res) {
                    if (res.isRight()) {
                        log.info("Successful delete orphan conversation messages.");
                        final JsonArray attachments = res.right().getValue();
                        if (attachments != null && attachments.size() > 0) {
                            log.info("Orphan attachments : " + attachments.encode());
                            JsonArray ids = new fr.wseduc.webutils.collections.JsonArray();
                            for (Object attObj : attachments) {
                                if (!(attObj instanceof JsonObject))
                                    continue;
                                JsonObject unusedAttachment = (JsonObject) attObj;
                                final String attachmentId = unusedAttachment.getString("orphanid");
                                ids.add(attachmentId);
                                storage.removeFile(attachmentId, new Handler<JsonObject>() {
                                    public void handle(JsonObject event) {
                                        if (!"ok".equals(event.getString("status"))) {
                                            log.error("Error while tying to delete attachment file (_id: {"
                                                    + attachmentId + "})");
                                        }
                                    }
                                });
                            }
                            final String deletOrphanAttachments = "delete from conversation.attachments where id IN "
                                    + Sql.listPrepared(ids.getList());
                            sql.prepared(deletOrphanAttachments, ids,
                                    new DeliveryOptions().setSendTimeout(TIMEOUT),
                                    new Handler<Message<JsonObject>>() {
                                        @Override
                                        public void handle(Message<JsonObject> event) {
                                            if (!"ok".equals(event.body().getString("status"))) {
                                                log.error("Error deleting orphan attachments : "
                                                        + event.body().getString("message", ""));
                                            } else {
                                                log.info("Successful delete orphan conversation attachments.");
                                            }
                                        }
                                    });
                        }
                    } else {
                        log.error("Orphan conversation error : " + res.left().getValue());
                    }
                }
            }));
}

From source file:org.entcore.conversation.service.impl.Neo4jConversationService.java

License:Open Source License

public void addDisplayNames(final JsonObject message, final JsonObject parentMessage,
        final Handler<JsonObject> handler) {
    if (!displayNamesCondition(message)) {
        handler.handle(message);/*from w  ww  . ja  va2  s.  c o m*/
        return;
    }

    String query = "MATCH (v:Visible) " + "WHERE v.id IN {ids} "
            + "RETURN COLLECT(distinct (v.id + '$' + coalesce(v.displayName, ' ') + '$' + "
            + "coalesce(v.name, ' ') + '$' + coalesce(v.groupDisplayName, ' '))) as displayNames ";

    Set<String> ids = new HashSet<>();
    ids.addAll(message.getJsonArray("to", new fr.wseduc.webutils.collections.JsonArray()).getList());
    ids.addAll(message.getJsonArray("cc", new fr.wseduc.webutils.collections.JsonArray()).getList());
    if (message.containsKey("from")) {
        ids.add(message.getString("from"));
    }
    if (parentMessage != null) {
        ids.addAll(parentMessage.getJsonArray("to", new fr.wseduc.webutils.collections.JsonArray()).getList());
        ids.addAll(parentMessage.getJsonArray("cc", new fr.wseduc.webutils.collections.JsonArray()).getList());
        if (parentMessage.containsKey("from"))
            ids.add(parentMessage.getString("from"));
    }
    neo.execute(query,
            new JsonObject().put("ids", new fr.wseduc.webutils.collections.JsonArray(new ArrayList<>(ids))),
            new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> m) {
                    JsonArray r = m.body().getJsonArray("result");
                    if ("ok".equals(m.body().getString("status")) && r != null && r.size() == 1) {
                        JsonObject j = r.getJsonObject(0);
                        JsonArray d = j.getJsonArray("displayNames");
                        if (d != null && d.size() > 0) {
                            message.put("displayNames", d);
                        }
                    }
                    handler.handle(message);
                }
            });
}

From source file:org.entcore.conversation.service.impl.SqlConversationService.java

License:Open Source License

private void save(String parentMessageId, String threadId, JsonObject message, UserInfos user,
        Handler<Either<String, JsonObject>> result) {
    message.put("id", UUID.randomUUID().toString()).put("from", user.getUserId())
            .put("date", System.currentTimeMillis()).put("state", State.DRAFT.name());

    JsonObject m = Utils.validAndGet(message, MESSAGE_FIELDS, DRAFT_REQUIRED_FIELDS);
    if (validationError(user, m, result))
        return;/*from ww  w. ja  v a2s.c om*/

    SqlStatementsBuilder builder = new SqlStatementsBuilder();

    if (parentMessageId != null)
        message.put("parent_id", parentMessageId);

    if (threadId != null) {
        message.put("thread_id", threadId);
    } else {
        message.put("thread_id", message.getString("id"));
    }

    // 1 - Insert message
    builder.insert(messageTable, message, "id");

    // 2 - Link message to the user
    builder.insert(userMessageTable,
            new JsonObject().put("user_id", user.getUserId()).put("message_id", message.getString("id")));

    sql.transaction(builder.build(), SqlResult.validUniqueResultHandler(0, result));
}