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

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Get the number of values in this JSON array

Usage

From source file:org.entcore.workspace.service.impl.WorkspaceSearchingEvents.java

License:Open Source License

@SuppressWarnings("unchecked")
private JsonArray formatSearchResult(final JsonArray results, final JsonArray columnsHeader,
        final List<String> words, final String locale, final String userId,
        final Map<String, Map<String, String>> mapOwnerMapNameFolderId) {
    final List<String> aHeader = columnsHeader.getList();
    final JsonArray traity = new fr.wseduc.webutils.collections.JsonArray();

    for (int i = 0; i < results.size(); i++) {
        final JsonObject j = results.getJsonObject(i);
        final JsonObject jr = new JsonObject();

        if (j != null) {
            final String folder = j.getString("folder", "");

            Date modified = new Date();
            try {
                modified = DateUtils.parse(j.getString("modified"), PATTERN);
            } catch (ParseException e) {
                log.error("Can't parse date from modified", e);
            }/*from   w w w  . ja  v a 2  s .c o  m*/
            final String owner = j.getString("owner", "");
            final Map<String, Object> map = formatDescription(
                    j.getJsonArray("comments", new fr.wseduc.webutils.collections.JsonArray()), words, modified,
                    locale);
            jr.put(aHeader.get(0), j.getString("name"));
            jr.put(aHeader.get(1), map.get("description").toString());
            jr.put(aHeader.get(2), new JsonObject().put("$date", ((Date) map.get("modified")).getTime()));
            jr.put(aHeader.get(3), j.getString("ownerName", ""));
            jr.put(aHeader.get(4), owner);
            //default front route (no folder and the file belongs to the owner)
            String resourceURI = "/workspace/workspace";

            if (userId.equals(owner)) {
                if (!StringUtils.isEmpty(folder)) {
                    resourceURI += "#/folder/" + mapOwnerMapNameFolderId.get(owner).get(folder);
                }
            } else {
                //if there is a folder on entry file and this folder is shared
                if (!StringUtils.isEmpty(folder) && mapOwnerMapNameFolderId.containsKey(owner)
                        && mapOwnerMapNameFolderId.get(owner).containsKey(folder)) {
                    resourceURI += "#/shared/folder/" + mapOwnerMapNameFolderId.get(owner).get(folder);
                } else {
                    //only the file is shared
                    resourceURI += "#/shared";
                }
            }
            jr.put(aHeader.get(5), resourceURI);
            traity.add(jr);
        }
    }
    return traity;
}

From source file:org.entcore.workspace.service.impl.WorkspaceSearchingEvents.java

License:Open Source License

private Map<String, Object> formatDescription(JsonArray ja, final List<String> words, Date defaultDate,
        String locale) {/*w  w  w  .  ja v a  2 s .co  m*/
    final Map<String, Object> map = new HashMap<>();

    Integer countMatchComment = 0;
    Date modifiedRes = null;
    Date modifiedMarker = null;
    String comment = "";

    final List<String> unaccentWords = new ArrayList<>();
    for (final String word : words) {
        unaccentWords.add(StringUtils.stripAccentsToLowerCase(word));
    }

    //get the last modified comment that match with searched words for create the description
    for (int i = 0; i < ja.size(); i++) {
        final JsonObject jO = ja.getJsonObject(i);

        final String commentTmp = jO.getString("comment", "");
        Date currentDate = null;
        try {
            currentDate = DateUtils.parse(jO.getString("posted"), PATTERN);
        } catch (ParseException e) {
            log.error("Can't parse date from posted", e);
        }

        int match = unaccentWords.size();
        for (final String word : unaccentWords) {
            if (StringUtils.stripAccentsToLowerCase(commentTmp).contains(word)) {
                match--;
            }
        }
        if (countMatchComment == 0 && match == 0) {
            modifiedRes = currentDate;
        } else if (countMatchComment > 0 && match == 0 && currentDate != null && modifiedMarker != null
                && modifiedMarker.before(currentDate)) {
            modifiedMarker = currentDate;
            modifiedRes = currentDate;
        }
        if (match == 0) {
            comment = commentTmp;
            if (currentDate != null) {
                modifiedMarker = currentDate;
            }
            countMatchComment++;
        }
    }

    if (countMatchComment == 0) {
        map.put("modified", defaultDate);
        map.put("description", "");
    } else if (countMatchComment == 1) {
        map.put("modified", modifiedRes);
        map.put("description",
                i18n.translate("workspace.search.description.one", I18n.DEFAULT_DOMAIN, locale, comment));
    } else {
        map.put("modified", modifiedRes);
        map.put("description", i18n.translate("workspace.search.description.several", I18n.DEFAULT_DOMAIN,
                locale, countMatchComment.toString(), comment));
    }

    return map;
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void notifyShare(final HttpServerRequest request, final String resource, final UserInfos user,
        JsonArray sharedArray, final boolean isFolder) {
    final List<String> recipients = new ArrayList<>();
    final AtomicInteger remaining = new AtomicInteger(sharedArray.size());
    for (Object j : sharedArray) {
        JsonObject json = (JsonObject) j;
        String userId = json.getString("userId");
        if (userId != null) {
            recipients.add(userId);/*from ww w .  ja v  a2 s  . co  m*/
            remaining.getAndDecrement();
        } else {
            String groupId = json.getString("groupId");
            if (groupId != null) {
                UserUtils.findUsersInProfilsGroups(groupId, eb, user.getUserId(), false,
                        new Handler<JsonArray>() {
                            @Override
                            public void handle(JsonArray event) {
                                if (event != null) {
                                    for (Object o : event) {
                                        if (!(o instanceof JsonObject))
                                            continue;
                                        JsonObject j = (JsonObject) o;
                                        String id = j.getString("id");
                                        log.debug(id);
                                        recipients.add(id);
                                    }
                                }
                                if (remaining.decrementAndGet() < 1) {
                                    sendNotify(request, resource, user, recipients, isFolder);
                                }
                            }
                        });
            }
        }
    }
    if (remaining.get() < 1) {
        sendNotify(request, resource, user, recipients, isFolder);
    }
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void createThumbnails(List<String> thumbs, JsonObject srcFile, final String collection,
        final String documentId, final Handler<Message<JsonObject>> callback) {
    Pattern size = Pattern.compile("([0-9]+)x([0-9]+)");
    JsonArray outputs = new fr.wseduc.webutils.collections.JsonArray();
    for (String thumb : thumbs) {
        Matcher m = size.matcher(thumb);
        if (m.matches()) {
            try {
                int width = Integer.parseInt(m.group(1));
                int height = Integer.parseInt(m.group(2));
                if (width == 0 && height == 0)
                    continue;
                JsonObject j = new JsonObject().put("dest",
                        storage.getProtocol() + "://" + storage.getBucket());
                if (width != 0) {
                    j.put("width", width);
                }//from  w  w  w  . ja  v  a  2s .c  om
                if (height != 0) {
                    j.put("height", height);
                }
                outputs.add(j);
            } catch (NumberFormatException e) {
                log.error("Invalid thumbnail size.", e);
            }
        }
    }
    if (outputs.size() > 0) {
        JsonObject json = new JsonObject().put("action", "resizeMultiple")
                .put("src",
                        storage.getProtocol() + "://" + storage.getBucket() + ":" + srcFile.getString("_id"))
                .put("destinations", outputs);
        eb.send(imageResizerAddress, json, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> event) {
                JsonObject thumbnails = event.body().getJsonObject("outputs");
                if ("ok".equals(event.body().getString("status")) && thumbnails != null) {
                    mongo.update(collection, new JsonObject().put("_id", documentId),
                            new JsonObject().put("$set", new JsonObject().put("thumbnails", thumbnails)),
                            callback);
                }
            }
        }));
    } else if (callback != null) {
        callback.handle(null);
    }
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void copyFiles(final HttpServerRequest request, final String collection, final String owner,
        final UserInfos user) {
    String ids = request.params().get("ids"); // TODO refactor with json in request body
    String folder2 = getOrElse(request.params().get("folder"), "");
    try {//from  w ww  .  ja  v a2  s  .c  o  m
        folder2 = URLDecoder.decode(folder2, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.warn(e.getMessage(), e);
    }
    final String folder = folder2;
    if (ids != null && !ids.trim().isEmpty()) {
        JsonArray idsArray = new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(ids.split(",")));
        String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
        if (owner != null) {
            criteria += ", \"to\" : \"" + owner + "\"";
        }
        criteria += "}";
        mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> r) {
                JsonObject src = r.body();
                if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                    final JsonArray origs = src.getJsonArray("results");
                    final JsonArray insert = new fr.wseduc.webutils.collections.JsonArray();
                    final AtomicInteger number = new AtomicInteger(origs.size());
                    emptySize(user, new Handler<Long>() {
                        @Override
                        public void handle(Long emptySize) {
                            long size = 0;
                            for (Object o : origs) {
                                if (!(o instanceof JsonObject))
                                    continue;
                                JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                                if (metadata != null) {
                                    size += metadata.getLong("size", 0l);
                                }
                            }
                            if (size > emptySize) {
                                badRequest(request, "files.too.large");
                                return;
                            }
                            for (Object o : origs) {
                                JsonObject orig = (JsonObject) o;
                                final JsonObject dest = orig.copy();
                                String now = MongoDb.formatDate(new Date());
                                dest.remove("_id");
                                dest.remove("protected");
                                dest.remove("comments");
                                dest.put("application", WORKSPACE_NAME);
                                if (owner != null) {
                                    dest.put("owner", owner);
                                    dest.put("ownerName", dest.getString("toName"));
                                    dest.remove("to");
                                    dest.remove("from");
                                    dest.remove("toName");
                                    dest.remove("fromName");
                                } else if (user != null) {
                                    dest.put("owner", user.getUserId());
                                    dest.put("ownerName", user.getUsername());
                                    dest.put("shared", new fr.wseduc.webutils.collections.JsonArray());
                                }
                                dest.put("_id", UUID.randomUUID().toString());
                                dest.put("created", now);
                                dest.put("modified", now);
                                if (folder != null && !folder.trim().isEmpty()) {
                                    dest.put("folder", folder);
                                } else {
                                    dest.remove("folder");
                                }
                                insert.add(dest);
                                final String filePath = orig.getString("file");

                                if ((owner != null || user != null) && folder != null
                                        && !folder.trim().isEmpty()) {

                                    //If the document has a new parent folder, replicate sharing rights
                                    String parentName, parentFolder;
                                    if (folder.lastIndexOf('_') < 0) {
                                        parentName = folder;
                                        parentFolder = folder;
                                    } else if (filePath != null) {
                                        String[] splittedPath = folder.split("_");
                                        parentName = splittedPath[splittedPath.length - 1];
                                        parentFolder = folder;
                                    } else {
                                        String[] splittedPath = folder.split("_");
                                        parentName = splittedPath[splittedPath.length - 2];
                                        parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                    }

                                    folderService.getParentRights(parentName, parentFolder, owner,
                                            new Handler<Either<String, JsonArray>>() {
                                                public void handle(Either<String, JsonArray> event) {
                                                    final JsonArray parentSharedRights = event.right() == null
                                                            || event.isLeft() ? null : event.right().getValue();

                                                    if (parentSharedRights != null
                                                            && parentSharedRights.size() > 0)
                                                        dest.put("shared", parentSharedRights);
                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                }
                                            });
                                } else if (filePath != null) {
                                    storage.copyFile(filePath, new Handler<JsonObject>() {

                                        @Override
                                        public void handle(JsonObject event) {
                                            if (event != null && "ok".equals(event.getString("status"))) {
                                                dest.put("file", event.getString("_id"));
                                                persist(insert, number.decrementAndGet());
                                            }
                                        }
                                    });
                                } else {
                                    persist(insert, number.decrementAndGet());
                                }
                            }
                        }
                    });
                } else {
                    renderJson(request, src, 404);
                }
            }

            private void persist(final JsonArray insert, int remains) {
                if (remains == 0) {
                    mongo.insert(DocumentDao.DOCUMENTS_COLLECTION, insert, new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> inserted) {
                            if ("ok".equals(inserted.body().getString("status"))) {
                                incrementStorage(insert);
                                for (Object obj : insert) {
                                    JsonObject json = (JsonObject) obj;
                                    createRevision(json.getString("_id"), json.getString("file"),
                                            json.getString("name"), json.getString("owner"),
                                            json.getString("owner"), json.getString("ownerName"),
                                            json.getJsonObject("metadata"));
                                }
                                renderJson(request, inserted.body());
                            } else {
                                renderError(request, inserted.body());
                            }
                        }
                    });
                }
            }

        });
    } else {
        badRequest(request);
    }
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void flattenShareIds(final JsonArray sharedArray, final UserInfos user,
        final Handler<List<String>> resultHandler) {
    final List<String> recipients = new ArrayList<>();
    final AtomicInteger remaining = new AtomicInteger(sharedArray.size());
    for (Object j : sharedArray) {
        JsonObject json = (JsonObject) j;
        String userId = json.getString("userId");
        if (userId != null) {
            if (!userId.equals(user.getUserId()))
                recipients.add(userId);/*from w w w.j a v  a 2 s  .  c o m*/
            remaining.getAndDecrement();
        } else {
            String groupId = json.getString("groupId");
            if (groupId != null) {
                UserUtils.findUsersInProfilsGroups(groupId, eb, user.getUserId(), false,
                        new Handler<JsonArray>() {
                            public void handle(JsonArray event) {
                                if (event != null) {
                                    for (Object o : event) {
                                        if (!(o instanceof JsonObject))
                                            continue;
                                        JsonObject j = (JsonObject) o;
                                        String id = j.getString("id");
                                        if (!id.equals(user.getUserId()))
                                            recipients.add(id);
                                    }
                                }
                                if (remaining.decrementAndGet() < 1) {
                                    resultHandler.handle(recipients);
                                }
                            }
                        });
            }
        }
    }
    if (remaining.get() < 1) {
        resultHandler.handle(recipients);
    }
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

@Put("/documents/move/:ids/:folder")
@SecuredAction(value = "workspace.manager", type = ActionType.RESOURCE)
public void moveDocuments(final HttpServerRequest request) {
    final String ids = request.params().get("ids"); // TODO refactor with json in request body
    String tempFolder = getOrElse(request.params().get("folder"), "");
    try {// w  w  w  .java  2s .c  om
        tempFolder = URLDecoder.decode(tempFolder, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.warn(e.getMessage(), e);
    }
    final String folder = tempFolder;
    final String cleanedFolder = folder.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))
            .replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("\\\""));

    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {

        @Override
        public void handle(UserInfos user) {
            if (user != null && user.getUserId() != null) {
                if (ids != null && !ids.trim().isEmpty()) {
                    JsonArray idsArray = new fr.wseduc.webutils.collections.JsonArray(
                            Arrays.asList(ids.split(",")));
                    final String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}}";

                    if (folder != null && !folder.trim().isEmpty()) {

                        //If the document has a parent folder, replicate sharing rights
                        String parentName, parentFolder;
                        if (folder.lastIndexOf('_') < 0) {
                            parentName = folder;
                            parentFolder = folder;
                        } else {
                            String[] splittedPath = folder.split("_");
                            parentName = splittedPath[splittedPath.length - 1];
                            parentFolder = folder;
                        }

                        folderService.getParentRights(parentName, parentFolder, user,
                                new Handler<Either<String, JsonArray>>() {
                                    public void handle(Either<String, JsonArray> event) {
                                        final JsonArray parentSharedRights = event.right() == null
                                                || event.isLeft() ? null : event.right().getValue();

                                        String obj = "{ \"$set\" : { \"folder\": \"" + cleanedFolder
                                                + "\", \"modified\" : \"" + MongoDb.formatDate(new Date())
                                                + "\"";
                                        if (parentSharedRights != null && parentSharedRights.size() > 0)
                                            obj += ", \"shared\" : " + parentSharedRights.toString() + " }}";
                                        else
                                            obj += "}, \"$unset\" : { \"shared\": 1 }}";

                                        mongo.update(DocumentDao.DOCUMENTS_COLLECTION, new JsonObject(criteria),
                                                new JsonObject(obj), false, true,
                                                new Handler<Message<JsonObject>>() {
                                                    @Override
                                                    public void handle(Message<JsonObject> r) {
                                                        JsonObject res = r.body();
                                                        if ("ok".equals(res.getString("status"))) {
                                                            renderJson(request, res);
                                                        } else {
                                                            renderJson(request, res, 404);
                                                        }
                                                    }
                                                });
                                    }
                                });
                    } else {
                        String obj = "{ \"$set\" : { \"modified\" : \"" + MongoDb.formatDate(new Date())
                                + "\" }, " + " \"$unset\" : { \"folder\" : 1, \"shared\": 1 }}";

                        mongo.update(DocumentDao.DOCUMENTS_COLLECTION, new JsonObject(criteria),
                                new JsonObject(obj), false, true, new Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> r) {
                                        JsonObject res = r.body();
                                        if ("ok".equals(res.getString("status"))) {
                                            renderJson(request, res);
                                        } else {
                                            renderJson(request, res, 404);
                                        }
                                    }
                                });
                    }
                } else {
                    badRequest(request);
                }
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void addDocument(final Message<JsonObject> message) {
    JsonObject uploaded = message.body().getJsonObject("uploaded");
    JsonObject doc = message.body().getJsonObject("document");
    if (doc == null || uploaded == null) {
        message.reply(new JsonObject().put("status", "error").put("message", "missing.attribute"));
        return;/* w w  w.j  a v  a 2 s  .  c  o  m*/
    }
    String name = message.body().getString("name");
    String application = message.body().getString("application");
    JsonArray t = message.body().getJsonArray("thumbs", new fr.wseduc.webutils.collections.JsonArray());
    List<String> thumbs = new ArrayList<>();
    for (int i = 0; i < t.size(); i++) {
        thumbs.add(t.getString(i));
    }
    addAfterUpload(uploaded, doc, name, application, thumbs, DocumentDao.DOCUMENTS_COLLECTION,
            new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> m) {
                    if (m != null) {
                        message.reply(m.body());
                    }
                }
            });
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void updateDocument(final Message<JsonObject> message) {
    JsonObject uploaded = message.body().getJsonObject("uploaded");
    String id = message.body().getString("id");
    if (uploaded == null || id == null || id.trim().isEmpty()) {
        message.reply(new JsonObject().put("status", "error").put("message", "missing.attribute"));
        return;/*from w  ww .  j  a v  a2s  .  co m*/
    }
    String name = message.body().getString("name");
    JsonArray t = message.body().getJsonArray("thumbs", new fr.wseduc.webutils.collections.JsonArray());
    List<String> thumbs = new ArrayList<>();
    for (int i = 0; i < t.size(); i++) {
        thumbs.add(t.getString(i));
    }
    updateAfterUpload(id, name, uploaded, thumbs, null, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> m) {
            if (m != null) {
                message.reply(m.body());
            }
        }
    });
}

From source file:org.folio.auth.permissions_module.impl.MongoPermissionsStore.java

@Override
public Future<JsonArray> getExpandedPermissions(String permission, String tenant) {
    //System.out.println("Permissions> Expanding permission '"+ permission + "' on tenant '"+
    //        tenant + "'");
    JsonObject query = new JsonObject().put("permission_name", permission).put("tenant", tenant);
    JsonArray permList = new JsonArray();
    Future<JsonArray> future = Future.future();
    mongoClient.find("permissions", query, res -> {
        if (res.succeeded() && res.result().size() > 0) {
            //System.out.println("Permissions> Successfully queried mongo for '"+ permission + "' on tenant '"+
            //    tenant + "'");
            /*/*from  w  w w  .  ja v a  2  s  .co m*/
            If there are no subpermissions, go ahead and complete the future with the
            given value of the JsonArray
                    
            If there are subpermissions, create a list of new futures, by calling
            walkPerms for each sub permission, then create a composite future from
            these new futures, with a handler that completes the original
            future when they return
            */
            JsonObject permObj = res.result().get(0);
            permList.add(permission);
            JsonArray subPerms = permObj.getJsonArray("sub_permissions");
            LinkedList<Future> futureList = new LinkedList<>();
            if (subPerms != null && !subPerms.isEmpty()) {
                logger.debug("Permissions> " + subPerms.size() + " subs to process for '" + permission + "'");
                for (Object o : subPerms) {
                    String sub = (String) o;
                    Future<JsonArray> newFuture = getExpandedPermissions(sub, tenant);
                    futureList.add(newFuture);
                }
                logger.debug("Permissions> Creating CompositeFuture to expand " + permission + " into "
                        + futureList.size() + " subs: " + subPerms.encode());
                CompositeFuture compositeFuture = CompositeFuture.all(futureList);
                compositeFuture.setHandler(res2 -> {
                    if (res2.succeeded()) {
                        //Get output of contained futures and complete the future here
                        for (Future f : futureList) {
                            JsonArray arr = (JsonArray) f.result();
                            for (Object o : arr) {
                                permList.add(o);
                            }
                        }
                        future.complete(permList);
                    } else {
                        future.fail("Unable to populate permissions: " + res2.cause().getMessage());
                    }
                });
            } else {
                //System.out.println("Permissions> No sub-permissions found for '" + permission + "'");
                future.complete(permList);
            }
        } else {
            future.fail("No permission '" + permission + "' found for tenant '" + tenant + "'");
        }
    });
    return future;
}