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

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

Introduction

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

Prototype

@Override
public JsonObject copy() 

Source Link

Document

Copy the JSON object

Usage

From source file:org.entcore.feeder.timetable.edt.EDTImporter.java

License:Open Source License

void addProfesseur(JsonObject currentEntity) {
    final String id = currentEntity.getString(IDENT);
    final String idPronote = structureExternalId + "$" + currentEntity.getString(IDPN);
    userImportedPronoteId.add(idPronote);
    final String[] teacherId = teachersMapping.get(idPronote);
    if (teacherId != null && isNotEmpty(teacherId[0])) {
        teachers.put(id, teacherId[0]);//from  w  w  w  .  j  a  va  2  s  .c  o  m
        if (getSource().equals(teacherId[1])) {
            try {
                final JsonObject user = persEducNat.applyMapping(currentEntity.copy());
                updateUser(user.put(IDPN, idPronote));
            } catch (ValidationException e) {
                report.addError("update.user.error");
            }
        }
    } else {
        findPersEducNat(currentEntity, idPronote, "Teacher");
    }
}

From source file:org.entcore.registry.services.impl.DefaultAppRegistryService.java

License:Open Source License

@Override
public void linkRolesToGroup(String groupId, JsonArray roleIds, Handler<Either<String, JsonObject>> handler) {
    JsonObject params = new JsonObject();
    params.put("groupId", groupId);
    if (groupId != null && !groupId.trim().isEmpty()) {
        String deleteQuery = "MATCH (m:Group)-[r:AUTHORIZED]-(:Role) " + "WHERE m.id = {groupId} " + "DELETE r";
        if (roleIds == null || roleIds.size() == 0) {
            neo.execute(deleteQuery, params, validEmptyHandler(handler));
        } else {//  w ww . j  a  va  2 s  . c o  m
            StatementsBuilder s = new StatementsBuilder().add(deleteQuery, params);
            String createQuery = "MATCH (n:Role), (m:Group) " + "WHERE m.id = {groupId} AND n.id IN {roles} "
                    + "CREATE UNIQUE m-[:AUTHORIZED]->n";
            s.add(createQuery, params.copy().put("roles", roleIds));
            neo.executeTransaction(s.build(), null, true, validEmptyHandler(handler));
        }
    } else {
        handler.handle(new Either.Left<String, JsonObject>("invalid.arguments"));
    }
}

From source file:org.entcore.registry.services.impl.DefaultAppRegistryService.java

License:Open Source License

@Override
public void createApplication(String structureId, JsonObject application, JsonArray actions,
        final Handler<Either<String, JsonObject>> handler) {
    if (defaultValidationParamsNull(handler, application, application.getString("name")))
        return;//from   www. j  a v a 2  s  . co  m
    final String applicationName = application.getString("name");
    final String id = UUID.randomUUID().toString();
    final String address = application.getString("address");
    application.put("scope", new fr.wseduc.webutils.collections.JsonArray(
            "[\"" + application.getString("scope", "").replaceAll("\\s", "\",\"") + "\"]"));
    application.put("id", id);
    final String createApplicationQuery = "MATCH (n:Application) " + "WHERE n.name = {applicationName} "
            + "WITH count(*) AS exists " + "WHERE exists=0 " + "CREATE (m:Application {props}) "
            + "RETURN m.id as id";
    final JsonObject params = new JsonObject().put("applicationName", applicationName);
    if (structureId != null && !structureId.trim().isEmpty()) {
        application.put("structureId", structureId);
    }
    final StatementsBuilder b = new StatementsBuilder().add(createApplicationQuery,
            params.copy().put("props", application));
    if (actions != null && actions.size() > 0) {
        for (Object o : actions) {
            JsonObject json = (JsonObject) o;
            String type;
            List<String> removeLabels = new ArrayList<>();
            removeLabels.add("ResourceAction");
            removeLabels.add("AuthenticatedAction");
            removeLabels.add("WorkflowAction");
            switch (json.getString("type", "WORKFLOW")) {
            case "RESOURCE":
                type = "Resource";
                break;
            case "AUTHENTICATED":
                type = "Authenticated";
                break;
            default:
                type = "Workflow";
                break;
            }
            removeLabels.remove(type + "Action");
            String createAction = "MERGE (a:Action {name:{name}}) " + "REMOVE a:"
                    + Joiner.on(":").join(removeLabels) + " "
                    + "SET a.displayName = {displayName}, a.type = {type}, a:" + type + "Action " + "WITH a "
                    + "MATCH (n:Application) " + "WHERE n.name = {applicationName} "
                    + "CREATE UNIQUE n-[r:PROVIDE]->a " + "RETURN a.name as name";
            b.add(createAction, json.put("applicationName", applicationName).put("type",
                    "SECURED_ACTION_" + json.getString("type", "WORKFLOW")));
        }
        final String removeNotWorkflowInRole = "MATCH (:Role)-[r:AUTHORIZE]->(a:Action) "
                + "WHERE a:ResourceAction OR a:AuthenticatedAction " + "DELETE r";
        b.add(removeNotWorkflowInRole);
    } else if (address != null && !address.trim().isEmpty()) {
        String query2 = "MATCH (n:Application) " + "WHERE n.id = {id} "
                + "CREATE UNIQUE n-[r:PROVIDE]->(a:Action:WorkflowAction {type: {type}, "
                + "name:{name}, displayName:{displayName}}) " + "RETURN a.name as name";
        b.add(query2, new JsonObject().put("id", id).put("type", "SECURED_ACTION_WORKFLOW")
                .put("name", applicationName + "|address").put("displayName", applicationName + ".address"));
    }
    neo.executeTransaction(b.build(), null, true, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> m) {
            JsonArray results = m.body().getJsonArray("results");
            if ("ok".equals(m.body().getString("status")) && results != null) {
                JsonArray r = results.getJsonArray(0);
                JsonObject j;
                if (r.size() > 0) {
                    j = r.getJsonObject(0);
                } else {
                    j = new JsonObject();
                }
                handler.handle(new Either.Right<String, JsonObject>(j));
            } else {
                handler.handle(new Either.Left<String, JsonObject>(m.body().getString("message")));
            }
        }
    });
}

From source file:org.entcore.timeline.events.DefaultTimelineEventStore.java

License:Open Source License

private JsonObject validAndGet(JsonObject json) {
    if (json != null) {
        JsonObject e = json.copy();
        for (String attr : json.fieldNames()) {
            if (!FIELDS.contains(attr) || e.getValue(attr) == null) {
                e.remove(attr);//w ww . jav  a2 s  .  c  o  m
            }
        }
        if (e.getMap().keySet().containsAll(REQUIRED_FIELDS)) {
            return e;
        }
    }
    return null;
}

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

License:Open Source License

@Override
public void copy(final String id, final String n, final String p, final UserInfos owner, final long emptySize,
        final Handler<Either<String, JsonArray>> result) {
    if (owner == null) {
        result.handle(new Either.Left<String, JsonArray>("workspace.invalid.user"));
        return;/*www .  jav a2 s . c  o  m*/
    }
    if (id == null || id.trim().isEmpty()) {
        result.handle(new Either.Left<String, JsonArray>("workspace.folder.not.found"));
        return;
    }
    final String path = getOrElse(p, "");
    //If the folder has a parent folder, replicate sharing rights
    String[] splittedPath = path.split("_");
    String parentName = splittedPath[splittedPath.length - 1];
    String parentFolder = path;

    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();

            QueryBuilder query = QueryBuilder.start("_id").is(id).put("owner").is(owner.getUserId());
            JsonObject keys = new JsonObject().put("folder", 1).put("name", 1);

            mongo.findOne(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query), keys,
                    new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> event) {
                            final String folder = event.body().getJsonObject("result", new JsonObject())
                                    .getString("folder");
                            final String n1 = event.body().getJsonObject("result", new JsonObject())
                                    .getString("name");
                            if ("ok".equals(event.body().getString("status")) && folder != null
                                    && !folder.trim().isEmpty() && n1 != null && !n1.trim().isEmpty()) {
                                final String folderAttr = "folder";
                                QueryBuilder q = QueryBuilder.start("owner").is(owner.getUserId())
                                        .put(folderAttr)
                                        .regex(Pattern.compile("^" + Pattern.quote(folder) + "($|_)"));
                                mongo.find(DOCUMENTS_COLLECTION, MongoQueryBuilder.build(q),
                                        new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> src) {
                                                final JsonArray origs = src.body().getJsonArray("results",
                                                        new fr.wseduc.webutils.collections.JsonArray());
                                                if ("ok".equals(src.body().getString("status"))
                                                        && origs.size() > 0) {
                                                    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) {
                                                        result.handle(new Either.Left<String, JsonArray>(
                                                                "files.too.large"));
                                                        return;
                                                    }
                                                    final AtomicInteger number = new AtomicInteger(
                                                            origs.size());
                                                    final JsonArray insert = new fr.wseduc.webutils.collections.JsonArray();
                                                    String name = (n != null && !n.trim().isEmpty()) ? n : n1;
                                                    final String destFolderName = (path != null
                                                            && !path.trim().isEmpty()) ? path + "_" + name
                                                                    : name;
                                                    QueryBuilder alreadyExist = QueryBuilder.start("owner")
                                                            .is(owner.getUserId()).put("folder")
                                                            .is(destFolderName);
                                                    mongo.count(DOCUMENTS_COLLECTION,
                                                            MongoQueryBuilder.build(alreadyExist),
                                                            new Handler<Message<JsonObject>>() {
                                                                @Override
                                                                public void handle(Message<JsonObject> event) {
                                                                    String destFolder;
                                                                    if ("ok".equals(
                                                                            event.body().getString("status"))
                                                                            && event.body()
                                                                                    .getInteger("count") == 0) {
                                                                        destFolder = destFolderName;
                                                                    } else {
                                                                        destFolder = destFolderName + "-"
                                                                                + format.format(new Date());
                                                                    }
                                                                    for (Object o : origs) {
                                                                        if (!(o instanceof JsonObject))
                                                                            continue;
                                                                        JsonObject orig = (JsonObject) o;
                                                                        final JsonObject dest = orig.copy();
                                                                        String now = MongoDb
                                                                                .formatDate(new Date());
                                                                        dest.remove("_id");
                                                                        dest.put("created", now);
                                                                        dest.put("modified", now);
                                                                        dest.put("folder", dest
                                                                                .getString("folder", "")
                                                                                .replaceFirst(
                                                                                        "^" + Pattern
                                                                                                .quote(folder),
                                                                                        Matcher.quoteReplacement(
                                                                                                destFolder)));
                                                                        dest.put("shared", parentSharedRights);
                                                                        insert.add(dest);
                                                                        String filePath = orig
                                                                                .getString("file");
                                                                        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 {
                                                    result.handle(new Either.Left<String, JsonArray>(
                                                            "workspace.folder.not.found"));
                                                }
                                            }

                                            private void persist(final JsonArray insert, int remains) {
                                                if (remains == 0) {
                                                    mongo.insert(DOCUMENTS_COLLECTION, insert,
                                                            new Handler<Message<JsonObject>>() {
                                                                @Override
                                                                public void handle(
                                                                        Message<JsonObject> inserted) {
                                                                    if ("ok".equals(inserted.body()
                                                                            .getString("status"))) {
                                                                        result.handle(
                                                                                new Either.Right<String, JsonArray>(
                                                                                        insert));
                                                                    } else {
                                                                        result.handle(
                                                                                new Either.Left<String, JsonArray>(
                                                                                        inserted.body()
                                                                                                .getString(
                                                                                                        "message")));
                                                                    }
                                                                }
                                                            });
                                                }
                                            }
                                        });
                            } else {
                                result.handle(new Either.Left<String, JsonArray>("workspace.folder.not.found"));
                            }
                        }
                    });
        }
    });
}

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  ww w  . jav a  2 s.  c  om*/
        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 copyFile(final HttpServerRequest request, final GenericDao dao, final String owner,
        final long emptySize) {
    dao.findById(request.params().get("id"), owner, new Handler<JsonObject>() {

        @Override//w  ww. ja va2 s . com
        public void handle(JsonObject src) {
            if ("ok".equals(src.getString("status")) && src.getJsonObject("result") != null) {
                JsonObject orig = src.getJsonObject("result");
                if (orig.getJsonObject("metadata", new JsonObject()).getLong("size", 0l) > emptySize) {
                    badRequest(request, "file.too.large");
                    return;
                }
                final JsonObject dest = orig.copy();
                String now = MongoDb.formatDate(new Date());
                dest.remove("_id");
                dest.remove("protected");
                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");
                }
                dest.put("created", now);
                dest.put("modified", now);
                String folder = getOrElse(request.params().get("folder"), "");
                try {
                    folder = URLDecoder.decode(folder, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    log.warn(e.getMessage(), e);
                }
                dest.put("folder", folder);
                String filePath = orig.getString("file");
                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(dest);
                            }
                        }
                    });
                } else {
                    persist(dest);
                }
            } else {
                renderJson(request, src, 404);
            }
        }

        private void persist(final JsonObject dest) {
            documentDao.save(dest, new Handler<JsonObject>() {
                @Override
                public void handle(JsonObject res) {
                    if ("ok".equals(res.getString("status"))) {
                        incrementStorage(dest);
                        renderJson(request, res);
                    } else {
                        renderError(request, res);
                    }
                }
            });
        }

    });
}

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

License:Open Source License

private void notifyComment(final HttpServerRequest request, final String id, final UserInfos user,
        final boolean isFolder) {
    final JsonObject params = new JsonObject()
            .put("userUri", "/userbook/annuaire#" + user.getUserId() + "#" + user.getType())
            .put("userName", user.getUsername()).put("appPrefix", pathPrefix + "/workspace");

    final String notifyName = WORKSPACE_NAME.toLowerCase() + "." + (isFolder ? "comment-folder" : "comment");

    //Retrieve the document from DB
    mongo.findOne(DocumentDao.DOCUMENTS_COLLECTION, new JsonObject().put("_id", id),
            new Handler<Message<JsonObject>>() {
                @Override// ww  w.j av  a2 s .  c o m
                public void handle(Message<JsonObject> event) {
                    if ("ok".equals(event.body().getString("status"))
                            && event.body().getJsonObject("result") != null) {
                        final JsonObject document = event.body().getJsonObject("result");
                        params.put("resourceName", document.getString("name", ""));

                        //Handle the parent folder id (null if document is at root level)
                        final Handler<String> folderIdHandler = new Handler<String>() {
                            public void handle(final String folderId) {

                                //Send the notification to the shared network
                                Handler<List<String>> shareNotificationHandler = new Handler<List<String>>() {
                                    public void handle(List<String> recipients) {
                                        JsonObject sharedNotifParams = params.copy();

                                        if (folderId != null) {
                                            sharedNotifParams.put("resourceUri",
                                                    pathPrefix + "/workspace#/shared/folder/" + folderId);
                                        } else {
                                            sharedNotifParams.put("resourceUri",
                                                    pathPrefix + "/workspace#/shared");
                                        }

                                        // don't send comment with share uri at owner
                                        final String o = document.getString("owner");
                                        if (o != null && recipients.contains(o)) {
                                            recipients.remove(o);
                                        }
                                        notification.notifyTimeline(request, notifyName, user, recipients, id,
                                                sharedNotifParams);
                                    }
                                };

                                //'Flatten' the share users & group into a user id list (excluding the current user)
                                flattenShareIds(
                                        document.getJsonArray("shared",
                                                new fr.wseduc.webutils.collections.JsonArray()),
                                        user, shareNotificationHandler);

                                //If the user commenting is not the owner, send a notification to the owner
                                if (!document.getString("owner").equals(user.getUserId())) {
                                    JsonObject ownerNotif = params.copy();
                                    ArrayList<String> ownerList = new ArrayList<>();
                                    ownerList.add(document.getString("owner"));

                                    if (folderId != null) {
                                        ownerNotif.put("resourceUri",
                                                pathPrefix + "/workspace#/folder/" + folderId);
                                    } else {
                                        ownerNotif.put("resourceUri", pathPrefix + "/workspace");
                                    }
                                    notification.notifyTimeline(request, notifyName, user, ownerList, id, null,
                                            ownerNotif, true);
                                }

                            }
                        };

                        //Handle the parent folder result from DB
                        Handler<Message<JsonObject>> folderHandler = new Handler<Message<JsonObject>>() {
                            public void handle(Message<JsonObject> event) {
                                if (!"ok".equals(event.body().getString("status"))
                                        || event.body().getJsonObject("result") == null) {
                                    log.error(
                                            "Unable to send timeline notification : invalid parent folder on resource "
                                                    + id);
                                    return;
                                }

                                final JsonObject folder = event.body().getJsonObject("result");
                                final String folderId = folder.getString("_id");

                                folderIdHandler.handle(folderId);
                            }
                        };

                        //If the document does not have a parent folder
                        if (!isFolder && !document.containsKey("folder") || isFolder
                                && document.getString("folder").equals(document.getString("name"))) {
                            folderIdHandler.handle(null);
                        } else {
                            //If the document has a parent folder
                            String parentFolderPath = document.getString("folder");
                            if (isFolder) {
                                parentFolderPath = parentFolderPath.substring(0,
                                        parentFolderPath.lastIndexOf("_"));
                            }

                            QueryBuilder query = QueryBuilder.start("folder").is(parentFolderPath).and("file")
                                    .exists(false).and("owner").is(document.getString("owner"));

                            //Retrieve the parent folder from DB
                            mongo.findOne(DocumentDao.DOCUMENTS_COLLECTION, MongoQueryBuilder.build(query),
                                    folderHandler);
                        }

                    } else {
                        log.error("Unable to send timeline notification : missing name on resource " + id);
                    }
                }
            });
}

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

License:Open Source License

private void copyFile(JsonObject message, final GenericDao dao, final long emptySize,
        Handler<JsonObject> handler) {
    try {//from  ww w  .j  a v a2  s  .  com
        dao.findById(message.getString("documentId"), message.getString("ownerId"), new Handler<JsonObject>() {
            @Override
            public void handle(JsonObject src) {
                if ("ok".equals(src.getString("status")) && src.getJsonObject("result") != null) {
                    JsonObject orig = src.getJsonObject("result");
                    if (orig.getJsonObject("metadata", new JsonObject()).getLong("size", 0l) > emptySize) {
                        handler.handle(new JsonObject().put("status", "ko").put("error", "file.too.large"));
                        return;
                    }
                    final JsonObject dest = orig.copy();
                    String now = MongoDb.formatDate(new Date());
                    dest.remove("_id");
                    dest.remove("protected");
                    if (message.getBoolean("protected") != null)
                        dest.put("protected", message.getBoolean("protected"));
                    dest.put("application", WORKSPACE_NAME);
                    if (message.getJsonObject("user") != null) {
                        dest.put("owner", message.getJsonObject("user").getString("userId"));
                        dest.put("ownerName", message.getJsonObject("user").getString("userName"));
                        dest.remove("to");
                        dest.remove("from");
                        dest.remove("toName");
                        dest.remove("fromName");
                    }
                    dest.put("created", now);
                    dest.put("modified", now);
                    String folder = getOrElse(message.getString("folder"), "");
                    try {
                        folder = URLDecoder.decode(folder, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        log.warn(e.getMessage(), e);
                    }
                    dest.put("folder", folder);
                    String filePath = orig.getString("file");
                    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(dest);
                                }
                            }
                        });
                    } else {
                        persist(dest);
                    }
                } else {
                    handler.handle(new JsonObject().put("status", "ko").put("error", "not.found"));
                }
            }

            private void persist(final JsonObject dest) {
                documentDao.save(dest, new Handler<JsonObject>() {
                    @Override
                    public void handle(JsonObject res) {
                        if ("ok".equals(res.getString("status"))) {
                            incrementStorage(dest);
                            handler.handle(res);
                        } else {
                            handler.handle(res);
                        }
                    }
                });
            }

        });
    } catch (Exception e) {
        log.error(e);
    }
}