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

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

Introduction

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

Prototype

public Object remove(String key) 

Source Link

Document

Remove an entry from this object.

Usage

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

License:Open Source License

@Override
public void listExternalApps(String structureId, final Handler<Either<String, JsonArray>> handler) {
    String filter = "";
    JsonObject params = null;//from ww  w . j  av a2 s . c o  m
    if (structureId != null && !structureId.trim().isEmpty()) {
        filter = ", (s:Structure)-[:HAS_ATTACHMENT*0..]->(p:Structure) "
                + "WHERE HAS(app.structureId) AND s.id = {structure} AND p.id = app.structureId AND r.structureId = app.structureId "
                + "AND (app.inherits = true OR p = s) ";
        params = new JsonObject().put("structure", structureId);
    }
    String query = "MATCH (app:Application:External)-[:PROVIDE]->(act:Action)<-[:AUTHORIZE]-(r:Role) " + filter
            + "WITH app, r, collect(distinct act) as roleActions " + "MATCH (app)-[:PROVIDE]->(action:Action) "
            + "RETURN distinct app as application, collect(action) as actions, collect(distinct {role: r, actions: roleActions}) as roles";
    neo.execute(query, params, validResultHandler(new Handler<Either<String, JsonArray>>() {
        public void handle(Either<String, JsonArray> event) {
            if (event.isLeft()) {
                handler.handle(event);
                return;
            }
            JsonArray rows = event.right().getValue();
            for (Object objRow : rows) {
                JsonObject row = (JsonObject) objRow;
                JsonObject application = row.getJsonObject("application");
                JsonArray actions = row.getJsonArray("actions");
                JsonArray roles = row.getJsonArray("roles");

                JsonObject appData = application.getJsonObject("data");
                JsonArray scope = appData.getJsonArray("scope");
                if (scope != null && scope.size() > 0) {
                    appData.put("scope", Joiner.on(" ").join(scope));
                } else {
                    appData.put("scope", "");
                }
                row.put("data", appData);
                row.remove("application");

                JsonArray actionsCopy = new fr.wseduc.webutils.collections.JsonArray();
                for (Object actionObj : actions) {
                    JsonObject action = (JsonObject) actionObj;
                    JsonObject data = action.getJsonObject("data");
                    actionsCopy.add(data);
                }
                row.put("actions", actionsCopy);

                for (Object roleObj : roles) {
                    JsonObject role = (JsonObject) roleObj;
                    JsonObject data = role.getJsonObject("role").getJsonObject("data");
                    role.put("role", data);
                    JsonArray acts = role.getJsonArray("actions");
                    JsonArray actsCopy = new fr.wseduc.webutils.collections.JsonArray();
                    for (Object actionObj : acts) {
                        JsonObject action = (JsonObject) actionObj;
                        actsCopy.add(action.getJsonObject("data"));
                    }
                    role.put("actions", actsCopy);

                }
            }

            handler.handle(event);
        }
    }));
}

From source file:org.entcore.session.AuthManager.java

License:Open Source License

private void generateSessionInfos(final String userId, final Handler<JsonObject> handler) {
    final String query = "MATCH (n:User {id : {id}}) " + "WHERE HAS(n.login) "
            + "OPTIONAL MATCH n-[:IN]->(gp:Group) " + "OPTIONAL MATCH gp-[:DEPENDS]->(s:Structure) "
            + "OPTIONAL MATCH gp-[:DEPENDS]->(c:Class) "
            + "OPTIONAL MATCH n-[rf:HAS_FUNCTION]->fg-[:CONTAINS_FUNCTION*0..1]->(f:Function) "
            + "OPTIONAL MATCH n<-[:RELATED]-(child:User) " + "RETURN distinct "
            + "n.classes as classNames, n.level as level, n.login as login, COLLECT(distinct [c.id, c.name]) as classes, "
            + "n.lastName as lastName, n.firstName as firstName, n.externalId as externalId, n.federated as federated, "
            + "n.birthDate as birthDate, "
            + "n.displayName as username, HEAD(n.profiles) as type, COLLECT(distinct [child.id, child.lastName, child.firstName]) as childrenInfo, "
            + "COLLECT(distinct [s.id, s.name]) as structures, COLLECT(distinct [f.externalId, rf.scope]) as functions, "
            + "COLLECT(distinct s.UAI) as uai, "
            + "COLLECT(distinct gp.id) as groupsIds, n.federatedIDP as federatedIDP, n.functions as aafFunctions";
    final String query2 = "MATCH (n:User {id : {id}})-[:IN]->()-[:AUTHORIZED]->(:Role)-[:AUTHORIZE]->(a:Action)"
            + "<-[:PROVIDE]-(app:Application) " + "WHERE HAS(n.login) "
            + "RETURN DISTINCT COLLECT(distinct [a.name,a.displayName,a.type]) as authorizedActions, "
            + "COLLECT(distinct [app.name,app.address,app.icon,app.target,app.displayName,app.display,app.prefix]) as apps";
    final String query3 = "MATCH (u:User {id: {id}})-[:IN]->(g:Group)-[auth:AUTHORIZED]->(w:Widget) "
            + "WHERE HAS(u.login) "
            + "AND ( NOT(w<-[:HAS_WIDGET]-(:Application)-[:PROVIDE]->(:WorkflowAction)) "
            + "XOR w<-[:HAS_WIDGET]-(:Application)-[:PROVIDE]->(:WorkflowAction)<-[:AUTHORIZE]-(:Role)<-[:AUTHORIZED]-g )  "
            + "OPTIONAL MATCH (w)<-[:HAS_WIDGET]-(app:Application) "
            + "WITH w, app, collect(auth) as authorizations " + "RETURN DISTINCT COLLECT({"
            + "id: w.id, name: w.name, " + "path: coalesce(app.address, '') + w.path, "
            + "js: coalesce(app.address, '') + w.js, " + "i18n: coalesce(app.address, '') + w.i18n, "
            + "application: app.name, "
            + "mandatory: ANY(a IN authorizations WHERE HAS(a.mandatory) AND a.mandatory = true)"
            + "}) as widgets";
    final String query4 = "MATCH (s:Structure) return s.id as id, s.externalId as externalId";
    final String query5 = "MATCH (u:User {id: {id}})-[:PREFERS]->(uac:UserAppConf) RETURN uac AS preferences";
    JsonObject params = new JsonObject();
    params.put("id", userId);
    JsonArray statements = new fr.wseduc.webutils.collections.JsonArray()
            .add(new JsonObject().put("statement", query).put("parameters", params))
            .add(new JsonObject().put("statement", query2).put("parameters", params))
            .add(new JsonObject().put("statement", query3).put("parameters", params))
            .add(new JsonObject().put("statement", query4))
            .add(new JsonObject().put("statement", query5).put("parameters", params));
    neo4j.executeTransaction(statements, null, true, new Handler<Message<JsonObject>>() {

        @Override/*from  w  ww .java  2  s.com*/
        public void handle(Message<JsonObject> message) {
            JsonArray results = message.body().getJsonArray("results");
            if ("ok".equals(message.body().getString("status")) && results != null && results.size() == 5
                    && results.getJsonArray(0).size() > 0 && results.getJsonArray(1).size() > 0) {
                JsonObject j = results.getJsonArray(0).getJsonObject(0);
                JsonObject j2 = results.getJsonArray(1).getJsonObject(0);
                JsonObject j3 = results.getJsonArray(2).getJsonObject(0);
                JsonObject structureMapping = new JsonObject();
                for (Object o : results.getJsonArray(3)) {
                    if (!(o instanceof JsonObject))
                        continue;
                    JsonObject jsonObject = (JsonObject) o;
                    structureMapping.put(jsonObject.getString("externalId"), jsonObject.getString("id"));
                }
                j.put("userId", userId);
                JsonObject functions = new JsonObject();
                JsonArray actions = new fr.wseduc.webutils.collections.JsonArray();
                JsonArray apps = new fr.wseduc.webutils.collections.JsonArray();
                for (Object o : getOrElse(j2.getJsonArray("authorizedActions"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    JsonArray a = (JsonArray) o;
                    actions.add(new JsonObject().put("name", a.getString(0)).put("displayName", a.getString(1))
                            .put("type", a.getString(2)));
                }
                for (Object o : getOrElse(j2.getJsonArray("apps"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    JsonArray a = (JsonArray) o;
                    apps.add(new JsonObject().put("name", (String) a.getString(0))
                            .put("address", (String) a.getString(1)).put("icon", (String) a.getString(2))
                            .put("target", (String) a.getString(3)).put("displayName", (String) a.getString(4))
                            .put("display", ((a.getValue(5) == null) || a.getBoolean(5)))
                            .put("prefix", (String) a.getString(6)));
                }
                for (Object o : getOrElse(j.getJsonArray("aafFunctions"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (o == null)
                        continue;
                    String[] sf = o.toString().split("\\$");
                    if (sf.length == 5) {
                        JsonObject jo = functions.getJsonObject(sf[1]);
                        if (jo == null) {
                            jo = new JsonObject().put("code", sf[1]).put("functionName", sf[2])
                                    .put("scope", new fr.wseduc.webutils.collections.JsonArray())
                                    .put("structureExternalIds", new fr.wseduc.webutils.collections.JsonArray())
                                    .put("subjects", new JsonObject());
                            functions.put(sf[1], jo);
                        }
                        JsonObject subject = jo.getJsonObject("subjects").getJsonObject(sf[3]);
                        if (subject == null) {
                            subject = new JsonObject().put("subjectCode", sf[3]).put("subjectName", sf[4])
                                    .put("scope", new fr.wseduc.webutils.collections.JsonArray())
                                    .put("structureExternalIds",
                                            new fr.wseduc.webutils.collections.JsonArray());
                            jo.getJsonObject("subjects").put(sf[3], subject);
                        }
                        jo.getJsonArray("structureExternalIds").add(sf[0]);
                        subject.getJsonArray("structureExternalIds").add(sf[0]);
                        String sid = structureMapping.getString(sf[0]);
                        if (sid != null) {
                            jo.getJsonArray("scope").add(sid);
                            subject.getJsonArray("scope").add(sid);
                        }
                    }
                }
                j.remove("aafFunctions");
                for (Object o : getOrElse(j.getJsonArray("functions"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    JsonArray a = (JsonArray) o;
                    String code = a.getString(0);
                    if (code != null) {
                        functions.put(code, new JsonObject().put("code", code).put("scope", a.getJsonArray(1)));
                    }
                }
                final JsonObject children = new JsonObject();
                final List<String> childrenIds = new ArrayList<String>();
                for (Object o : getOrElse(j.getJsonArray("childrenInfo"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    final JsonArray a = (JsonArray) o;
                    final String childId = a.getString(0);
                    if (childId != null) {
                        childrenIds.add(childId);
                        JsonObject jo = children.getJsonObject(childId);
                        if (jo == null) {
                            jo = new JsonObject().put("lastName", a.getString(1)).put("firstName",
                                    a.getString(2));
                            children.put(childId, jo);
                        }
                    }
                }
                j.remove("childrenInfo");
                final List<String> classesIds = new ArrayList<String>();
                final List<String> classesNames = new ArrayList<String>();
                for (Object o : getOrElse(j.getJsonArray("classes"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    final JsonArray c = (JsonArray) o;
                    if (c.getString(0) != null) {
                        classesIds.add(c.getString(0));
                        classesNames.add(c.getString(1));
                    }
                }
                j.remove("classes");
                final List<String> structureIds = new ArrayList<String>();
                final List<String> structureNames = new ArrayList<String>();
                for (Object o : getOrElse(j.getJsonArray("structures"),
                        new fr.wseduc.webutils.collections.JsonArray())) {
                    if (!(o instanceof JsonArray))
                        continue;
                    final JsonArray s = (JsonArray) o;
                    if (s.getString(0) != null) {
                        structureIds.add(s.getString(0));
                        structureNames.add(StringUtils.trimToBlank(s.getString(1)));
                    }
                }
                j.remove("structures");
                j.put("structures", new fr.wseduc.webutils.collections.JsonArray(structureIds));
                j.put("structureNames", new fr.wseduc.webutils.collections.JsonArray(structureNames));
                j.put("classes", new fr.wseduc.webutils.collections.JsonArray(classesIds));
                j.put("realClassesNames", new fr.wseduc.webutils.collections.JsonArray(classesNames));
                j.put("functions", functions);
                j.put("authorizedActions", actions);
                j.put("apps", apps);
                j.put("childrenIds", new fr.wseduc.webutils.collections.JsonArray(childrenIds));
                j.put("children", children);
                final JsonObject cache = (results.getJsonArray(4) != null && results.getJsonArray(4).size() > 0
                        && results.getJsonArray(4).getJsonObject(0) != null)
                                ? results.getJsonArray(4).getJsonObject(0)
                                : new JsonObject();
                j.put("cache", cache);
                j.put("widgets",
                        getOrElse(j3.getJsonArray("widgets"), new fr.wseduc.webutils.collections.JsonArray()));
                handler.handle(j);
            } else {
                handler.handle(null);
            }
        }
    });
}

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/registeredNotifications")
@SecuredAction(value = "", type = ActionType.AUTHENTICATED)
public void registeredNotifications(HttpServerRequest request) {
    JsonArray reply = new fr.wseduc.webutils.collections.JsonArray();
    for (String key : registeredNotifications.keySet()) {
        JsonObject notif = new JsonObject(registeredNotifications.get(key)).put("key", key);
        notif.remove("template");
        reply.add(notif);/*from w  w  w  .j av a2s.  c o m*/
    }
    renderJson(request, reply);
}

From source file:org.entcore.timeline.controllers.TimelineController.java

License:Open Source License

@Get("/notifications-defaults")
@SecuredAction("timeline.external.notifications")
public void mixinConfig(final HttpServerRequest request) {
    configService.list(new Handler<Either<String, JsonArray>>() {
        public void handle(Either<String, JsonArray> event) {
            if (event.isLeft()) {
                badRequest(request);//from ww  w .  j  a v a 2 s.co  m
                return;
            }
            JsonArray admcDefaults = event.right().getValue();
            JsonArray reply = new fr.wseduc.webutils.collections.JsonArray();

            for (String key : registeredNotifications.keySet()) {
                JsonObject notif = new JsonObject(registeredNotifications.get(key)).put("key", key);
                notif.remove("template");
                for (Object admcDefaultObj : admcDefaults) {
                    JsonObject admcDefault = (JsonObject) admcDefaultObj;
                    if (admcDefault.getString("key", "").equals(key)) {
                        notif.mergeIn(admcDefault);
                        notif.remove("_id");
                        break;
                    }
                }
                reply.add(notif);
            }
            renderJson(request, reply);
        }
    });

}

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);
            }//  www  . j  a  v  a2 s.  c om
        }
        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;/* w  ww.  j  a v  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   w w  w  .j  av 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 w w  . j  a va2  s.  co  m*/
        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 restore(final HttpServerRequest request, final GenericDao dao, final String to) {
    final String id = request.params().get("id");
    if (id != null && !id.trim().isEmpty()) {
        dao.findById(id, to, new Handler<JsonObject>() {

            @Override// w w  w. j  ava2  s.c o m
            public void handle(JsonObject res) {
                if ("ok".equals(res.getString("status"))) {
                    JsonObject doc = res.getJsonObject("result");
                    if (doc.getString("old-folder") != null) {
                        doc.put("folder", doc.getString("old-folder"));
                    } else {
                        doc.remove("folder");
                    }
                    doc.remove("old-folder");
                    dao.update(id, doc, to, new Handler<JsonObject>() {
                        @Override
                        public void handle(JsonObject res) {
                            if ("ok".equals(res.getString("status"))) {
                                renderJson(request, res);
                            } else {
                                renderJson(request, res, 404);
                            }
                        }
                    });
                } else {
                    renderJson(request, res, 404);
                }
            }
        });
    } else {
        badRequest(request);
    }
}

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 {/*  w ww.j  a  va 2s.c o m*/
        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);
    }
}