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

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

Introduction

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

Prototype

public String encode() 

Source Link

Document

Encode this JSON object as a string.

Usage

From source file:org.entcore.common.events.impl.HttpLocalhostEventStore.java

License:Open Source License

@Override
protected void storeEvent(final JsonObject event, final Handler<Either<String, Void>> handler) {
    HttpClientRequest req = httpClient.post("/infra/event/localhost/store", new Handler<HttpClientResponse>() {
        @Override/*from w ww .ja  va  2 s. co m*/
        public void handle(final HttpClientResponse response) {
            if (response.statusCode() == 200) {
                handler.handle(new Either.Right<String, Void>(null));
            } else if (response.statusCode() == 403) {
                handler.handle(new Either.Left<String, Void>(
                        "Error : " + response.statusMessage() + ", Event : " + event.encode()));
            } else {
                response.bodyHandler(new Handler<Buffer>() {
                    @Override
                    public void handle(Buffer b) {
                        if (b.length() > 0) {
                            JsonObject body = new JsonObject(b.toString());
                            handler.handle(new Either.Left<String, Void>(
                                    "Error : " + body.getString("error") + ", Event : " + event.encode()));
                        } else {
                            handler.handle(new Either.Left<String, Void>(
                                    "Error : " + response.statusMessage() + ", Event : " + event.encode()));
                        }
                    }
                });
            }
        }
    });
    req.exceptionHandler(e -> logger.error("Error storing event : " + event.encode(), e));
    req.end(event.encode());
}

From source file:org.entcore.common.events.impl.MongoDbEventStore.java

License:Open Source License

@Override
protected void storeEvent(final JsonObject event, final Handler<Either<String, Void>> handler) {
    mongoDb.insert(COLLECTION, event, new Handler<Message<JsonObject>>() {
        @Override/*w w  w. ja  va 2s  .  c om*/
        public void handle(Message<JsonObject> res) {
            if ("ok".equals(res.body().getString("status"))) {
                handler.handle(new Either.Right<String, Void>(null));
            } else {
                handler.handle(new Either.Left<String, Void>(
                        "Error : " + res.body().getString("message") + ", Event : " + event.encode()));
            }
        }
    });
}

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

License:Open Source License

private void createIndex(final JsonObject j) {
    try {/*from  ww w . j  a va2  s .  c  om*/
        final HttpClientRequest req = nodeManager.getClient().post("/db/data/index/" + j.getString("for"),
                new Handler<HttpClientResponse>() {
                    @Override
                    public void handle(HttpClientResponse event) {
                        if (event.statusCode() != 201) {
                            event.bodyHandler(new Handler<Buffer>() {
                                @Override
                                public void handle(Buffer event) {
                                    logger.error(
                                            "Error creating index : " + j.encode() + " -> " + event.toString());
                                }
                            });
                        }
                    }
                });
        JsonObject body = new JsonObject().put("name", j.getString("name"));
        body.put("config",
                new JsonObject().put("type", j.getString("type", "exact")).put("provider", "lucene"));
        req.exceptionHandler(e -> logger.error("Error creating index : " + j.encode(), e));
        req.end(body.encode());
    } catch (Neo4jConnectionException e) {
        logger.error(e.getMessage(), e);
    }
}

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

License:Open Source License

@Override
public void execute(String query, JsonObject p, final Handler<JsonObject> handler) {
    JsonObject params = p;// w ww.j  a v a  2s .  c o  m
    if (params == null) {
        params = new JsonObject();
    }
    JsonObject body = new JsonObject().put("query", query).put("params", params);
    logger.debug(body.encode());
    try {
        sendRequest("/cypher", body, true, 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"));
                            if (resp.statusCode() == 200) {
                                handler.handle(new JsonObject().put("result", transformJson(json)));
                            } else {
                                handler.handle(json);
                            }
                        } else {
                            handler.handle(new JsonObject().put("message",
                                    resp.statusMessage() + " : " + b.toString()));
                        }
                    }
                });
            }
        });
    } catch (Neo4jConnectionException e) {
        ExceptionUtils.exceptionToJson(e);
    }
}

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

License:Open Source License

private void registerNotification(String fullName, JsonObject notification) {
    log.info("Registering notification : " + fullName);
    sharedMap.put(fullName, notification.encode(), ar -> {
        if (ar.failed()) {
            log.error("Error registering notification : " + fullName, ar.cause());
        }//from   w  ww .  ja  v  a 2  s.co m
    });
}

From source file:org.entcore.common.notification.ws.OssFcm.java

License:Open Source License

public void sendNotifications(final JsonObject message) throws Exception {
    getAccessToken(new Handler<String>() {
        @Override//from ww w .  jav  a2 s .c  om
        public void handle(String token) {
            if (token == null) {
                log.error("[OssFcm] Error get token");
                return;
            }
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-type", "application/json");
            headers.put("Accept-Language", message.getString("language", "fr"));
            client.postProtectedResource(url, token, headers, message.encode(),
                    new Handler<HttpClientResponse>() {
                        @Override
                        public void handle(HttpClientResponse response) {
                            if (response.statusCode() != 200) {
                                log.error("[OssFcm.sendNotifications] request failed : "
                                        + response.statusMessage());
                            }
                        }
                    });

        }
    });
}

From source file:org.entcore.common.user.UserUtils.java

License:Open Source License

public static UserInfos sessionToUserInfos(JsonObject session) {
    if (session == null) {
        return null;
    }/* w w w. j  a  v a 2s  .  co  m*/
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(session.encode(), UserInfos.class);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.entcore.conversation.controllers.ConversationController.java

License:Open Source License

private void timelineNotification(HttpServerRequest request, JsonObject sentMessage, UserInfos user) {
    log.debug(sentMessage.encode());
    JsonArray r = sentMessage.getJsonArray("sentIds");
    String id = sentMessage.getString("id");
    String subject = sentMessage.getString("subject", "<span translate key=\"timeline.no.subject\"></span>");
    sentMessage.remove("sentIds");
    sentMessage.remove("id");
    sentMessage.remove("subject");
    if (r == null || id == null || user == null) {
        return;//w w w  .ja va 2  s.c o m
    }
    final JsonObject params = new JsonObject()
            .put("uri", "/userbook/annuaire#" + user.getUserId() + "#" + user.getType())
            .put("username", user.getUsername()).put("subject", subject)
            .put("messageUri", pathPrefix + "/conversation#/read-mail/" + id);
    params.put("resourceUri", params.getString("messageUri"));
    params.put("pushNotif", new JsonObject().put("title", "push.notif.new.message").put("body",
            user.getUsername() + " : " + sentMessage.getString("body")));
    List<String> recipients = new ArrayList<>();
    String idTmp;
    for (Object o : r) {
        if (!(o instanceof String))
            continue;
        idTmp = (String) o;
        if (!user.getUserId().equals(idTmp))
            recipients.add(idTmp);
    }
    notification.notifyTimeline(request, "messagerie.send-message", user, recipients, id, params);
}

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

License:Open Source License

@Get("/api/person")
@SecuredAction(value = "userbook.authent", type = ActionType.AUTHENTICATED)
public void person(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override//from w w  w.  j av  a  2 s .c  om
        public void handle(final UserInfos user) {
            if (user != null) {
                String hobbyVisibility;
                String personnalInfos;
                Map<String, Object> params = new HashMap<>();
                if (request.params().get("id") == null) {
                    Object person = user.getAttribute(PERSON_ATTRIBUTE);
                    if (person != null) {
                        renderJson(request, new JsonObject(person.toString()));
                        return;
                    }
                    params.put("userId", user.getUserId());
                    hobbyVisibility = "PUBLIC|PRIVE";
                    personnalInfos = "OPTIONAL MATCH u-[r0:SHOW_EMAIL]->() "
                            + "OPTIONAL MATCH u-[r1:SHOW_BIRTHDATE]->() "
                            + "OPTIONAL MATCH u-[r2:SHOW_PHONE]->() " + "OPTIONAL MATCH u-[r3:SHOW_MAIL]->() "
                            + "OPTIONAL MATCH u-[r4:SHOW_HEALTH]->u " + "OPTIONAL MATCH u-[r5:SHOW_MOBILE]->() "
                            + "WITH DISTINCT h, s, c, n, v, u, n2, p, n.address as address, "
                            + "n.email as email, u.health as health, "
                            + "n.homePhone as tel, n.birthDate as birthdate, n.mobile as mobile, "
                            + "COLLECT(distinct [type(r0),type(r1),type(r2),type(r3),type(r4),type(r5)]) as r ";
                } else {
                    params.put("userId", request.params().get("id"));
                    hobbyVisibility = "PUBLIC";
                    personnalInfos = "OPTIONAL MATCH u-[:SHOW_EMAIL]->e " + "OPTIONAL MATCH u-[:SHOW_MAIL]->a "
                            + "OPTIONAL MATCH u-[:SHOW_PHONE]->ph " + "OPTIONAL MATCH u-[:SHOW_MOBILE]->mo "
                            + "OPTIONAL MATCH u-[:SHOW_BIRTHDATE]->b " + "OPTIONAL MATCH u-[:SHOW_HEALTH]->st "
                            + "WITH h, s, c, n, v, u, n2, p, a.address as address, "
                            + "e.email as email, st.health as health, "
                            + "ph.homePhone as tel, b.birthDate as birthdate, mo.mobile as mobile, "
                            + "COLLECT([]) as r ";
                }
                String query = "MATCH (n:User) " + "WHERE n.id = {userId} "
                        + "OPTIONAL MATCH n-[:IN]->(:ProfileGroup)-[:HAS_PROFILE]->(p:Profile) "
                        + "OPTIONAL MATCH n-[:IN]->(:ProfileGroup)-[:DEPENDS]->(s:Structure) "
                        + "OPTIONAL MATCH n-[:IN]->(:ProfileGroup)-[:DEPENDS]->(c:Class)-[:BELONGS]->(s) "
                        + "OPTIONAL MATCH (n)-[:USERBOOK]->(u) " + "OPTIONAL MATCH (u)-[v:" + hobbyVisibility
                        + "]->(h1) " + "OPTIONAL MATCH (n)-[:RELATED]-(n2) "
                        + "WITH DISTINCT h1 as h, s, collect(distinct c.name) as c, n, v, u, n2, p "
                        + personnalInfos
                        + "WITH COLLECT(DISTINCT {name: s.name, id: s.id, classes: c}) as schools, "
                        + "n, u, n2, address, email, health, tel, mobile, birthdate, r,  COLLECT(p.name) as type, "
                        + "COLLECT(DISTINCT {visibility: type(v), category: h.category, values: h.values}) as hobbies "
                        + "RETURN DISTINCT " + "n.id as id," + "n.login as login, "
                        + "n.displayName as displayName," + "type," + "address," + "email, " + "tel, "
                        + "mobile, " + "birthdate, " + "HEAD(r) as visibleInfos, " + "schools, "
                        + "n2.displayName as relatedName, " + "n2.id as relatedId," + "n2.type as relatedType,"
                        + "u.userid as userId," + "u.motto as motto,"
                        + "COALESCE(u.picture, {defaultAvatar}) as photo,"
                        + "COALESCE(u.mood, {defaultMood}) as mood," + "health," + "hobbies";
                params.put("defaultAvatar", userBookData.getString("default-avatar"));
                params.put("defaultMood", userBookData.getString("default-mood"));
                neo.send(query, params, new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> message) {
                        JsonObject r = message.body();
                        if (request.params().get("id") == null) {
                            UserUtils.addSessionAttribute(eb, user.getUserId(), PERSON_ATTRIBUTE, r.encode(),
                                    null);
                        }
                        renderJson(request, r);
                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

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

License:Open Source License

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

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