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

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

Introduction

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

Prototype

public JsonObject getJsonObject(String key) 

Source Link

Document

Get the JsonObject value with the specified key

Usage

From source file:org.entcore.blog.security.BlogResourcesProvider.java

License:Open Source License

private void hasRightOnPost(final HttpServerRequest request, final UserInfos user,
        final Handler<Boolean> handler, String action) {
    String postId = request.params().get("postId");
    if (StringUtils.isEmpty(postId)) {
        handler.handle(false);//  ww  w  . j a v  a2s.c o  m
        return;
    }
    //
    QueryBuilder query = QueryBuilder.start("_id").is(postId);
    request.pause();
    mongo.findOne("posts", MongoQueryBuilder.build(query), null, new JsonArray().add("blog"),
            new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> event) {
                    request.resume();
                    if ("ok".equals(event.body().getString("status"))) {
                        JsonObject res = event.body().getJsonObject("result");
                        if (res == null) {
                            handler.handle(false);
                            return;
                        }
                        /**
                         * Is author?
                         */
                        if (res.getJsonObject("author") != null
                                && user.getUserId().equals(res.getJsonObject("author").getString("userId"))) {
                            handler.handle(true);
                            return;
                        }
                        if (res.getJsonObject("blog") != null
                                && res.getJsonObject("blog").getJsonArray("shared") != null) {
                            /**
                             * is author?
                             */
                            String blogAuthorId = res.getJsonObject("blog")
                                    .getJsonObject("author", new JsonObject()).getString("userId");
                            if (blogAuthorId != null && blogAuthorId.equals(user.getUserId())) {
                                handler.handle(true);
                                return;
                            }
                            /**
                             * has right action?
                             */
                            for (Object o : res.getJsonObject("blog").getJsonArray("shared")) {
                                if (!(o instanceof JsonObject))
                                    continue;
                                JsonObject json = (JsonObject) o;
                                if (json != null && json.getBoolean(action, false)
                                        && (user.getUserId().equals(json.getString("userId"))
                                                || user.getGroupsIds().contains(json.getString("groupId")))) {
                                    handler.handle(true);
                                    return;
                                }
                            }
                        }
                        handler.handle(false);
                    }
                }
            });
}

From source file:org.entcore.blog.services.impl.DefaultBlogTimelineService.java

License:Open Source License

@Override
public void notifyShare(final HttpServerRequest request, final String blogId, final UserInfos user,
        final JsonArray sharedArray, final String resourceUri) {
    if (sharedArray != null && user != null && blogId != null && request != null && resourceUri != null) {
        QueryBuilder query = QueryBuilder.start("_id").is(blogId);
        JsonObject keys = new JsonObject().put("title", 1);
        mongo.findOne("blogs", MongoQueryBuilder.build(query), keys, new Handler<Message<JsonObject>>() {
            @Override/*from   w w w.java 2s. c  o  m*/
            public void handle(final Message<JsonObject> event) {
                if ("ok".equals(event.body().getString("status"))) {
                    List<String> shareIds = getSharedIds(sharedArray);
                    if (!shareIds.isEmpty()) {
                        Map<String, Object> params = new HashMap<>();
                        params.put("userId", user.getUserId());
                        neo.send(neoQuery(shareIds), params, new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> res) {
                                if ("ok".equals(res.body().getString("status"))) {
                                    JsonObject r = res.body().getJsonObject("result");
                                    List<String> recipients = new ArrayList<>();
                                    for (String attr : r.fieldNames()) {
                                        String id = r.getJsonObject(attr).getString("id");
                                        if (id != null) {
                                            recipients.add(id);
                                        }
                                    }
                                    String blogTitle = event.body().getJsonObject("result", new JsonObject())
                                            .getString("title");
                                    JsonObject p = new JsonObject()
                                            .put("uri",
                                                    "/userbook/annuaire#" + user.getUserId() + "#"
                                                            + user.getType())
                                            .put("username", user.getUsername()).put("blogTitle", blogTitle)
                                            .put("resourceUri", resourceUri).put("disableAntiFlood", true);
                                    notification.notifyTimeline(request, "blog.share", user, recipients, blogId,
                                            p);
                                }
                            }
                        });
                    }
                }
            }
        });
    }
}

From source file:org.entcore.blog.services.impl.DefaultPostService.java

License:Open Source License

@Override
public void update(String postId, final JsonObject post, final UserInfos user,
        final Handler<Either<String, JsonObject>> result) {

    final JsonObject jQuery = MongoQueryBuilder.build(QueryBuilder.start("_id").is(postId));
    mongo.findOne(POST_COLLECTION, jQuery,
            MongoDbResult.validActionResultHandler(new Handler<Either<String, JsonObject>>() {
                public void handle(Either<String, JsonObject> event) {
                    if (event.isLeft()) {
                        result.handle(event);
                        return;
                    } else {
                        final JsonObject postFromDb = event.right().getValue().getJsonObject("result",
                                new JsonObject());
                        final JsonObject now = MongoDb.now();
                        post.put("modified", now);
                        final JsonObject b = Utils.validAndGet(post, UPDATABLE_FIELDS,
                                Collections.<String>emptyList());

                        if (validationError(result, b))
                            return;
                        if (b.containsKey("content")) {
                            b.put("contentPlain", StringUtils.stripHtmlTag(b.getString("content", "")));
                        }//from   ww w  .  j a  v  a  2 s. c om

                        if (postFromDb.getJsonObject("firstPublishDate") != null) {
                            b.put("sorted", postFromDb.getJsonObject("firstPublishDate"));
                        } else {
                            b.put("sorted", now);
                        }

                        //if user is author, draft state
                        if (user.getUserId().equals(
                                postFromDb.getJsonObject("author", new JsonObject()).getString("userId"))) {
                            b.put("state", StateType.DRAFT.name());
                        }

                        MongoUpdateBuilder modifier = new MongoUpdateBuilder();
                        for (String attr : b.fieldNames()) {
                            modifier.set(attr, b.getValue(attr));
                        }
                        mongo.update(POST_COLLECTION, jQuery, modifier.build(),
                                new Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> event) {
                                        if ("ok".equals(event.body().getString("status"))) {
                                            final JsonObject r = new JsonObject().put("state",
                                                    b.getString("state", postFromDb.getString("state")));
                                            result.handle(new Either.Right<String, JsonObject>(r));
                                        } else {
                                            result.handle(new Either.Left<String, JsonObject>(
                                                    event.body().getString("message", "")));
                                        }
                                    }
                                });
                    }
                }
            }));

}

From source file:org.entcore.blog.services.impl.DefaultPostService.java

License:Open Source License

@Override
public void listComment(String blogId, String postId, final UserInfos user,
        final Handler<Either<String, JsonArray>> result) {
    final QueryBuilder query = QueryBuilder.start("_id").is(postId).put("blog.$id").is(blogId);
    JsonObject keys = new JsonObject().put("comments", 1).put("blog", 1);
    JsonArray fetch = new JsonArray().add("blog");
    mongo.findOne(POST_COLLECTION, MongoQueryBuilder.build(query), keys, fetch,
            new Handler<Message<JsonObject>>() {
                @Override// w  w w  .j a v a2 s .  com
                public void handle(Message<JsonObject> event) {
                    JsonArray comments = new JsonArray();
                    if ("ok".equals(event.body().getString("status"))
                            && event.body().getJsonObject("result", new JsonObject()).size() > 0) {
                        JsonObject res = event.body().getJsonObject("result");
                        boolean userIsManager = userIsManager(user, res.getJsonObject("blog"));
                        for (Object o : res.getJsonArray("comments", new JsonArray())) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject j = (JsonObject) o;
                            if (userIsManager || StateType.PUBLISHED.name().equals(j.getString("state"))
                                    || user.getUserId().equals(
                                            j.getJsonObject("author", new JsonObject()).getString("userId"))) {
                                comments.add(j);
                            }
                        }
                    }
                    result.handle(new Either.Right<String, JsonArray>(comments));
                }
            });
}

From source file:org.entcore.cas.services.EnglishAttackRegisteredService.java

License:Open Source License

@Override
protected void prepareUserCas20(User user, final String userId, String service, final JsonObject data,
        final Document doc, final List<Element> additionnalAttributes) {
    user.setUser(data.getString(principalAttributeName));

    if (log.isDebugEnabled()) {
        log.debug("START : prepareUserCas20 userId : " + userId);
    }//  w ww  .  j  av  a 2  s  . com

    try {
        if (log.isDebugEnabled()) {
            log.debug("DATA : prepareUserCas20 data : " + data);
        }

        String query = "MATCH (u:`User` { id : {id}}) return u";
        JsonObject params = new JsonObject().put("id", userId);
        neo.execute(query, params, new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> m) {

                // Uid
                if (data.containsKey("externalId")) {
                    additionnalAttributes.add(createTextElement(EA_ID, data.getString("externalId"), doc));
                }

                // Structures
                Element rootStructures = createElement(EA_STRUCTURE + "s", doc);
                for (Object o : data.getJsonArray("structures", new fr.wseduc.webutils.collections.JsonArray())
                        .getList()) {
                    if (o == null || !(o instanceof JsonObject))
                        continue;
                    JsonObject structure = (JsonObject) o;
                    Element rootStructure = createElement(EA_STRUCTURE, doc);

                    if (structure.containsKey("UAI")) {
                        rootStructure.appendChild(
                                createTextElement(EA_STRUCTURE_UAI, structure.getString("UAI"), doc));
                    }
                    if (structure.containsKey("name")) {
                        rootStructure.appendChild(
                                createTextElement(EA_STRUCTURE_NAME, structure.getString("name"), doc));
                    }
                    rootStructures.appendChild(rootStructure);
                }
                additionnalAttributes.add(rootStructures);

                // Profile
                switch (data.getString("type")) {
                case "Student":
                    additionnalAttributes.add(createTextElement(EA_PROFILES, "National_1", doc));
                    addStringArray(EA_CLASSE, "classes", "name", data, doc, additionnalAttributes,
                            new Mapper<String, String>() {
                                String map(String input) {
                                    Matcher m = classGroupPattern.matcher(input);
                                    if (m.matches() && m.groupCount() >= 1) {
                                        return m.group(1);
                                    }
                                    return input;
                                }
                            });
                    // Email
                    if (data.containsKey("email")) {
                        additionnalAttributes.add(createTextElement(EA_EMAIL, data.getString("email"), doc));
                    }
                    break;
                case "Teacher":
                    additionnalAttributes.add(createTextElement(EA_PROFILES, "National_3", doc));
                    addStringArray(EA_CLASSE, "classes", "name", data, doc, additionnalAttributes,
                            new Mapper<String, String>() {
                                String map(String input) {
                                    Matcher m = classGroupPattern.matcher(input);
                                    if (m.matches() && m.groupCount() >= 1) {
                                        return m.group(1);
                                    }
                                    return input;
                                }
                            });

                    //Discipline
                    Either<String, JsonObject> res = validUniqueResult(m);
                    if (res.isRight()) {
                        JsonObject j = res.right().getValue();
                        if (null != j.getJsonObject("u") && null != j.getJsonObject("u").getJsonObject("data")
                                && null != j.getJsonObject("u").getJsonObject("data")
                                        .getJsonArray("functions")) {
                            JsonArray jsonArrayFunctions = j.getJsonObject("u").getJsonObject("data")
                                    .getJsonArray("functions");
                            if (jsonArrayFunctions.size() > 0) {
                                Element rootDisciplines = createElement(EA_DISCIPLINE + "s", doc);
                                List<String> vTempListDiscipline = new ArrayList<>();
                                for (int i = 0; i < jsonArrayFunctions.size(); i++) {
                                    String fonction = jsonArrayFunctions.getString(i);
                                    String[] elements = fonction.split("\\$");
                                    if (elements.length > 1) {
                                        String discipline = elements[elements.length - 2] + "$"
                                                + elements[elements.length - 1];
                                        if (!vTempListDiscipline.contains(discipline)) {
                                            vTempListDiscipline.add(discipline);
                                            rootDisciplines.appendChild(
                                                    createTextElement(EA_DISCIPLINE, discipline, doc));
                                        }
                                    } else {
                                        log.error("Failed to get User functions userID, : " + userId
                                                + " fonction : " + fonction);
                                    }
                                }
                                additionnalAttributes.add(rootDisciplines);
                            }
                        } else {
                            log.error("Failed to get User functions userID, user empty : " + userId + " j : "
                                    + j);
                        }
                    } else {
                        log.error("Failed to get User functions userID : " + userId);
                    }
                    // Email
                    if (data.containsKey("emailAcademy")) {
                        additionnalAttributes
                                .add(createTextElement(EA_EMAIL, data.getString("emailAcademy"), doc));
                    } else if (data.containsKey("email")) {
                        additionnalAttributes.add(createTextElement(EA_EMAIL, data.getString("email"), doc));

                    }
                    break;
                case "Relative":
                    additionnalAttributes.add(createTextElement(EA_PROFILES, "National_2", doc));
                    break;
                case "Personnel":
                    additionnalAttributes.add(createTextElement(EA_PROFILES, "National_4", doc));
                    break;
                }

                // Lastname
                if (data.containsKey("lastName")) {
                    additionnalAttributes.add(createTextElement(EA_LASTNAME, data.getString("lastName"), doc));
                }

                // Firstname
                if (data.containsKey("firstName")) {
                    additionnalAttributes
                            .add(createTextElement(EA_FIRSTNAME, data.getString("firstName"), doc));
                }
            }
        });

    } catch (Exception e) {
        log.error("Failed to transform User for EnglishAttack", e);
    }

    if (log.isDebugEnabled()) {
        log.debug("START : prepareUserCas20 userId : " + userId);
    }
}

From source file:org.entcore.common.aggregation.indicators.mongo.IndicatorMongoImpl.java

License:Open Source License

private void writeStats(JsonArray results, final IndicatorGroup group, final Handler<JsonObject> callBack) {

    //If no documents found, write nothing
    if (results.size() == 0) {
        callBack.handle(new JsonObject());
        return;//from w  w w .  j  av a  2 s. c om
    }

    //Document date
    Date writeDate = this.writeDate;

    final MongoDBBuilder criteriaQuery = new MongoDBBuilder();

    //Synchronization handler
    final AtomicInteger countDown = new AtomicInteger(results.size());
    Handler<Message<JsonObject>> synchroHandler = new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> message) {
            if (!"ok".equals(message.body().getString("status"))) {
                String groupstr = group == null ? "Global" : group.toString();
                log.error("[Aggregation][Error]{" + writtenIndicatorKey + "} (" + groupstr + ") writeStats : "
                        + message.body().toString());
                //log.info(criteriaQuery.toString());
            }

            if (countDown.decrementAndGet() == 0) {
                callBack.handle(new JsonObject());
            }
        }
    };
    //For each aggregated result
    for (Object obj : results) {
        JsonObject result = (JsonObject) obj;

        if (group == null) {
            //When not using groups, set groupedBy specifically to not exists
            criteriaQuery.put(STATS_FIELD_DATE).is(MongoDb.formatDate(writeDate)).and(STATS_FIELD_GROUPBY)
                    .exists(false);
        } else {
            //Adding date & group by to the criterias.
            criteriaQuery.put(STATS_FIELD_DATE).is(MongoDb.formatDate(writeDate)).and(STATS_FIELD_GROUPBY)
                    .is(group.toString());

            //Adding the group ids values
            IndicatorGroup g = group;
            while (g != null) {
                criteriaQuery.and(g.getKey() + "_id").is(result.getJsonObject("_id").getString(g.getKey()));
                g = g.getParent();
            }
        }

        //Perform write action
        writeAction(criteriaQuery, result.getInteger("count"), synchroHandler);
    }
}

From source file:org.entcore.common.bus.WorkspaceHelper.java

License:Open Source License

public void readDocument(String documentId, final Handler<Document> handler) {
    getDocument(documentId, new Handler<AsyncResult<Message<JsonObject>>>() {
        @Override/* w w w.ja v  a2  s  .  com*/
        public void handle(AsyncResult<Message<JsonObject>> event) {
            if (event.failed()) {
                handler.handle(null);
                return;
            }
            JsonObject res = event.result().body();
            String status = res.getString("status");
            final JsonObject result = res.getJsonObject("result");
            if ("ok".equals(status) && result != null) {
                String file = result.getString("file");
                if (file != null && !file.trim().isEmpty()) {
                    readFile(file, new Handler<Buffer>() {
                        @Override
                        public void handle(Buffer event) {
                            if (event != null) {
                                handler.handle(new Document(result, event));
                            } else {
                                handler.handle(null);
                            }
                        }
                    });
                } else {
                    handler.handle(null);
                }
            } else {
                handler.handle(null);
            }
        }
    });
}

From source file:org.entcore.common.email.EmailFactory.java

License:Open Source License

public EmailFactory(Vertx vertx, JsonObject config) {
    this.vertx = vertx;
    if (config != null && config.getJsonObject("emailConfig") != null) {
        this.config = config.getJsonObject("emailConfig");
    } else {/*from  w  w  w  .  j a v a2  s .c o m*/
        LocalMap<Object, Object> server = vertx.sharedData().getLocalMap("server");
        String s = (String) server.get("emailConfig");
        if (s != null) {
            this.config = new JsonObject(s);
        } else {
            this.config = null;
        }
    }
}

From source file:org.entcore.common.http.filter.CsrfFilter.java

License:Open Source License

protected void compareToken(final HttpServerRequest request, final Handler<Boolean> handler) {
    UserUtils.getSession(eb, request, new Handler<JsonObject>() {
        @Override/*  ww w.  ja  v  a  2 s  .  c  o m*/
        public void handle(JsonObject session) {
            String XSRFToken = null;
            if (session != null && session.getJsonObject("cache") != null) {
                XSRFToken = session.getJsonObject("cache").getString("xsrf-token");
                if (XSRFToken == null) { // TODO remove when support session cache persistence
                    XSRFToken = CookieHelper.get("XSRF-TOKEN", request);
                }
            }
            handler.handle(XSRFToken != null && !XSRFToken.isEmpty()
                    && XSRFToken.equals(request.headers().get("X-XSRF-TOKEN")));
        }
    });
}

From source file:org.entcore.common.http.response.SecurityHookRender.java

License:Open Source License

private void contentSecurityPolicyHeader(HttpServerRequest request, JsonObject session) {
    if (contentSecurityPolicy == null)
        return;/* ww w  .j a va2  s .  com*/
    final String csp;
    if (session != null && session.getJsonObject("cache") != null
            && session.getJsonObject("cache").getString("content-security-policy") != null) {
        csp = session.getJsonObject("cache").getString("content-security-policy");
    } else if (session != null && session.getJsonArray("apps") != null) {
        final StringBuilder sb = new StringBuilder(contentSecurityPolicy);
        if (!contentSecurityPolicy.contains("frame-src")) {
            if (!contentSecurityPolicy.trim().endsWith(";")) {
                sb.append("; ");
            }
            sb.append("frame-src 'self'");
        }
        for (Object o : session.getJsonArray("apps")) {
            if (!(o instanceof JsonObject))
                continue;
            String address = ((JsonObject) o).getString("address");
            if (address != null && address.contains("adapter#")) {
                String[] s = address.split("adapter#");
                if (s.length == 2 && isNotEmpty(s[1])) {
                    try {
                        URI uri = new URI(s[1]);
                        sb.append(" ").append(uri.getHost());
                    } catch (URISyntaxException e) {
                        log.warn("Invalid adapter URI : " + s[1], e);
                    }
                }
            }
        }
        csp = sb.append(";").toString();
        UserUtils.addSessionAttribute(eb, session.getString("userId"), "content-security-policy", csp, null);
    } else {
        csp = contentSecurityPolicy;
    }
    request.response().putHeader("Content-Security-Policy", csp);
}