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

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

Introduction

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

Prototype

public JsonObject getJsonObject(int pos) 

Source Link

Document

Get the JsonObject at position pos in the array.

Usage

From source file:org.entcore.portal.controllers.PortalController.java

License:Open Source License

@Get("/theme")
@SecuredAction(value = "portal", type = ActionType.AUTHENTICATED)
public void getTheme(final HttpServerRequest request) {
    final String theme_attr = THEME_ATTRIBUTE + getHost(request);
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override//from   ww  w. j av  a2s .  c om
        public void handle(final UserInfos user) {
            if (user != null) {
                Object t = user.getAttribute(theme_attr);
                if (t != null) {
                    renderJson(request, new JsonObject(t.toString()));
                    return;
                }
                JsonObject urls = config.getJsonObject("urls", new JsonObject());
                final JsonObject theme = new JsonObject().put("template", "/public/template/portal.html")
                        .put("logoutCallback", getLogoutCallback(request, urls));
                String query = "MATCH (n:User)-[:USERBOOK]->u " + "WHERE n.id = {id} " + "RETURN u.theme"
                        + getSkinFromConditions(request).replaceAll("\\W+", "") + " as theme";
                Map<String, Object> params = new HashMap<>();
                params.put("id", user.getUserId());
                Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))) {
                            JsonArray result = event.body().getJsonArray("result");
                            String userTheme = (result != null && result.size() == 1)
                                    ? result.getJsonObject(0).getString("theme")
                                    : null;
                            List<String> t = themes.get(getSkinFromConditions(request));
                            if (userTheme != null && t != null && t.contains(userTheme)) {
                                theme.put("skin", getThemePrefix(request) + "/skins/" + userTheme + "/");
                            } else {
                                theme.put("skin", getThemePrefix(request) + "/skins/default/");
                            }
                        } else {
                            theme.put("skin", getThemePrefix(request) + "/skins/default/");
                        }
                        renderJson(request, theme);
                        UserUtils.addSessionAttribute(eb, user.getUserId(), theme_attr, theme.encode(), null);
                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.registry.filters.AbstractFilter.java

License:Open Source License

private void check(final HttpServerRequest request, String query, JsonObject params,
        final Handler<Boolean> handler) {
    request.pause();//w  w  w .  j av  a 2  s .  com
    neo4j.execute(query, params, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> event) {
            request.resume();
            JsonArray r = event.body().getJsonArray("result");
            handler.handle("ok".equals(event.body().getString("status")) && r != null && r.size() == 1
                    && r.getJsonObject(0).getBoolean("exists", false));
        }
    });
}

From source file:org.entcore.registry.filters.RoleGroupFilter.java

License:Open Source License

@Override
public void authorize(HttpServerRequest request, Binding binding, UserInfos user,
        final Handler<Boolean> handler) {
    Map<String, UserInfos.Function> functions = user.getFunctions();
    final String groupId = request.params().get("groupId");
    final String roleId = request.params().get("roleId");

    if (groupId == null || groupId.trim().isEmpty() || roleId == null || roleId.trim().isEmpty()) {
        handler.handle(false);//from  ww w . j  a va2s. co  m
        return;
    }

    if (functions == null || functions.isEmpty()) {
        handler.handle(false);
        return;
    }
    if (functions.containsKey(DefaultFunctions.SUPER_ADMIN)) {
        handler.handle(true);
        return;
    }
    final UserInfos.Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL);
    if (adminLocal == null || adminLocal.getScope() == null) {
        handler.handle(false);
        return;
    }

    final JsonObject params = new JsonObject().put("groupId", groupId).put("roleId", roleId)
            .put("scopedStructures", new fr.wseduc.webutils.collections.JsonArray(adminLocal.getScope()));

    final String regularQuery = "MATCH (s:Structure)<-[:BELONGS*0..1]-()<-[:DEPENDS]-(:Group {id: {groupId}}), (r:Role) "
            + "WHERE s.id IN {scopedStructures} AND r.id = {roleId} "
            + "AND NOT((:Application {locked: true})-[:PROVIDE]->(:Action)<-[:AUTHORIZE]-(r)) "
            + "OPTIONAL MATCH (ext:Application:External)-[:PROVIDE]->(:Action)<-[:AUTHORIZE]-(r) "
            + "RETURN count(distinct r) = 1 as exists, count(distinct ext) as externalApps";
    final String externalQuery = "MATCH (r:Role {id : {roleId}}), "
            + "(ext:Application:External)-[:PROVIDE]->(:Action)<-[:AUTHORIZE]-(r), "
            + "(s:Structure)-[:HAS_ATTACHMENT*0..]->(p:Structure) "
            + "WHERE s.id IN {scopedStructures} AND p.id = ext.structureId AND (ext.inherits = true OR p = s) "
            + "RETURN (count(distinct r) = 1 AND count(distinct ext) = {nbExt}) as exists";

    neo4j.execute(regularQuery, params, new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> event) {
            JsonArray r = event.body().getJsonArray("result");
            if ("ok".equals(event.body().getString("status")) && r != null && r.size() == 1) {
                boolean exists = r.getJsonObject(0).getBoolean("exists", false);
                int nbExt = r.getJsonObject(0).getInteger("nbExt", 0);
                if (!exists) {
                    handler.handle(false);
                } else if (nbExt == 0) {
                    handler.handle(true);
                } else {
                    neo4j.execute(externalQuery, params.put("nbExt", nbExt),
                            new Handler<Message<JsonObject>>() {
                                public void handle(Message<JsonObject> event) {
                                    JsonArray r = event.body().getJsonArray("result");
                                    if ("ok".equals(event.body().getString("status")) && r != null
                                            && r.size() == 1) {
                                        handler.handle(r.getJsonObject(0).getBoolean("exists", false));
                                    } else {
                                        handler.handle(false);
                                    }
                                }
                            });
                }
            } else {
                handler.handle(false);
            }

        }
    });

}

From source file:org.entcore.registry.filters.WidgetLinkFilter.java

License:Open Source License

@Override
public void authorize(HttpServerRequest request, Binding binding, UserInfos user,
        final Handler<Boolean> handler) {

    Map<String, UserInfos.Function> functions = user.getFunctions();

    if (functions == null || functions.isEmpty()) {
        handler.handle(false);//w  w w.  j  a v a 2 s . c  om
        return;
    }
    if (functions.containsKey(DefaultFunctions.SUPER_ADMIN)) {
        handler.handle(true);
        return;
    }
    final UserInfos.Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL);
    if (adminLocal == null || adminLocal.getScope() == null) {
        handler.handle(false);
        return;
    }

    final String groupId = request.params().get("groupId");
    if (groupId == null || groupId.trim().isEmpty()) {
        handler.handle(false);
        return;
    }

    String query = "MATCH (s:Structure)<-[:BELONGS*0..1]-()<-[:DEPENDS]-(g:Group {id : {groupId}}) "
            + "WHERE s.id IN {adminScope} " + "RETURN count(g) = 1 as exists";
    JsonObject params = new JsonObject().put("groupId", groupId).put("adminScope",
            new fr.wseduc.webutils.collections.JsonArray(adminLocal.getScope()));

    neo4j.execute(query, params, new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> event) {
            JsonArray r = event.body().getJsonArray("result");
            handler.handle("ok".equals(event.body().getString("status")) && r != null && r.size() == 1
                    && r.getJsonObject(0).getBoolean("exists", false));
        }
    });
}

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 w w w. j  a v a  2  s. c o  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.registry.services.impl.DefaultAppRegistryService.java

License:Open Source License

@Override
public void getApplication(String applicationId, final Handler<Either<String, JsonObject>> handler) {
    String query = "MATCH (n:Application) " + "WHERE n.id = {id} " + "RETURN n.id as id, n.name as name, "
            + "n.grantType as grantType, n.secret as secret, n.address as address, "
            + "n.icon as icon, n.target as target, n.displayName as displayName, "
            + "n.scope as scope, n.pattern as pattern, n.casType as casType";
    JsonObject params = new JsonObject().put("id", applicationId);
    neo.execute(query, params, new Handler<Message<JsonObject>>() {
        @Override/*  w w w .  java2s  .co m*/
        public void handle(Message<JsonObject> res) {
            JsonArray r = res.body().getJsonArray("result");
            if (r != null && r.size() == 1) {
                JsonObject j = r.getJsonObject(0);
                JsonArray scope = j.getJsonArray("scope");
                if (scope != null && scope.size() > 0) {
                    j.put("scope", Joiner.on(" ").join(scope));
                } else {
                    j.put("scope", "");
                }
            }
            handler.handle(validUniqueResult(res));
        }
    });
}

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

License:Open Source License

@Override
public void createExternalApplication(String structureId, final JsonObject application,
        final Handler<Either<String, JsonObject>> handler) {
    if (defaultValidationParamsNull(handler, application, application.getString("name"), structureId,
            application.getString("address")))
        return;/*from w  w w. j a va  2 s .  c  o  m*/

    final String applicationName = application.getString("name");
    final String id = UUID.randomUUID().toString();
    application.put("scope", new fr.wseduc.webutils.collections.JsonArray(
            "[\"" + application.getString("scope", "").replaceAll("\\s", "\",\"") + "\"]"));
    application.put("id", id);
    application.put("structureId", structureId);

    /* App creation query */
    final String createApplicationQuery = "MATCH (n:Application) " + "WHERE n.name = {applicationName} "
            + "WITH count(*) AS exists " + "WHERE exists=0 " + "CREATE (m:Application:External {props}) "
            + "RETURN m.id as id";

    final StatementsBuilder b = new StatementsBuilder().add(createApplicationQuery,
            new JsonObject().put("applicationName", applicationName).put("props", application));

    /* Underlying action & role creation query */
    String createActionsAndRolesQuery = "MATCH (n:Application) " + "WHERE n.id = {id} "
            + "CREATE UNIQUE n-[r:PROVIDE]->(a:Action:WorkflowAction {type: {type}, "
            + "name:{name}, displayName:{displayName}}) " + "WITH a "
            + "CREATE UNIQUE (r:Role {id: {roleId}, name: {roleName}, structureId: {structureId}})-[:AUTHORIZE]->(a) "
            + "RETURN r.id as roleId";
    b.add(createActionsAndRolesQuery,
            new JsonObject().put("id", id).put("roleId", UUID.randomUUID().toString())
                    .put("type", "SECURED_ACTION_WORKFLOW").put("name", applicationName + "|address")
                    .put("roleName", applicationName + "- ACCESS ").put("structureId", structureId)
                    .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 appRes = results.getJsonArray(0);
                JsonArray roleRes = results.getJsonArray(1);
                JsonObject j = new JsonObject()
                        .mergeIn(appRes.size() > 0 ? appRes.getJsonObject(0) : new JsonObject())
                        .mergeIn(roleRes.size() > 0 ? roleRes.getJsonObject(0) : 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.controllers.TimelineLambda.java

License:Open Source License

public static void setLambdaTemplateRequest(final HttpServerRequest request, final Map<String, Object> ctx,
        final LocalMap<String, String> eventsI18n, final HashMap<String, JsonObject> lazyEventsI18n) {

    ctx.put("i18n", new Mustache.Lambda() {
        @Override/*from  ww w  . j  a  v a 2  s.  c  om*/
        public void execute(Template.Fragment frag, Writer out) throws IOException {
            String key = frag.execute();
            String language = Utils.getOrElse(I18n.acceptLanguage(request), "fr", false);

            JsonObject timelineI18n;
            if (!lazyEventsI18n.containsKey(language)) {
                String i18n = eventsI18n.get(language.split(",")[0].split("-")[0]);
                i18n = i18n != null ? i18n : "}";
                try {
                    timelineI18n = new JsonObject("{" + i18n.substring(0, i18n.length() - 1) + "}");
                    lazyEventsI18n.put(language, timelineI18n);
                } catch (DecodeException de) {
                    timelineI18n = new JsonObject();
                    log.error("Bad json : " + "{" + i18n.substring(0, i18n.length() - 1) + "}", de);
                }
            } else {
                timelineI18n = lazyEventsI18n.get(language);
            }

            String translatedContents = I18n.getInstance().translate(key, Renders.getHost(request), language);
            if (translatedContents.equals(key)) {
                translatedContents = timelineI18n.getString(key, key);
            }
            Mustache.compiler().compile(translatedContents).execute(ctx, out);
        }
    });

    ctx.put("host", new Mustache.Lambda() {
        @Override
        public void execute(Template.Fragment frag, Writer out) throws IOException {
            String contents = frag.execute();
            if (contents.matches("^(http://|https://).*")) {
                out.write(contents);
            } else {
                String host = Renders.getScheme(request) + "://" + Renders.getHost(request);
                out.write(host + contents);
            }
        }
    });

    ctx.put("nested", new Mustache.Lambda() {
        public void execute(Template.Fragment frag, Writer out) throws IOException {
            String nestedTemplateName = frag.execute();
            String nestedTemplate = (String) ctx.get(nestedTemplateName);
            if (nestedTemplate != null)
                Mustache.compiler().compile(nestedTemplate).execute(ctx, out);
        }
    });

    ctx.put("nestedArray", new Mustache.Lambda() {
        public void execute(Template.Fragment frag, Writer out) throws IOException {
            String nestedTemplatePos = frag.execute();
            JsonArray nestedArray = new fr.wseduc.webutils.collections.JsonArray(
                    (List<Object>) ctx.get("nestedTemplatesArray"));
            try {
                JsonObject nestedTemplate = nestedArray.getJsonObject(Integer.parseInt(nestedTemplatePos) - 1);
                ctx.putAll(nestedTemplate.getJsonObject("params", new JsonObject()).getMap());
                Mustache.compiler().compile(nestedTemplate.getString("template", "")).execute(ctx, out);
            } catch (NumberFormatException e) {
                log.error("Mustache compiler error while parsing a nested template array lambda.");
            }
        }
    });
}

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

License:Open Source License

private void getRecipientsUsers(Date from, final Handler<JsonArray> handler) {
    final JsonObject aggregation = new JsonObject();
    JsonArray pipeline = new fr.wseduc.webutils.collections.JsonArray();
    aggregation.put("aggregate", "timeline").put("allowDiskUse", true).put("pipeline", pipeline);

    JsonObject matcher = MongoQueryBuilder.build(QueryBuilder.start("date").greaterThanEquals(from));
    JsonObject grouper = new JsonObject(
            "{ \"_id\" : \"notifiedUsers\", \"recipients\" : {\"$addToSet\" : \"$recipients.userId\"}}");

    pipeline.add(new JsonObject().put("$match", matcher));
    pipeline.add(new JsonObject().put("$unwind", "$recipients"));
    pipeline.add(new JsonObject().put("$group", grouper));

    mongo.command(aggregation.toString(), new Handler<Message<JsonObject>>() {
        @Override//from www .  j  a v  a 2s.  co m
        public void handle(Message<JsonObject> event) {
            if ("error".equals(event.body().getString("status", "error"))) {
                handler.handle(new fr.wseduc.webutils.collections.JsonArray());
            } else {
                JsonArray r = event.body().getJsonObject("result", new JsonObject()).getJsonArray("result");
                if (r != null && r.size() > 0) {
                    handler.handle(r.getJsonObject(0).getJsonArray("recipients",
                            new fr.wseduc.webutils.collections.JsonArray()));
                } else {
                    handler.handle(new fr.wseduc.webutils.collections.JsonArray());
                }
            }
        }

    });
}

From source file:org.entcore.workspace.security.WorkspaceResourcesProvider.java

License:Open Source License

private void isUserOrAdmin(HttpServerRequest request, UserInfos user, final Handler<Boolean> handler) {
    final String userId = request.params().get("userId");
    if (user.getUserId().equals(userId)) {
        handler.handle(true);//from  www  .j  a v a 2s. c  o  m
        return;
    }
    final UserInfos.Function adminLocal = getFunction(user, handler);
    if (adminLocal == null)
        return;
    String query = "MATCH (s:Structure)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User {id : {userId}}) "
            + "WHERE s.id IN {structures} " + "RETURN count(*) > 0 as exists ";
    JsonObject params = new JsonObject()
            .put("structures", new fr.wseduc.webutils.collections.JsonArray(adminLocal.getScope()))
            .put("userId", userId);
    Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            JsonArray res = message.body().getJsonArray("result");
            handler.handle("ok".equals(message.body().getString("status")) && res != null && res.size() == 1
                    && res.getJsonObject(0).getBoolean("exists", false));
        }
    });
}