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

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

Introduction

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

Prototype

public boolean contains(Object value) 

Source Link

Document

Does the JSON array contain the specified value?

Usage

From source file:org.entcore.auth.services.impl.FrEduVecteurService.java

License:Open Source License

public void getVectors(final String userId, final Handler<Either<String, JsonArray>> handler) {
    String queryGetUserProfile = "MATCH (u:User) WHERE u.id = {userId} RETURN u.profiles";
    neo4j.execute(queryGetUserProfile, new JsonObject().put("userId", userId),
            Neo4jResult.validUniqueResultHandler(new Handler<Either<String, JsonObject>>() {
                @Override//ww w .  ja  v  a  2 s . c o m
                public void handle(final Either<String, JsonObject> event) {
                    if (event.isRight()) {
                        JsonObject value = event.right().getValue();
                        if (value == null) {
                            handler.handle(new Either.Left<String, JsonArray>("error : user not found"));
                        } else {
                            JsonArray profiles = value.getJsonArray("u.profiles");
                            if (profiles != null && profiles.size() > 0) {
                                if (profiles.contains("Student")) {
                                    // Get student vectors for saml response : "4|"+u.lastName+"|"+u.firstName+"|"+u.externalId+"|"+s.UAI
                                    String query = "MATCH u-[:IN]->()-[:DEPENDS]->(s:Structure) "
                                            + "WHERE u.id = {userId} "
                                            + "RETURN DISTINCT '4|'+u.lastName+'|'+u.firstName+'|'+u.attachmentId+'|'+s.UAI as FrEduVecteur";

                                    neo4j.execute(query, new JsonObject().put("userId", userId),
                                            validResultHandler(handler));
                                } else if (profiles.contains("Relative")) {
                                    // Get parent vectors for saml response : '2|'+u.lastName+'|'+u.firstName+'|'+ child.externalId+'|'+s.UAI"
                                    String query = "MATCH (child: User)-[:RELATED]->u-[:IN]->()-[:DEPENDS]->(s:Structure) "
                                            + "WHERE u.id = {userId} "
                                            + "RETURN DISTINCT '2|'+u.lastName+'|'+u.firstName+'|'+ child.attachmentId+'|'+s.UAI as FrEduVecteur";

                                    neo4j.execute(query, new JsonObject().put("userId", userId),
                                            validResultHandler(handler));
                                } else {
                                    // We return null for others profiles
                                    handler.handle(
                                            new Either.Left<String, JsonArray>("error : profil not supported"));
                                }
                            }
                        }
                    } else {
                        handler.handle(new Either.Left<String, JsonArray>("error : user or profile not found"));
                    }
                }
            }));
}

From source file:org.entcore.cas.services.BRNERegisteredService.java

License:Open Source License

@Override
protected void prepareUser(User user, String userId, String service, JsonObject data) {
    //return the first uai as principalAttributeName
    for (Object s : data.getJsonArray("structureNodes", new fr.wseduc.webutils.collections.JsonArray())) {
        if (s == null || !(s instanceof JsonObject))
            continue;
        JsonObject structure = (JsonObject) s;
        String uai = structure.getString("UAI", "");
        if (!uai.isEmpty()) {
            user.setUser(uai);//from   w ww. ja  v  a  2  s  .  com
            break;
        }
    }

    user.setAttributes(new HashMap<String, String>());

    // Profile
    JsonArray profiles = data.getJsonArray("type", new fr.wseduc.webutils.collections.JsonArray());
    if (profiles.contains("Teacher")) {
        user.getAttributes().put(PROFIL, "National_3");
    } else if (profiles.contains("Student")) {
        user.getAttributes().put(PROFIL, "National_1");
    }
}

From source file:org.entcore.cas.services.WebclasseursRegisteredService.java

License:Open Source License

@Override
protected void prepareUserCas20(User user, String userId, String service, JsonObject data, Document doc,
        List<Element> additionnalAttributes) {
    user.setUser(data.getString(principalAttributeName));

    try {/*from w  w w  .  j a  va 2 s.  c o  m*/
        // Lastname
        if (data.containsKey("login")) {
            additionnalAttributes.add(createTextElement(WEBCLASSEURS_LOGIN, data.getString("login"), doc));
        }

        // Profile
        JsonArray profiles = data.getJsonArray("type");
        if (profiles.contains("Teacher") || profiles.contains("Personnel")) {
            // Teacher and Personnel seen alike for Webclasseurs
            additionnalAttributes.add(createTextElement(WEBCLASSEURS_PROFILE, "National_3", doc));
        } else if (profiles.contains("Student")) {
            additionnalAttributes.add(createTextElement(WEBCLASSEURS_PROFILE, "National_1", doc));
        } else if (profiles.contains("Relative")) {
            additionnalAttributes.add(createTextElement(WEBCLASSEURS_PROFILE, "National_2", doc));
        }

    } catch (Exception e) {
        log.error("Failed to transform User for Webclasseurs", e);
    }
}

From source file:org.entcore.common.neo4j.Neo4jUtils.java

License:Open Source License

private static void loadAndExecute(final String schema, final Vertx vertx, final String path,
        final boolean index, final JsonArray excludeFileNames) {
    final String pattern = index ? ".*?-index\\.cypher$" : "^(?!.*-index).*?\\.cypher$";
    vertx.fileSystem().readDir(path, pattern, new Handler<AsyncResult<List<String>>>() {
        @Override//from w  w  w. ja v a2  s.  c om
        public void handle(AsyncResult<List<String>> asyncResult) {
            if (asyncResult.succeeded()) {
                final List<String> files = asyncResult.result();
                Collections.sort(files);
                final StatementsBuilder s = new StatementsBuilder();
                final JsonArray newFiles = new fr.wseduc.webutils.collections.JsonArray();
                final AtomicInteger count = new AtomicInteger(files.size());
                for (final String f : files) {
                    final String filename = f.substring(f.lastIndexOf(File.separatorChar) + 1);
                    if (!excludeFileNames.contains(filename)) {
                        vertx.fileSystem().readFile(f, new Handler<AsyncResult<Buffer>>() {
                            @Override
                            public void handle(AsyncResult<Buffer> bufferAsyncResult) {
                                if (bufferAsyncResult.succeeded()) {
                                    String script = bufferAsyncResult.result().toString();
                                    for (String q : script.replaceAll("(\r|\n)", " ").split(";")) {
                                        s.add(q);
                                    }
                                    newFiles.add(filename);
                                } else {
                                    log.error("Error reading file : " + f, bufferAsyncResult.cause());
                                }
                                if (count.decrementAndGet() == 0) {
                                    commit(schema, s, newFiles, index);
                                }
                            }
                        });
                    } else if (count.decrementAndGet() == 0 && newFiles.size() > 0) {
                        commit(schema, s, newFiles, index);
                    }
                }
            } else if (log.isDebugEnabled()) {
                log.debug("Error reading neo4j directory : " + path, asyncResult.cause());
            }
        }

        private void commit(final String schema, StatementsBuilder s, final JsonArray newFiles,
                final boolean index) {
            final JsonObject params = new JsonObject().put("appName", schema).put("newFiles", newFiles);
            if (!index) {
                s.add(UPDATE_SCRIPTS, params);
            }
            Neo4j.getInstance().executeTransaction(s.build(), null, true, new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> message) {
                    if ("ok".equals(message.body().getString("status"))) {
                        if (index) {
                            Neo4j.getInstance().execute(UPDATE_SCRIPTS, params,
                                    new Handler<Message<JsonObject>>() {
                                        @Override
                                        public void handle(Message<JsonObject> event) {
                                            if (!"ok".equals(event.body().getString("status"))) {
                                                log.error("Error update scripts : "
                                                        + event.body().getString("message"));
                                            }
                                        }
                                    });
                        }
                        log.info("Scripts added : " + newFiles.encode());
                    } else {
                        log.error("Error when commit transaction : " + message.body().getString("message"));
                    }
                }
            });
        }
    });
}

From source file:org.entcore.common.sql.SqlResult.java

License:Open Source License

private static void parseShared(JsonObject j) {
    Map<String, JsonObject> shared = new HashMap<>();
    JsonArray a = new fr.wseduc.webutils.collections.JsonArray();
    JsonArray s = new fr.wseduc.webutils.collections.JsonArray(j.getString("shared"));
    JsonArray m = new fr.wseduc.webutils.collections.JsonArray(j.getString("groups"));
    for (Object o : s) {
        if (o == null || !(o instanceof JsonObject))
            continue;
        JsonObject json = (JsonObject) o;
        String member = json.getString("member_id");
        String action = json.getString("action");
        if (member != null && action != null) {
            if (shared.containsKey(member)) {
                shared.get(member).put(action, true);
            } else {
                JsonObject sj = new JsonObject().put(action, true);
                if (m.contains(member)) {
                    sj.put("groupId", member);
                } else {
                    sj.put("userId", member);
                }// w  w w .  j ava  2  s.c  o  m
                shared.put(member, sj);
                a.add(sj);
            }
        }
    }
    j.remove("groups");
    j.put("shared", a);
}

From source file:org.entcore.directory.security.TeacherOfUser.java

License:Open Source License

@Override
public void authorize(final HttpServerRequest resourceRequest, Binding binding, final UserInfos user,
        final Handler<Boolean> handler) {
    RequestUtils.bodyToJson(resourceRequest, new Handler<JsonObject>() {
        @Override/*from  w w  w. j  av  a 2s  .c  o m*/
        public void handle(JsonObject event) {
            if (event != null) {
                JsonArray userIds = event.getJsonArray("users");
                if (userIds == null || userIds.size() == 0 || userIds.contains(user.getUserId())
                        || (!"Teacher".equals(user.getType()) && !"Personnel".equals(user.getType()))) {
                    handler.handle(false);
                    return;
                }
                String query = "MATCH (t:User { id : {teacherId}})-[:IN]->(g:ProfileGroup)-[:DEPENDS]->(c:Class) "
                        + "WITH c " + "MATCH c<-[:DEPENDS]-(og:ProfileGroup)<-[:IN]-(u:User) "
                        + "WHERE u.id IN {userIds} " + "RETURN count(distinct u) = {size} as exists ";
                JsonObject params = new JsonObject().put("userIds", userIds).put("teacherId", user.getUserId())
                        .put("size", userIds.size());
                validateQuery(resourceRequest, handler, query, params);
            } else {
                handler.handle(false);
            }
        }
    });

}

From source file:org.entcore.directory.services.impl.DefaultTimetableService.java

License:Open Source License

@Override
public void updateClassesMapping(final String structureId, final JsonObject mapping,
        final Handler<Either<String, JsonObject>> handler) {

    classesMapping(structureId, new Handler<Either<String, JsonObject>>() {
        @Override/*  ww  w.j  a v  a  2 s . com*/
        public void handle(Either<String, JsonObject> event) {
            if (event.isRight()) {
                final JsonObject cm = event.right().getValue();
                if (cm == null || cm.getJsonArray("unknownClasses") == null) {
                    handler.handle(new Either.Left<String, JsonObject>("missing.classes.mapping"));
                    return;
                }
                final JsonArray uc = cm.getJsonArray("unknownClasses");
                final JsonObject m = mapping.getJsonObject("mapping");
                for (String attr : m.copy().fieldNames()) {
                    if (!uc.contains(attr)) {
                        m.remove(attr);
                    }
                }
                mapping.put("mapping", m.encode());
                final String query = "MATCH (:Structure {id:{id}})<-[:MAPPING]-(cm:ClassesMapping) "
                        + "SET cm.mapping = {mapping} ";
                neo4j.execute(query, mapping.put("id", structureId), validEmptyHandler(handler));
            } else {
                handler.handle(event);
            }
        }
    });
}

From source file:org.entcore.directory.services.impl.DefaultUserService.java

License:Open Source License

@Override
public void listByUAI(List<String> UAI, JsonArray expectedTypes, boolean isExportFull, JsonArray fields,
        Handler<Either<String, JsonArray>> results) {
    if (UAI == null || UAI.isEmpty()) {
        results.handle(new Either.Left<String, JsonArray>("missing.uai"));
        return;//from   ww  w  . java2  s . co m
    } else {
        for (String uaiCode : UAI) {
            if (!StringValidation.isUAI(uaiCode)) {
                results.handle(new Either.Left<String, JsonArray>("invalid.uai"));
                return;
            }
        }
    }

    if (fields == null || fields.size() == 0) {
        fields = new fr.wseduc.webutils.collections.JsonArray().add("id").add("externalId").add("lastName")
                .add("firstName").add("login");
    }

    //user's fields for Full Export
    if (isExportFull) {
        fields.add("email");
        fields.add("emailAcademy");
        fields.add("mobile");
        fields.add("deleteDate");
        fields.add("functions");
        fields.add("displayName");
    }

    // Init params and filter for all type of queries
    String filter = "WHERE s.UAI IN {uai} ";

    JsonObject params = new JsonObject().put("uai", new fr.wseduc.webutils.collections.JsonArray(UAI));

    StringBuilder query = new StringBuilder();
    query.append("MATCH (s:Structure)<-[:DEPENDS]-(cpg:ProfileGroup)");

    // filter by types if needed OR full export
    if (isExportFull || (expectedTypes != null && expectedTypes.size() > 0)) {
        query.append("-[:HAS_PROFILE]->(p:Profile)");
    }
    // filter by types if needed
    if (expectedTypes != null && expectedTypes.size() > 0) {

        filter += "AND p.name IN {expectedTypes} ";
        params.put("expectedTypes", expectedTypes);
    }

    query.append(", cpg<-[:IN]-(u:User) ").append(filter);

    if (fields.contains("administrativeStructure")) {
        query.append("OPTIONAL MATCH u-[:ADMINISTRATIVE_ATTACHMENT]->sa ");
    }

    query.append("RETURN DISTINCT ");

    for (Object field : fields) {
        if ("type".equals(field) || "profile".equals(field)) {
            query.append(" HEAD(u.profiles)");
        } else if ("administrativeStructure".equals(field)) {
            query.append(" sa.externalId ");
        } else {
            query.append(" u.").append(field);
        }
        query.append(" as ").append(field).append(",");
    }
    query.deleteCharAt(query.length() - 1);

    //Full Export : profiles and Structure
    if (isExportFull) {
        query.append(", p.name as profiles");
        query.append(", s.externalId as structures")
                .append(" , CASE WHEN size(u.classes) > 0  THEN  last(collect(u.classes)) END as classes");
    }

    neo.execute(query.toString(), params, validResultHandler(results));
}

From source file:org.entcore.feeder.aaf.AafFeeder.java

License:Open Source License

@Override
public void launch(final Importer importer, final Handler<Message<JsonObject>> handler) throws Exception {
    vertx.fileSystem().readFile(path + File.separator + IMPORT_DIRECTORIES_JSON,
            new Handler<AsyncResult<Buffer>>() {
                @Override//from   w  w w .  j a va 2 s. c  o  m
                public void handle(AsyncResult<Buffer> f) {
                    if (f.succeeded()) {
                        final JsonArray importSubDirectories;
                        try {
                            importSubDirectories = new fr.wseduc.webutils.collections.JsonArray(
                                    f.result().toString());
                        } catch (RuntimeException e) {
                            handler.handle(new ResultMessage().error("invalid.importDirectories.file"));
                            log.error("Invalid importDirectories file.", e);
                            return;
                        }
                        vertx.fileSystem().readDir(path, new Handler<AsyncResult<List<String>>>() {
                            @Override
                            public void handle(AsyncResult<List<String>> event) {
                                if (event.succeeded()) {
                                    final List<String> importsDirs = new ArrayList<>();
                                    for (String dir : event.result()) {
                                        final int idx = dir.lastIndexOf(File.separator);
                                        if (idx >= 0 && dir.length() > idx
                                                && importSubDirectories.contains(dir.substring(idx + 1))) {
                                            importsDirs.add(dir);
                                        }
                                    }
                                    if (importsDirs.size() < 1) {
                                        handler.handle(new ResultMessage().error("missing.subdirectories"));
                                        return;
                                    }
                                    final Handler<Message<JsonObject>>[] handlers = new Handler[importsDirs
                                            .size()];
                                    handlers[handlers.length - 1] = new Handler<Message<JsonObject>>() {
                                        @Override
                                        public void handle(Message<JsonObject> m) {
                                            handler.handle(m);
                                        }
                                    };
                                    for (int i = importsDirs.size() - 2; i >= 0; i--) {
                                        final int j = i + 1;
                                        handlers[i] = new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> m) {
                                                if (m != null && "ok".equals(m.body().getString("status"))) {
                                                    new StructureImportProcessing(importsDirs.get(j), vertx)
                                                            .start(handlers[j]);
                                                } else {
                                                    handler.handle(m);
                                                }
                                            }
                                        };
                                    }
                                    new StructureImportProcessing(importsDirs.get(0), vertx).start(handlers[0]);
                                } else {
                                    handler.handle(new ResultMessage().error(event.cause().getMessage()));
                                }
                            }
                        });
                    } else {
                        new StructureImportProcessing(path, vertx).start(handler);
                    }
                }
            });
}

From source file:org.entcore.feeder.aaf.BaseImportProcessing.java

License:Open Source License

protected void initAcademyPrefix(String file) {
    if (academyPrefix != null)
        return;/*from  www. ja  va2 s . co m*/
    if (file != null && file.contains(File.separator) && vertx.fileSystem()
            .existsBlocking(new File(file).getParent() + File.separator + AafFeeder.IMPORT_DIRECTORIES_JSON)) {
        if (file.endsWith(File.separator)) {
            file = file.substring(0, file.length() - 1);
        }
        try {
            JsonArray importDirectories = new fr.wseduc.webutils.collections.JsonArray(vertx.fileSystem()
                    .readFileBlocking(
                            new File(file).getParent() + File.separator + AafFeeder.IMPORT_DIRECTORIES_JSON)
                    .toString());
            final String[] a = file.split(File.separator);
            final String dirName = a[a.length - 1];
            if (a.length > 1 && importDirectories.contains(dirName)) {
                academyPrefix = dirName + "-";
            } else {
                academyPrefix = "";
            }
        } catch (RuntimeException e) {
            log.error("Invalid import directories files.", e);
            academyPrefix = "";
        }
    } else {
        academyPrefix = "";
    }
}