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

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

Introduction

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

Prototype

public JsonArray getJsonArray(String key) 

Source Link

Document

Get the JsonArray value with the specified key

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 w w  w  .ja  va2 s . com*/
    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  www . j a  v a2  s.  c  o m
        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.helper.NotificationHelper.java

License:Open Source License

public void sendImmediateNotifications(final HttpServerRequest request, final JsonObject json) {
    //Get notification properties (mixin : admin console configuration which overrides default properties)
    final String notificationName = json.getString("notificationName");
    final JsonObject notification = json.getJsonObject("notification");
    configService.getNotificationProperties(notificationName, new Handler<Either<String, JsonObject>>() {
        public void handle(final Either<String, JsonObject> properties) {
            if (properties.isLeft() || properties.right().getValue() == null) {
                log.error("[NotificationHelper] Issue while retrieving notification (" + notificationName
                        + ") properties.");
                return;
            }//from  w w w .j  a va 2 s. c  o m
            final JsonObject notificationProperties = properties.right().getValue();
            //Get users preferences (overrides notification properties)
            NotificationUtils.getUsersPreferences(eb, json.getJsonArray("recipientsIds"),
                    "language: uac.language, tokens: uac.fcmTokens ", new Handler<JsonArray>() {
                        public void handle(final JsonArray userList) {
                            if (userList == null) {
                                log.error("[NotificationHelper] Issue while retrieving users preferences.");
                                return;
                            }
                            mailerService.sendImmediateMails(request, notificationName, notification,
                                    json.getJsonObject("params"), userList, notificationProperties);

                            if (pushNotifService != null && json.containsKey("pushNotif")
                                    && notificationProperties.getBoolean("push-notif")
                                    && !TimelineNotificationsLoader.Restrictions.INTERNAL.name()
                                            .equals(notificationProperties.getString("restriction"))
                                    && !TimelineNotificationsLoader.Restrictions.HIDDEN.name()
                                            .equals(notificationProperties.getString("restriction")))

                                pushNotifService.sendImmediateNotifs(notificationName, json, userList,
                                        notificationProperties);
                        }
                    });
        }
    });
}

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

License:Open Source License

private void getExternalNotifications(final Handler<Either<String, JsonObject>> handler) {
    configService.list(new Handler<Either<String, JsonArray>>() {
        public void handle(Either<String, JsonArray> event) {
            if (event.isLeft()) {
                handler.handle(new Either.Left<String, JsonObject>(event.left().getValue()));
                return;
            }/*from   w w w. j ava  2s  . c o m*/
            final JsonObject restricted = new JsonObject();
            for (String key : registeredNotifications.keySet()) {
                JsonObject notif = new JsonObject(registeredNotifications.get(key));
                String restriction = notif.getString("restriction",
                        TimelineNotificationsLoader.Restrictions.NONE.name());
                for (Object notifConfigObj : event.right().getValue()) {
                    JsonObject notifConfig = (JsonObject) notifConfigObj;
                    if (notifConfig.getString("key", "").equals(key)) {
                        restriction = notifConfig.getString("restriction", restriction);
                        break;
                    }
                }
                if (restriction.equals(TimelineNotificationsLoader.Restrictions.EXTERNAL.name())
                        || restriction.equals(TimelineNotificationsLoader.Restrictions.HIDDEN.name())) {
                    String notifType = notif.getString("type");
                    if (!restricted.containsKey(notifType)) {
                        restricted.put(notifType, new fr.wseduc.webutils.collections.JsonArray());
                    }
                    restricted.getJsonArray(notifType).add(notif.getString("event-type"));
                }
            }
            handler.handle(new Either.Right<String, JsonObject>(restricted));
        }
    });
}

From source file:org.entcore.timeline.services.impl.DefaultPushNotifService.java

License:Open Source License

private void sendUsers(final String notificationName, final JsonObject notification, final JsonArray userList,
        final JsonObject notificationProperties, boolean typeNotification, boolean typeData) {

    for (Object userObj : userList) {
        final JsonObject userPref = ((JsonObject) userObj);

        JsonObject notificationPreference = userPref.getJsonObject("preferences", new JsonObject())
                .getJsonObject("config", new JsonObject()).getJsonObject(notificationName, new JsonObject());

        if (notificationPreference.getBoolean("push-notif", notificationProperties.getBoolean("push-notif"))
                && !TimelineNotificationsLoader.Restrictions.INTERNAL.name()
                        .equals(notificationPreference.getString("restriction",
                                notificationProperties.getString("restriction")))
                && !TimelineNotificationsLoader.Restrictions.HIDDEN.name()
                        .equals(notificationPreference.getString("restriction",
                                notificationProperties.getString("restriction")))
                && userPref.getJsonArray("tokens") != null && userPref.getJsonArray("tokens").size() > 0) {
            for (Object token : userPref.getJsonArray("tokens")) {
                processMessage(notification, "fr", typeNotification, typeData, new Handler<JsonObject>() {
                    @Override/*www. jav  a  2  s . c o m*/
                    public void handle(final JsonObject message) {
                        try {
                            ossFcm.sendNotifications(
                                    new JsonObject().put("message", message.put("token", (String) token)));
                        } catch (Exception e) {
                            log.error("[sendNotificationToUsers] Issue while sending notification ("
                                    + notificationName + ").", e);

                        }
                    }
                });
            }

        }
    }
}

From source file:org.entcore.workspace.controllers.QuotaController.java

License:Open Source License

@Put("/quota")
@SecuredAction(value = "", type = ActionType.RESOURCE)
public void update(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, pathPrefix + "updateQuota", new Handler<JsonObject>() {
        @Override//from  ww  w  . j  a  v a 2  s .  c om
        public void handle(JsonObject object) {
            quotaService.update(object.getJsonArray("users"), object.getLong("quota"),
                    arrayResponseHandler(request));
        }
    });
}

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

License:Open Source License

@Override
public void deleteGroups(JsonArray groups) {
    for (Object o : groups) {
        if (!(o instanceof JsonObject))
            continue;
        final JsonObject j = (JsonObject) o;
        final JsonObject query = MongoQueryBuilder
                .build(QueryBuilder.start("shared.groupId").is(j.getString("group")));
        final Handler<Message<JsonObject>> handler = new Handler<Message<JsonObject>>() {
            @Override/*from www  .j  av  a2s . com*/
            public void handle(Message<JsonObject> event) {
                if (!"ok".equals(event.body().getString("status"))) {
                    log.error("Error updating documents with group " + j.getString("group") + " : "
                            + event.body().encode());
                } else {
                    log.info("Documents with group " + j.getString("group") + " updated : "
                            + event.body().getInteger("number"));
                }
            }
        };
        if (shareOldGroupsToUsers) {
            JsonArray userShare = new fr.wseduc.webutils.collections.JsonArray();
            for (Object u : j.getJsonArray("users")) {
                JsonObject share = new JsonObject().put("userId", u.toString())
                        .put("org-entcore-workspace-service-WorkspaceService|copyDocuments", true)
                        .put("org-entcore-workspace-service-WorkspaceService|getDocument", true);
                userShare.add(share);
            }
            JsonObject update = new JsonObject().put("$addToSet",
                    new JsonObject().put("shared", new JsonObject().put("$each", userShare)));
            mongo.update(DocumentDao.DOCUMENTS_COLLECTION, query, update, false, true, handler);
        } else {
            final MongoUpdateBuilder update = new MongoUpdateBuilder()
                    .pull("shared", new JsonObject().put("groupId", j.getString("group")))
                    .addToSet("old_shared", new JsonObject().put("groupId", j.getString("group")));
            mongo.update(DocumentDao.DOCUMENTS_COLLECTION, query, update.build(), false, true, handler);
        }
    }
}

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

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

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

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

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

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

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

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

From source file:org.etourdot.vertx.marklogic.AbstractTestMarklogicDocument.java

License:Open Source License

protected String getHost() throws InterruptedException {
    HostsOptions option = new HostsOptions();
    CountDownLatch latch = new CountDownLatch(1);
    final String[] host = new String[1];
    mlManagement.getHosts(option, onSuccess(r -> {
        JsonObject items = r.getJsonObject("host-default-list").getJsonObject("list-items");
        JsonObject item = items.getJsonArray("list-item").getJsonObject(0);
        host[0] = item.getString("nameref");
        latch.countDown();/*w  w w.  ja v a  2  s  . com*/
    }));
    awaitLatch(latch);
    return host[0];
}

From source file:org.etourdot.vertx.marklogic.http.impl.response.BulkResponse.java

License:Open Source License

@Override
public void process() {
    response.bodyHandler(buffer -> {//from   w  w w .j  ava  2  s .co m
        final JsonObject jsonResponse = buffer.toJsonObject();
        if (jsonResponse.containsKey("documents")) {
            JsonArray docs = jsonResponse.getJsonArray("documents");
            docs.stream().forEach(doc -> documents.add(Document.create((JsonObject) doc)));
        }
        this.endHandler.handle(this);
    });
}