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.common.http.request.ActionsUtils.java

License:Open Source License

public static void findWorkflowSecureActions(EventBus eb, final HttpServerRequest request,
        Controller controller) {//  www. j  a va  2 s.c o  m
    final Map<String, Set<Binding>> bindings = controller.getSecuredUriBinding();
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {

        @Override
        public void handle(UserInfos user) {
            JsonObject actions = new JsonObject();
            if (user != null) {
                for (UserInfos.Action action : user.getAuthorizedActions()) {
                    if (bindings.containsKey(action.getName())) {
                        JsonArray b = new fr.wseduc.webutils.collections.JsonArray();
                        for (Binding binding : bindings.get(action.getName())) {
                            b.add(new JsonObject().put("verb", binding.getMethod().name())
                                    .put("path", binding.getUriPattern().pattern())
                                    .put("type", binding.getActionType().name()));
                        }
                        actions.put(action.getName(), b);
                    }
                }
            }
            Renders.renderJson(request, actions);
        }
    });
}

From source file:org.entcore.common.neo4j.ExceptionUtils.java

License:Open Source License

public static JsonObject exceptionToJson(Throwable e) {
    JsonArray stacktrace = new fr.wseduc.webutils.collections.JsonArray();
    for (StackTraceElement s : e.getStackTrace()) {
        stacktrace.add(s.toString());
    }//w w w  .  j av  a  2 s  .c  om
    return new JsonObject().put("message", e.getMessage()).put("exception", e.getClass().getSimpleName())
            .put("fullname", e.getClass().getName()).put("stacktrace", stacktrace);
}

From source file:org.entcore.common.neo4j.Neo.java

License:Open Source License

@Deprecated
public static JsonArray resultToJsonArray(JsonObject j) {
    JsonArray r = new fr.wseduc.webutils.collections.JsonArray();
    if (j != null) {
        for (String idx : j.fieldNames()) {
            r.add(j.getJsonObject(idx));
        }/*from  w  ww  .ja  v  a2  s . com*/
    }
    return r;
}

From source file:org.entcore.common.neo4j.Neo4jRest.java

License:Open Source License

@Override
public void executeBatch(JsonArray queries, final Handler<JsonObject> handler) {
    JsonArray body = new fr.wseduc.webutils.collections.JsonArray();
    int i = 0;// w w  w . j  av a 2s  .co  m
    for (Object q : queries) {
        JsonObject query = new JsonObject().put("method", "POST").put("to", "/cypher")
                .put("body", (JsonObject) q).put("id", i++);
        body.add(query);
    }
    logger.debug(body.encode());
    try {
        sendRequest("/batch", body, new Handler<HttpClientResponse>() {
            @Override
            public void handle(final HttpClientResponse resp) {
                resp.bodyHandler(new Handler<Buffer>() {

                    @Override
                    public void handle(Buffer b) {
                        logger.debug(b.toString());
                        if (resp.statusCode() != 404 && resp.statusCode() != 500) {
                            JsonArray json = new fr.wseduc.webutils.collections.JsonArray(b.toString("UTF-8"));
                            JsonArray out = new fr.wseduc.webutils.collections.JsonArray();
                            for (Object j : json) {
                                JsonObject qr = (JsonObject) j;
                                out.add(new JsonObject()
                                        .put("result",
                                                transformJson(qr.getJsonObject("body", new JsonObject())))
                                        .put("idx", qr.getLong("id")));
                            }
                            handler.handle(new JsonObject().put("results", out));
                        } else {
                            handler.handle(new JsonObject().put("message",
                                    resp.statusMessage() + " : " + b.toString()));
                        }
                    }
                });
            }
        });
    } catch (Neo4jConnectionException e) {
        ExceptionUtils.exceptionToJson(e);
    }
}

From source file:org.entcore.common.neo4j.Neo4jRest.java

License:Open Source License

public void executeTransaction(final JsonArray statements, final Integer transactionId, final boolean commit,
        final boolean allowRetry, final Handler<JsonObject> handler) {
    String uri = "/transaction";
    if (transactionId != null) {
        uri += "/" + transactionId;
    }//from ww w  . ja v  a2s . com
    if (commit) {
        uri += "/commit";
    }
    try {
        sendRequest(uri, new JsonObject().put("statements", statements), new Handler<HttpClientResponse>() {
            @Override
            public void handle(final HttpClientResponse resp) {
                resp.bodyHandler(new Handler<Buffer>() {

                    @Override
                    public void handle(Buffer b) {
                        logger.debug(b.toString());
                        if (resp.statusCode() != 404 && resp.statusCode() != 500) {
                            JsonObject json = new JsonObject(b.toString("UTF-8"));
                            JsonArray results = json.getJsonArray("results");
                            if (json.getJsonArray("errors", new fr.wseduc.webutils.collections.JsonArray())
                                    .size() == 0 && results != null) {
                                JsonArray out = new fr.wseduc.webutils.collections.JsonArray();
                                for (Object o : results) {
                                    if (!(o instanceof JsonObject))
                                        continue;
                                    out.add(transformJson((JsonObject) o));
                                }
                                json.put("results", out);
                                String commit = json.getString("commit");
                                if (commit != null) {
                                    String[] c = commit.split("/");
                                    if (c.length > 2) {
                                        json.put("transactionId", Integer.parseInt(c[c.length - 2]));
                                    }
                                }
                                json.remove("errors");
                                handler.handle(json);
                            } else {
                                if (transactionId == null && commit && allowRetry
                                        && json.getJsonArray("errors") != null
                                        && json.getJsonArray("errors").size() > 0) {
                                    JsonArray errors = json.getJsonArray("errors");
                                    for (Object o : errors) {
                                        if (!(o instanceof JsonObject))
                                            continue;
                                        switch (((JsonObject) o).getString("code", "")) {
                                        case "Neo.TransientError.Transaction.ConstraintsChanged":
                                        case "Neo.TransientError.Transaction.DeadlockDetected":
                                        case "Neo.TransientError.Transaction.InstanceStateChanged":
                                        case "Neo.TransientError.Schema.SchemaModifiedConcurrently":
                                            executeTransaction(statements, transactionId, commit, false,
                                                    handler);
                                            if (logger.isDebugEnabled()) {
                                                logger.debug("Retry transaction : " + statements.encode());
                                            }
                                            return;
                                        }
                                    }
                                }
                                handler.handle(
                                        new JsonObject().put("message",
                                                json.getJsonArray("errors",
                                                        new fr.wseduc.webutils.collections.JsonArray())
                                                        .encode()));
                            }
                        } else {
                            handler.handle(new JsonObject().put("message",
                                    resp.statusMessage() + " : " + b.toString()));
                        }
                    }
                });
            }
        });
    } catch (Neo4jConnectionException e) {
        ExceptionUtils.exceptionToJson(e);
    }
}

From source file:org.entcore.common.neo4j.Neo4jRest.java

License:Open Source License

private JsonArray transformJson(JsonObject json) {
    final JsonArray columns = json.getJsonArray("columns");
    final JsonArray data = json.getJsonArray("data");
    final JsonArray out = new fr.wseduc.webutils.collections.JsonArray();

    if (data != null && columns != null) {
        for (Object r : data) {
            JsonArray row;/*  w  w  w  . j a v  a2s .co  m*/
            if (r instanceof JsonArray) {
                row = (JsonArray) r;
            } else if (r instanceof JsonObject) {
                row = ((JsonObject) r).getJsonArray("row");
            } else {
                continue;
            }
            JsonObject outRow = new fr.wseduc.webutils.collections.JsonObject();
            out.add(outRow);
            for (int j = 0; j < row.size(); j++) {
                Object value = row.getValue(j);
                if (value == null) {
                    outRow.put(columns.getString(j), (String) null);
                } else if (value instanceof String) {
                    outRow.put(columns.getString(j), (String) value);
                } else if (value instanceof JsonArray) {
                    outRow.put(columns.getString(j), (JsonArray) value);
                } else if (value instanceof JsonObject) {
                    outRow.put(columns.getString(j), (JsonObject) value);
                } else if (value instanceof Boolean) {
                    outRow.put(columns.getString(j), (Boolean) value);
                } else if (value instanceof Number) {
                    outRow.put(columns.getString(j), (Number) value);
                } else {
                    outRow.put(columns.getString(j), value.toString());
                }
            }
        }
    }
    return out;
}

From source file:org.entcore.common.neo4j.Neo4jResult.java

License:Open Source License

public static Either<String, JsonObject> fullNodeMerge(String nodeAttr, Message<JsonObject> res,
        String... otherNodes) {//from w ww  . ja va2s  .co m
    Either<String, JsonObject> r = validUniqueResult(res);
    if (r.isRight() && r.right().getValue().size() > 0) {
        JsonObject j = r.right().getValue();
        JsonObject data = j.getJsonObject(nodeAttr, new JsonObject()).getJsonObject("data");
        if (otherNodes != null && otherNodes.length > 0) {
            for (String attr : otherNodes) {
                Object e = j.getValue(attr);
                if (e == null)
                    continue;
                if (e instanceof JsonObject) {
                    data.put(attr, ((JsonObject) e).getJsonObject("data"));
                } else if (e instanceof JsonArray) {
                    JsonArray a = new fr.wseduc.webutils.collections.JsonArray();
                    for (Object o : (JsonArray) e) {
                        if (!(o instanceof JsonObject))
                            continue;
                        JsonObject jo = (JsonObject) o;
                        a.add(jo.getJsonObject("data"));
                    }
                    data.put(attr, a);
                }
                j.remove(attr);
            }
        }
        if (data != null) {
            j.remove(nodeAttr);
            return new Either.Right<>(data.mergeIn(j));
        }
    }
    return r;
}

From source file:org.entcore.common.neo4j.Neo4jUtils.java

License:Open Source License

private static void loadAndExecute(final String schema, final Vertx vertx, final String path,
        final boolean index, final JsonArray excludeFileNames) {
    final String pattern = index ? ".*?-index\\.cypher$" : "^(?!.*-index).*?\\.cypher$";
    vertx.fileSystem().readDir(path, pattern, new Handler<AsyncResult<List<String>>>() {
        @Override/*from   ww  w .j  a  v a2  s . c o  m*/
        public void handle(AsyncResult<List<String>> asyncResult) {
            if (asyncResult.succeeded()) {
                final List<String> files = asyncResult.result();
                Collections.sort(files);
                final StatementsBuilder s = new StatementsBuilder();
                final JsonArray newFiles = new fr.wseduc.webutils.collections.JsonArray();
                final AtomicInteger count = new AtomicInteger(files.size());
                for (final String f : files) {
                    final String filename = f.substring(f.lastIndexOf(File.separatorChar) + 1);
                    if (!excludeFileNames.contains(filename)) {
                        vertx.fileSystem().readFile(f, new Handler<AsyncResult<Buffer>>() {
                            @Override
                            public void handle(AsyncResult<Buffer> bufferAsyncResult) {
                                if (bufferAsyncResult.succeeded()) {
                                    String script = bufferAsyncResult.result().toString();
                                    for (String q : script.replaceAll("(\r|\n)", " ").split(";")) {
                                        s.add(q);
                                    }
                                    newFiles.add(filename);
                                } else {
                                    log.error("Error reading file : " + f, bufferAsyncResult.cause());
                                }
                                if (count.decrementAndGet() == 0) {
                                    commit(schema, s, newFiles, index);
                                }
                            }
                        });
                    } else if (count.decrementAndGet() == 0 && newFiles.size() > 0) {
                        commit(schema, s, newFiles, index);
                    }
                }
            } else if (log.isDebugEnabled()) {
                log.debug("Error reading neo4j directory : " + path, asyncResult.cause());
            }
        }

        private void commit(final String schema, StatementsBuilder s, final JsonArray newFiles,
                final boolean index) {
            final JsonObject params = new JsonObject().put("appName", schema).put("newFiles", newFiles);
            if (!index) {
                s.add(UPDATE_SCRIPTS, params);
            }
            Neo4j.getInstance().executeTransaction(s.build(), null, true, new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> message) {
                    if ("ok".equals(message.body().getString("status"))) {
                        if (index) {
                            Neo4j.getInstance().execute(UPDATE_SCRIPTS, params,
                                    new Handler<Message<JsonObject>>() {
                                        @Override
                                        public void handle(Message<JsonObject> event) {
                                            if (!"ok".equals(event.body().getString("status"))) {
                                                log.error("Error update scripts : "
                                                        + event.body().getString("message"));
                                            }
                                        }
                                    });
                        }
                        log.info("Scripts added : " + newFiles.encode());
                    } else {
                        log.error("Error when commit transaction : " + message.body().getString("message"));
                    }
                }
            });
        }
    });
}

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

License:Open Source License

public void notify(final HttpServerRequest request, String from, JsonArray to, JsonArray cc, String subject,
        String message, final Handler<Either<String, JsonObject>> result) {
    if (cc == null) {
        cc = new fr.wseduc.webutils.collections.JsonArray();
    }//from   w  ww .  j  a  v a 2 s  .com
    if (subject == null || message == null || to == null || from == null) {
        result.handle(new Either.Left<String, JsonObject>("Conversation notification : invalid parameters"));
        log.warn("Conversation notification : invalid parameters");
        return;
    }
    JsonArray dest = to.copy();
    for (Object o : cc) {
        dest.add(o);
    }
    String language = I18n.acceptLanguage(request);
    if (language == null || language.trim().isEmpty()) {
        language = "fr";
    } else {
        String[] langs = language.split(",");
        language = langs[0];
    }
    String displayName = i18n.translate("no-reply", Renders.getHost(request), language);
    final JsonObject m = new JsonObject()
            .put("message",
                    new JsonObject().put("to", to).put("cc", cc).put("subject", subject).put("body", message))
            .put("action", "send").put("userId", "no-reply-" + language).put("username", displayName)
            .put("request", new JsonObject().put("path", request.path()).put("headers",
                    new JsonObject().put("Accept-Language", I18n.acceptLanguage(request))));
    String query = "MATCH (u:User { id : {noReplyId}}) " + "WITH count(*) as exists " + "WHERE exists = 0 "
            + "CREATE (u:User:Visible {id : {noReplyId}, displayName : {noReplyName}})";
    JsonObject params = new JsonObject().put("noReplyName", displayName)
            .put("noReplyId", "no-reply-" + language).put("dest", dest);
    StatementsBuilder sb = new StatementsBuilder().add(query, params);
    sb.add("MATCH (dest:User), (u:User {id : {noReplyId}}) " + "WHERE dest.id IN {dest} "
            + "CREATE UNIQUE u-[:COMMUNIQUE_DIRECT]->dest ", params);
    neo.executeTransaction(sb.build(), null, true, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            if ("ok".equals(message.body().getString("status"))) {
                eb.send(CONVERSATION_ADDRESS, m,
                        handlerToAsyncHandler(Neo4jResult.validUniqueResultHandler(result)));
            } else {
                result.handle(new Either.Left<String, JsonObject>(message.body().getString("message")));
            }
        }
    });
}

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 w w .ja  va2 s .  c o  m*/
        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"));
                }
            }
        }));
    });
}