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

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Get the number of entries in the JSON object

Usage

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void getAuthInfoByCode(String code, final Handler<AuthInfo> handler) {
    if (code != null && !code.trim().isEmpty()) {
        JsonObject query = new JsonObject().put("code", code).put("createdAt", new JsonObject().put("$gte",
                new JsonObject().put("$date", System.currentTimeMillis() - CODE_EXPIRES)));
        mongo.findOne(AUTH_INFO_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override//  w w w.  j  a v  a  2 s.  c  om
            public void handle(Message<JsonObject> res) {
                JsonObject r = res.body().getJsonObject("result");
                if ("ok".equals(res.body().getString("status")) && r != null && r.size() > 0) {
                    r.put("id", r.getString("_id"));
                    r.remove("_id");
                    r.remove("createdAt");
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        handler.handle(mapper.readValue(r.encode(), AuthInfo.class));
                    } catch (IOException e) {
                        handler.handle(null);
                    }
                } else {
                    handler.handle(null);
                }
            }
        });
    } else {
        handler.handle(null);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void getAccessToken(String token, final Handler<AccessToken> handler) {
    if (token != null && !token.trim().isEmpty()) {
        JsonObject query = new JsonObject().put("token", token);
        mongo.findOne(ACCESS_TOKEN_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override/*from  w  w w  .  ja va2  s. c  o  m*/
            public void handle(Message<JsonObject> res) {
                JsonObject r = res.body().getJsonObject("result");
                if ("ok".equals(res.body().getString("status")) && r != null && r.size() > 0) {
                    AccessToken t = new AccessToken();
                    t.setAuthId(r.getString("authId"));
                    t.setToken(r.getString("token"));
                    t.setCreatedOn(MongoDb.parseIsoDate(r.getJsonObject("createdOn")));
                    t.setExpiresIn(r.getInteger("expiresIn"));
                    handler.handle(t);
                } else {
                    handler.handle(null);
                }
            }
        });
    } else {
        handler.handle(null);
    }
}

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

License:Open Source License

@Override
public void submit(String blogId, String postId, UserInfos user,
        final Handler<Either<String, JsonObject>> result) {
    QueryBuilder query = QueryBuilder.start("_id").is(postId).put("blog.$id").is(blogId).put("state")
            .is(StateType.DRAFT.name()).put("author.userId").is(user.getUserId());
    final JsonObject q = MongoQueryBuilder.build(query);
    JsonObject keys = new JsonObject().put("blog", 1).put("firstPublishDate", 1);
    JsonArray fetch = new JsonArray().add("blog");
    mongo.findOne(POST_COLLECTION, q, keys, fetch, new Handler<Message<JsonObject>>() {
        @Override/*from   w  ww .j a v  a2s  .  c om*/
        public void handle(Message<JsonObject> event) {
            final JsonObject res = event.body().getJsonObject("result", new JsonObject());
            if ("ok".equals(event.body().getString("status")) && res.size() > 0) {
                BlogService.PublishType type = Utils.stringToEnum(
                        res.getJsonObject("blog", new JsonObject()).getString("publish-type"),
                        BlogService.PublishType.RESTRAINT, BlogService.PublishType.class);
                final StateType state = (BlogService.PublishType.RESTRAINT.equals(type)) ? StateType.SUBMITTED
                        : StateType.PUBLISHED;
                MongoUpdateBuilder updateQuery = new MongoUpdateBuilder().set("state", state.name());

                // if IMMEDIATE published post, first publishing must define the first published date
                if (StateType.PUBLISHED.equals(state) && res.getJsonObject("firstPublishDate") == null) {
                    updateQuery = updateQuery.set("firstPublishDate", MongoDb.now()).set("sorted",
                            MongoDb.now());
                }

                mongo.update(POST_COLLECTION, q, updateQuery.build(), new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> res) {
                        res.body().put("state", state.name());
                        result.handle(Utils.validResult(res));
                    }
                });
            } else {
                result.handle(Utils.validResult(event));
            }
        }
    });
}

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

License:Open Source License

private JsonObject generateEvent(String eventType, UserInfos user, HttpServerRequest request,
        JsonObject customAttributes) {
    JsonObject event = new JsonObject();
    if (customAttributes != null && customAttributes.size() > 0) {
        event.mergeIn(customAttributes);
    }/*from w w w.  j  a  v  a2s  . c o m*/
    event.put("event-type", eventType).put("module", module).put("date", System.currentTimeMillis());
    if (user != null) {
        event.put("userId", user.getUserId()).put("profil", user.getType());
        if (user.getStructures() != null) {
            event.put("structures", new fr.wseduc.webutils.collections.JsonArray(user.getStructures()));
        }
        if (user.getClasses() != null) {
            event.put("classes", new fr.wseduc.webutils.collections.JsonArray(user.getClasses()));
        }
        if (user.getGroupsIds() != null) {
            event.put("groups", new fr.wseduc.webutils.collections.JsonArray(user.getGroupsIds()));
        }
    }
    if (request != null) {
        event.put("referer", request.headers().get("Referer"));
        event.put("sessionId", CookieHelper.getInstance().getSigned("oneSessionId", request));
    }
    return event;
}

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

License:Open Source License

protected void shareValidation(String resourceId, String userId, JsonObject share,
        Handler<Either<String, JsonObject>> handler) {
    final JsonObject groups = share.getJsonObject("groups");
    final JsonObject users = share.getJsonObject("users");
    final JsonObject shareBookmark = share.getJsonObject("bookmarks");
    final HashMap<String, Set<String>> membersActions = new HashMap<>();

    if (groups != null && groups.size() > 0) {
        for (String attr : groups.fieldNames()) {
            JsonArray actions = groups.getJsonArray(attr);
            if (actionsExists(actions.getList())) {
                membersActions.put(attr, new HashSet<>(actions.getList()));
            }/*from   www .j ava  2  s  . c  om*/
        }
    }
    if (users != null && users.size() > 0) {
        for (String attr : users.fieldNames()) {
            JsonArray actions = users.getJsonArray(attr);
            if (actionsExists(actions.getList())) {
                membersActions.put(attr, new HashSet<>(actions.getList()));
            }
        }
    }
    if (shareBookmark != null && shareBookmark.size() > 0) {
        final JsonObject p = new JsonObject().put("userId", userId);
        StatementsBuilder statements = new StatementsBuilder();
        for (String sbId : shareBookmark.fieldNames()) {
            final String csbId = cleanId(sbId);
            final String query = "MATCH (:User {id:{userId}})-[:HAS_SB]->(sb:ShareBookmark) "
                    + "RETURN DISTINCT '" + csbId + "' as id, TAIL(sb." + csbId + ") as members ";
            statements.add(query, p);
        }
        Neo4j.getInstance().executeTransaction(statements.build(), null, true,
                Neo4jResult.validResultsHandler(sbRes -> {
                    if (sbRes.isRight()) {
                        JsonArray a = sbRes.right().getValue();
                        for (Object o : a) {
                            JsonObject r = ((JsonArray) o).getJsonObject(0);
                            JsonArray actions = shareBookmark.getJsonArray(r.getString("id"));
                            JsonArray mIds = r.getJsonArray("members");
                            if (actions != null && mIds != null && mIds.size() > 0
                                    && actionsExists(actions.getList())) {
                                for (Object mId : mIds) {
                                    Set<String> actionsShare = membersActions.get(mId.toString());
                                    if (actionsShare == null) {
                                        actionsShare = new HashSet<>(new HashSet<>(actions.getList()));
                                        membersActions.put(mId.toString(), actionsShare);
                                        //                        } else {
                                        //                           actionsShare.addAll(new HashSet<>(actions.getList()));
                                    }
                                }
                            }
                        }
                        shareValidationVisible(userId, resourceId, handler, membersActions,
                                shareBookmark.fieldNames());
                    } else {
                        handler.handle(new Either.Left<>(sbRes.left().getValue()));
                    }
                }));
    } else {
        shareValidationVisible(userId, resourceId, handler, membersActions, null);
    }
}

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

License:Open Source License

private void removeShare(String resourceId, final String shareId, List<String> removeActions, boolean isGroup,
        final Handler<Either<String, JsonObject>> handler) {
    final String shareIdAttr = isGroup ? "groupId" : "userId";
    final List<String> actions = findRemoveActions(removeActions);
    QueryBuilder query = QueryBuilder.start("_id").is(resourceId);
    JsonObject keys = new JsonObject().put("shared", 1);
    final JsonObject q = MongoQueryBuilder.build(query);
    mongo.findOne(collection, q, keys, new Handler<Message<JsonObject>>() {
        @Override//from  w ww .  j  a v  a2s  .  com
        public void handle(Message<JsonObject> event) {
            if ("ok".equals(event.body().getString("status")) && event.body().getJsonObject("result") != null) {
                JsonArray actual = event.body().getJsonObject("result").getJsonArray("shared",
                        new fr.wseduc.webutils.collections.JsonArray());
                JsonArray shared = new fr.wseduc.webutils.collections.JsonArray();
                for (int i = 0; i < actual.size(); i++) {
                    JsonObject s = actual.getJsonObject(i);
                    String id = s.getString(shareIdAttr);
                    if (shareId.equals(id)) {
                        if (actions != null) {
                            for (String action : actions) {
                                s.remove(action);
                            }
                            if (s.size() > 1) {
                                shared.add(s);
                            }
                        }
                    } else {
                        shared.add(s);
                    }
                }
                MongoUpdateBuilder updateQuery = new MongoUpdateBuilder().set("shared", shared);
                mongo.update(collection, q, updateQuery.build(), new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> res) {
                        handler.handle(Utils.validResult(res));
                    }
                });
            } else {
                handler.handle(new Either.Left<String, JsonObject>("Resource not found."));
            }
        }
    });
}

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

License:Open Source License

@Override
public void shareInfos(final String userId, String resourceId, final String acceptLanguage, final String search,
        final Handler<Either<String, JsonObject>> handler) {
    if (userId == null || userId.trim().isEmpty()) {
        handler.handle(new Either.Left<String, JsonObject>("Invalid userId."));
        return;//from w ww.  jav  a  2s. c  o  m
    }
    if (resourceId == null || resourceId.trim().isEmpty()) {
        handler.handle(new Either.Left<String, JsonObject>("Invalid resourceId."));
        return;
    }
    final JsonArray actions = getResoureActions(securedActions);
    String query = "SELECT s.member_id, s.action, m.group_id FROM " + shareTable + " AS s " + "JOIN " + schema
            + "members AS m ON s.member_id = m.id WHERE resource_id = ?";
    sql.prepared(query, new fr.wseduc.webutils.collections.JsonArray().add(Sql.parseId(resourceId)),
            new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> message) {
                    if ("ok".equals(message.body().getString("status"))) {
                        JsonArray r = message.body().getJsonArray("results");
                        JsonObject groupCheckedActions = new JsonObject();
                        JsonObject userCheckedActions = new JsonObject();
                        for (Object o : r) {
                            if (!(o instanceof JsonArray))
                                continue;
                            JsonArray row = (JsonArray) o;
                            final String memberId = row.getString(0);
                            if (memberId == null || memberId.equals(userId))
                                continue;
                            final JsonObject checkedActions = (row.getValue(2) != null) ? groupCheckedActions
                                    : userCheckedActions;
                            JsonArray m = checkedActions.getJsonArray(memberId);
                            if (m == null) {
                                m = new fr.wseduc.webutils.collections.JsonArray();
                                checkedActions.put(memberId, m);
                            }
                            m.add(row.getValue(1));
                        }
                        getShareInfos(userId, actions, groupCheckedActions, userCheckedActions, acceptLanguage,
                                search, new Handler<JsonObject>() {
                                    @Override
                                    public void handle(JsonObject event) {
                                        if (event != null && event.size() == 3) {
                                            handler.handle(new Either.Right<String, JsonObject>(event));
                                        } else {
                                            handler.handle(new Either.Left<String, JsonObject>(
                                                    "Error finding shared resource."));
                                        }
                                    }
                                });
                    }
                }
            });
}

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

License:Open Source License

@Override
public void update(String userId, JsonObject userBook, final Handler<Either<String, JsonObject>> result) {
    JsonObject u = Utils.validAndGet(userBook, UPDATE_USERBOOK_FIELDS, Collections.<String>emptyList());
    if (Utils.defaultValidationError(u, result, userId))
        return;//  w ww . ja v a2  s  . c  o m
    // OVERRIDE AVATAR URL
    Optional<String> pictureId = getPictureIdForUserbook(userBook);
    if (pictureId.isPresent()) {
        String fileId = avatarFileNameFromUserId(userId, Optional.empty());
        u.put("picture", "/userbook/avatar/" + fileId);
    }

    StatementsBuilder b = new StatementsBuilder();
    String query = "MATCH (u:`User` { id : {id}})-[:USERBOOK]->(ub:UserBook) WITH ub.picture as oldpic,ub,u SET "
            + nodeSetPropertiesFromJson("ub", u);
    query += " RETURN oldpic,ub.picture as picture";
    boolean updateUserBook = u.size() > 0;
    if (updateUserBook) {
        b.add(query, u.put("id", userId));
    }
    String q2 = "MATCH (u:`User` { id : {id}})-[:USERBOOK]->(ub:UserBook)"
            + "-[:PUBLIC|PRIVE]->(h:`Hobby` { category : {category}}) " + "SET h.values = {values} ";
    JsonArray hobbies = userBook.getJsonArray("hobbies");
    if (hobbies != null) {
        for (Object o : hobbies) {
            if (!(o instanceof JsonObject))
                continue;
            JsonObject j = (JsonObject) o;
            b.add(q2, j.put("id", userId));
        }
    }
    neo.executeTransaction(b.build(), null, true, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> r) {
            if ("ok".equals(r.body().getString("status"))) {
                if (updateUserBook) {
                    JsonArray results = r.body().getJsonArray("results", new JsonArray());
                    JsonArray firstStatement = results.getJsonArray(0);
                    if (firstStatement != null && firstStatement.size() > 0) {
                        JsonObject object = firstStatement.getJsonObject(0);
                        String picture = object.getString("picture", "");
                        cacheAvatarFromUserBook(userId, pictureId, StringUtils.isEmpty(picture))
                                .setHandler(e -> {
                                    if (e.succeeded()) {
                                        result.handle(new Either.Right<String, JsonObject>(new JsonObject()));
                                    } else {
                                        result.handle(new Either.Left<String, JsonObject>(
                                                r.body().getString("message", "update.error")));
                                    }
                                });
                    }
                } else {
                    result.handle(new Either.Right<String, JsonObject>(new JsonObject()));
                }
            } else {
                result.handle(
                        new Either.Left<String, JsonObject>(r.body().getString("message", "update.error")));
            }
        }
    });
}

From source file:org.entcore.feeder.dictionary.structures.PostImport.java

License:Open Source License

private void wsCall(JsonObject object) {
    for (String url : object.fieldNames()) {
        final JsonArray endpoints = object.getJsonArray(url);
        if (endpoints == null || endpoints.size() < 1)
            continue;
        try {/*from   w ww.  ja  v a  2s  .c  o  m*/
            final URI uri = new URI(url);
            HttpClientOptions options = new HttpClientOptions().setDefaultHost(uri.getHost())
                    .setDefaultPort(uri.getPort()).setMaxPoolSize(16).setSsl("https".equals(uri.getScheme()))
                    .setConnectTimeout(10000).setKeepAlive(false);
            final HttpClient client = vertx.createHttpClient(options);

            final Handler[] handlers = new Handler[endpoints.size() + 1];
            handlers[handlers.length - 1] = new Handler<Void>() {
                @Override
                public void handle(Void v) {
                    client.close();
                }
            };
            for (int i = endpoints.size() - 1; i >= 0; i--) {
                final int ji = i;
                handlers[i] = new Handler<Void>() {
                    @Override
                    public void handle(Void v) {
                        final JsonObject j = endpoints.getJsonObject(ji);
                        logger.info("endpoint : " + j.encode());
                        final HttpClientRequest req = client.request(HttpMethod.valueOf(j.getString("method")),
                                j.getString("uri"), new Handler<HttpClientResponse>() {
                                    @Override
                                    public void handle(HttpClientResponse resp) {
                                        if (resp.statusCode() >= 300) {
                                            logger.warn("Endpoint " + j.encode() + " error : "
                                                    + resp.statusCode() + " " + resp.statusMessage());
                                        }
                                        handlers[ji + 1].handle(null);
                                    }
                                });
                        JsonObject headers = j.getJsonObject("headers");
                        if (headers != null && headers.size() > 0) {
                            for (String h : headers.fieldNames()) {
                                req.putHeader(h, headers.getString(h));
                            }
                        }
                        req.exceptionHandler(
                                e -> logger.error("Error in ws call post import : " + j.encode(), e));
                        if (j.getString("body") != null) {
                            req.end(j.getString("body"));
                        } else {
                            req.end();
                        }
                    }
                };
            }
            handlers[0].handle(null);
        } catch (URISyntaxException e) {
            logger.error("Invalid uri in ws call after import : " + url, e);
        }
    }
}

From source file:org.entcore.feeder.Feeder.java

License:Open Source License

@Override
public void start() {
    super.start();
    String node = (String) vertx.sharedData().getLocalMap("server").get("node");
    if (node == null) {
        node = "";
    }/*from w w w.j  a  v  a2 s .com*/
    String neo4jConfig = (String) vertx.sharedData().getLocalMap("server").get("neo4jConfig");
    if (neo4jConfig != null) {
        neo4j = Neo4j.getInstance();
        neo4j.init(vertx, new JsonObject(neo4jConfig));
    }
    MongoDb.getInstance().init(vertx.eventBus(), node + "wse.mongodb.persistor");
    TransactionManager.getInstance().setNeo4j(neo4j);
    EventStoreFactory.getFactory().setVertx(vertx);
    defaultFeed = config.getString("feeder", "AAF");
    feeds.put("AAF", new AafFeeder(vertx, getFilesDirectory("AAF")));
    feeds.put("AAF1D", new Aaf1dFeeder(vertx, getFilesDirectory("AAF1D")));
    feeds.put("CSV", new CsvFeeder(vertx, config.getJsonObject("csvMappings", new JsonObject())));
    final long deleteUserDelay = config.getLong("delete-user-delay", 90 * 24 * 3600 * 1000l);
    final long preDeleteUserDelay = config.getLong("pre-delete-user-delay", 90 * 24 * 3600 * 1000l);
    final String deleteCron = config.getString("delete-cron", "0 0 2 * * ? *");
    final String preDeleteCron = config.getString("pre-delete-cron", "0 0 3 * * ? *");
    final String importCron = config.getString("import-cron");
    final JsonObject imports = config.getJsonObject("imports");
    final JsonObject preDelete = config.getJsonObject("pre-delete");
    final TimelineHelper timeline = new TimelineHelper(vertx, eb, config);
    try {
        new CronTrigger(vertx, deleteCron).schedule(new User.DeleteTask(deleteUserDelay, eb, vertx));
        if (preDelete != null) {
            if (preDelete.size() == ManualFeeder.profiles.size()
                    && ManualFeeder.profiles.keySet().containsAll(preDelete.fieldNames())) {
                for (String profile : preDelete.fieldNames()) {
                    final JsonObject profilePreDelete = preDelete.getJsonObject(profile);
                    if (profilePreDelete == null || profilePreDelete.getString("cron") == null
                            || profilePreDelete.getLong("delay") == null)
                        continue;
                    new CronTrigger(vertx, profilePreDelete.getString("cron")).schedule(
                            new User.PreDeleteTask(profilePreDelete.getLong("delay"), profile, timeline));
                }
            }
        } else {
            new CronTrigger(vertx, preDeleteCron)
                    .schedule(new User.PreDeleteTask(preDeleteUserDelay, timeline));
        }
        if (imports != null) {
            if (feeds.keySet().containsAll(imports.fieldNames())) {
                for (String f : imports.fieldNames()) {
                    final JsonObject i = imports.getJsonObject(f);
                    if (i != null && i.getString("cron") != null) {
                        new CronTrigger(vertx, i.getString("cron"))
                                .schedule(new ImporterTask(vertx, f, i.getBoolean("auto-export", false),
                                        config.getLong("auto-export-delay", 1800000l)));
                    }
                }
            } else {
                logger.error("Invalid imports configuration.");
            }
        } else if (importCron != null && !importCron.trim().isEmpty()) {
            new CronTrigger(vertx, importCron).schedule(new ImporterTask(vertx, defaultFeed,
                    config.getBoolean("auto-export", false), config.getLong("auto-export-delay", 1800000l)));
        }
    } catch (ParseException e) {
        logger.fatal(e.getMessage(), e);
        vertx.close();
        return;
    }
    Validator.initLogin(neo4j, vertx);
    manual = new ManualFeeder(neo4j);
    duplicateUsers = new DuplicateUsers(config.getBoolean("timetable", true),
            config.getBoolean("autoMergeOnlyInSameStructure", true), vertx.eventBus());
    postImport = new PostImport(vertx, duplicateUsers, config);
    vertx.eventBus().localConsumer(config.getString("address", FEEDER_ADDRESS), this);
    switch (config.getString("exporter", "")) {
    case "ELIOT":
        exporter = new EliotExporter(config.getString("export-path", "/tmp"),
                config.getString("export-destination"), config.getBoolean("concat-export", false),
                config.getBoolean("delete-export", true), vertx);
        break;
    }
    final JsonObject edt = config.getJsonObject("edt");
    if (edt != null) {
        final String pronotePrivateKey = edt.getString("pronote-private-key");
        if (isNotEmpty(pronotePrivateKey)) {
            edtUtils = new EDTUtils(vertx, pronotePrivateKey,
                    config.getString("pronote-partner-name", "NEO-Open"));
            final String edtPath = edt.getString("path");
            final String edtCron = edt.getString("cron");
            if (isNotEmpty(edtPath) && isNotEmpty(edtCron)) {
                try {
                    new CronTrigger(vertx, edtCron).schedule(new ImportsLauncher(vertx, edtPath, postImport,
                            edtUtils, config.getBoolean("udt-user-creation", true)));
                } catch (ParseException e) {
                    logger.error("Error in cron edt", e);
                }
            }
        }
    }
    final JsonObject udt = config.getJsonObject("udt");
    if (udt != null) {
        final String udtPath = udt.getString("path");
        final String udtCron = udt.getString("cron");
        if (isNotEmpty(udtPath) && isNotEmpty(udtCron)) {
            try {
                new CronTrigger(vertx, udtCron).schedule(new ImportsLauncher(vertx, udtPath, postImport,
                        edtUtils, config.getBoolean("udt-user-creation", true)));
            } catch (ParseException e) {
                logger.error("Error in cron udt", e);
            }
        }
    }
    final JsonObject csv = config.getJsonObject("csv");
    if (csv != null) {
        final String csvPath = csv.getString("path");
        final String csvCron = csv.getString("cron");
        final JsonObject csvConfig = csv.getJsonObject("config");
        if (isNotEmpty(csvPath) && isNotEmpty(csvCron) && csvConfig != null) {
            try {
                new CronTrigger(vertx, csvCron)
                        .schedule(new CsvImportsLauncher(vertx, csvPath, csvConfig, postImport));
            } catch (ParseException e) {
                logger.error("Error in cron csv", e);
            }
        }
    }
    I18n.getInstance().init(vertx);
}