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

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

Introduction

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

Prototype

public Set<String> fieldNames() 

Source Link

Document

Return the set of field names in the JSON objects

Usage

From source file:org.entcore.feeder.csv.CsvFeeder.java

License:Open Source License

public void start(final String profile, final Structure structure, String file, String charset,
        final Importer importer, final Handler<Message<JsonObject>> handler) {
    importer.getReport().addProfile(profile);
    importer.createOrUpdateProfile(STUDENT_PROFILE);
    importer.createOrUpdateProfile(RELATIVE_PROFILE);
    importer.createOrUpdateProfile(PERSONNEL_PROFILE);
    importer.createOrUpdateProfile(TEACHER_PROFILE);
    importer.createOrUpdateProfile(GUEST_PROFILE);
    DefaultFunctions.createOrUpdateFunctions(importer);

    final Validator validator = ManualFeeder.profiles.get(profile);
    //      final Structure structure = importer.getStructure(structureExternalId);
    //      if (structure == null) {
    //         handler.handle(new ResultMessage().error("invalid.structure"));
    //         return;
    //      }//from w ww . j  av  a2 s .c o m

    try {
        CSVReader csvParser = getCsvReader(file, charset);
        final List<String> columns = new ArrayList<>();
        int nbColumns = 0;
        String[] strings;
        int i = 0;
        csvParserWhile: while ((strings = csvParser.readNext()) != null) {
            if (i == 0) {
                columnsMapper.getColumsNames(strings, columns, profile, handler);
                nbColumns = columns.size();
            } else if (!columns.isEmpty()) {
                if (emptyLine(strings)) {
                    i++;
                    continue;
                }
                if (strings.length > nbColumns) {
                    strings = Arrays.asList(strings).subList(0, nbColumns).toArray(new String[nbColumns]);
                }
                JsonObject user = new JsonObject();
                user.put("structures",
                        new fr.wseduc.webutils.collections.JsonArray().add(structure.getExternalId()));
                user.put("profiles", new fr.wseduc.webutils.collections.JsonArray().add(profile));
                List<String[]> classes = new ArrayList<>();

                // Class Admin
                if (isNotEmpty(structure.getOverrideClass())) {
                    String eId = structure.getOverrideClass(); // structure.getExternalId() + '$' + structure.getOverrideClass();
                    //structure.createClassIfAbsent(eId, structure.getOverrideClass());
                    final String[] classId = new String[3];
                    classId[0] = structure.getExternalId();
                    classId[1] = eId;
                    classId[2] = "";
                    classes.add(classId);
                }

                for (int j = 0; j < strings.length; j++) {
                    final String c = columns.get(j);
                    final String v = strings[j].trim();
                    if ((v.isEmpty() && !c.startsWith("child"))
                            || ("classes".equals(c) && isNotEmpty(structure.getOverrideClass())))
                        continue;
                    switch (validator.getType(c)) {
                    case "string":
                        if ("birthDate".equals(c)) {
                            Matcher m = frenchDatePatter.matcher(v);
                            if (m.find()) {
                                user.put(c, m.group(3) + "-" + m.group(2) + "-" + m.group(1));
                            } else {
                                user.put(c, v);
                            }
                        } else {
                            user.put(c, v);
                        }
                        break;
                    case "array-string":
                        JsonArray a = user.getJsonArray(c);
                        if (a == null) {
                            a = new fr.wseduc.webutils.collections.JsonArray();
                            user.put(c, a);
                        }
                        if (("classes".equals(c) || "subjectTaught".equals(c) || "functions".equals(c))
                                && !v.startsWith(structure.getExternalId() + "$")) {
                            a.add(structure.getExternalId() + "$" + v);
                        } else {
                            a.add(v);
                        }
                        break;
                    case "boolean":
                        user.put(c, "true".equals(v.toLowerCase()));
                        break;
                    default:
                        Object o = user.getValue(c);
                        final String v2;
                        if ("childClasses".equals(c) && !v.startsWith(structure.getExternalId() + "$")) {
                            v2 = structure.getExternalId() + "$" + v;
                        } else {
                            v2 = v;
                        }
                        if (o != null) {
                            if (o instanceof JsonArray) {
                                ((JsonArray) o).add(v2);
                            } else {
                                JsonArray array = new fr.wseduc.webutils.collections.JsonArray();
                                array.add(o).add(v2);
                                user.put(c, array);
                            }
                        } else {
                            user.put(c, v2);
                        }
                    }
                    if ("classes".equals(c)) {
                        String[] cc = v.split("\\$");
                        if (cc.length == 2 && !cc[1].matches("[0-9]+")) {
                            final String fosEId = importer.getFieldOfStudy().get(cc[1]);
                            if (fosEId != null) {
                                cc[1] = fosEId;
                            }
                        }
                        String eId = structure.getExternalId() + '$' + cc[0];
                        structure.createClassIfAbsent(eId, cc[0]);
                        final String[] classId = new String[3];
                        classId[0] = structure.getExternalId();
                        classId[1] = eId;
                        classId[2] = (cc.length == 2) ? cc[1] : "";
                        classes.add(classId);
                    }
                }
                String ca;
                long seed;
                JsonArray classesA;
                Object co = user.getValue("classes");
                if (co != null && co instanceof JsonArray) {
                    classesA = (JsonArray) co;
                } else if (co instanceof String) {
                    classesA = new fr.wseduc.webutils.collections.JsonArray().add(co);
                } else {
                    classesA = null;
                }
                if ("Student".equals(profile) && classesA != null && classesA.size() == 1) {
                    seed = defaultStudentSeed;
                    ca = classesA.getString(0);
                } else {
                    ca = String.valueOf(i);
                    seed = System.currentTimeMillis();
                }
                generateUserExternalId(user, ca, structure, seed);
                if ("Student".equals(profile)) {
                    studentExternalIdMapping.put(getHashMapping(user, ca, structure, seed),
                            user.getString("externalId"));
                }
                switch (profile) {
                case "Teacher":
                    importer.createOrUpdatePersonnel(user, TEACHER_PROFILE_EXTERNAL_ID,
                            user.getJsonArray("structures"), classes.toArray(new String[classes.size()][2]),
                            null, true, true);
                    break;
                case "Personnel":
                    importer.createOrUpdatePersonnel(user, PERSONNEL_PROFILE_EXTERNAL_ID,
                            user.getJsonArray("structures"), classes.toArray(new String[classes.size()][2]),
                            null, true, true);
                    break;
                case "Student":
                    importer.createOrUpdateStudent(user, STUDENT_PROFILE_EXTERNAL_ID, null, null,
                            classes.toArray(new String[classes.size()][2]), null, null, true, true);
                    break;
                case "Relative":
                    if (("Intitul".equals(strings[0]) && "Adresse Organisme".equals(strings[1]))
                            || ("".equals(strings[0]) && "Intitul".equals(strings[1])
                                    && "Adresse Organisme".equals(strings[2]))) {
                        break csvParserWhile;
                    }
                    JsonArray linkStudents = new fr.wseduc.webutils.collections.JsonArray();
                    for (String attr : user.fieldNames()) {
                        if ("childExternalId".equals(attr)) {
                            Object o = user.getValue(attr);
                            if (o instanceof JsonArray) {
                                for (Object c : (JsonArray) o) {
                                    if (c instanceof String && !((String) c).trim().isEmpty()) {
                                        linkStudents.add(c);
                                    }
                                }
                            } else if (o instanceof String && !((String) o).trim().isEmpty()) {
                                linkStudents.add(o);
                            }
                        } else if ("childUsername".equals(attr)) {
                            Object childUsername = user.getValue(attr);
                            Object childLastName = user.getValue("childLastName");
                            Object childFirstName = user.getValue("childFirstName");
                            Object childClasses;
                            if (isNotEmpty(structure.getOverrideClass())) {
                                childClasses = structure.getOverrideClass();
                            } else {
                                childClasses = user.getValue("childClasses");
                            }
                            if (childUsername instanceof JsonArray && childLastName instanceof JsonArray
                                    && childFirstName instanceof JsonArray && childClasses instanceof JsonArray
                                    && ((JsonArray) childClasses).size() == ((JsonArray) childLastName).size()
                                    && ((JsonArray) childFirstName).size() == ((JsonArray) childLastName)
                                            .size()) {
                                for (int j = 0; j < ((JsonArray) childUsername).size(); j++) {
                                    String mapping = structure.getExternalId()
                                            + ((JsonArray) childUsername).getString(j).trim()
                                            + ((JsonArray) childLastName).getString(j).trim()
                                            + ((JsonArray) childFirstName).getString(j).trim()
                                            + ((JsonArray) childClasses).getString(j).trim()
                                            + defaultStudentSeed;
                                    relativeStudentMapping(linkStudents, mapping);
                                }
                            } else if (childUsername instanceof String && childLastName instanceof String
                                    && childFirstName instanceof String && childClasses instanceof String) {
                                String mapping = structure.getExternalId() + childLastName.toString().trim()
                                        + childFirstName.toString().trim() + childClasses.toString().trim()
                                        + defaultStudentSeed;
                                relativeStudentMapping(linkStudents, mapping);
                            } else {
                                handler.handle(new ResultMessage().error("invalid.child.mapping"));
                                return;
                            }
                        } else if ("childLastName".equals(attr)
                                && !user.fieldNames().contains("childUsername")) {
                            Object childLastName = user.getValue(attr);
                            Object childFirstName = user.getValue("childFirstName");
                            Object childClasses;
                            if (isNotEmpty(structure.getOverrideClass())) {
                                childClasses = structure.getOverrideClass();
                            } else {
                                childClasses = user.getValue("childClasses");
                            }
                            if (childLastName instanceof JsonArray && childFirstName instanceof JsonArray
                                    && childClasses instanceof JsonArray
                                    && ((JsonArray) childClasses).size() == ((JsonArray) childLastName).size()
                                    && ((JsonArray) childFirstName).size() == ((JsonArray) childLastName)
                                            .size()) {
                                for (int j = 0; j < ((JsonArray) childLastName).size(); j++) {
                                    String mapping = structure.getExternalId()
                                            + ((JsonArray) childLastName).getString(j).trim()
                                            + ((JsonArray) childFirstName).getString(j).trim()
                                            + ((JsonArray) childClasses).getString(j).trim()
                                            + defaultStudentSeed;
                                    relativeStudentMapping(linkStudents, mapping);
                                }
                            } else if (childLastName instanceof String && childFirstName instanceof String
                                    && childClasses instanceof String) {
                                String mapping = structure.getExternalId() + childLastName.toString().trim()
                                        + childFirstName.toString().trim() + childClasses.toString().trim()
                                        + defaultStudentSeed;
                                relativeStudentMapping(linkStudents, mapping);
                            } else {
                                handler.handle(new ResultMessage().error("invalid.child.mapping"));
                                return;
                            }
                        }
                    }
                    importer.createOrUpdateUser(user, linkStudents, true);
                    break;
                case "Guest":
                    importer.createOrUpdateGuest(user, classes.toArray(new String[classes.size()][2]));
                    break;
                }
            }
            i++;
        }

        switch (profile) {
        case "Teacher":
            importer.getPersEducNat().createAndLinkSubjects(structure.getExternalId());
            break;
        case "Relative":
            importer.linkRelativeToClass(RELATIVE_PROFILE_EXTERNAL_ID, null, structure.getExternalId());
            importer.linkRelativeToStructure(RELATIVE_PROFILE_EXTERNAL_ID, null, structure.getExternalId());
            importer.addRelativeProperties(getSource());
            break;
        }
    } catch (Exception e) {
        handler.handle(new ResultMessage().error("csv.exception"));
        log.error("csv.exception", e);
    }
    //      importer.markMissingUsers(structure.getExternalId(), new Handler<Void>() {
    //         @Override
    //         public void handle(Void event) {
    //            importer.persist(handler);
    //         }
    //      });
    //   importer.persist(handler);
}

From source file:org.entcore.feeder.csv.CsvValidator.java

License:Open Source License

private void validateFile(final String path, final String profile, final List<String> columns,
        final JsonArray existExternalId, final String charset, final Handler<JsonObject> handler) {
    addProfile(profile);/*from ww  w .  j ava2  s. c  o m*/
    final Validator validator = profiles.get(profile);
    getStructure(path.substring(0, path.lastIndexOf(File.separator)), new Handler<Structure>() {
        @Override
        public void handle(final Structure structure) {
            if (structure == null) {
                addError(profile, "invalid.structure");
                handler.handle(result);
                return;
            }
            final JsonObject checkChildExists = new JsonObject();
            try {
                CSVReader csvParser = getCsvReader(path, charset, 1);
                final int nbColumns = columns.size();
                String[] strings;
                int i = 1;
                csvParserWhile: while ((strings = csvParser.readNext()) != null) {
                    if (emptyLine(strings)) {
                        i++;
                        continue;
                    }
                    if (strings.length > nbColumns) {
                        strings = Arrays.asList(strings).subList(0, nbColumns).toArray(new String[nbColumns]);
                    }
                    //                  if (strings.length != nbColumns) {
                    //                     addErrorByFile(profile, "bad.columns.number", "" + ++i);
                    //                     continue;
                    //                  }
                    final JsonArray classesNames = new fr.wseduc.webutils.collections.JsonArray();
                    JsonObject user = new JsonObject();
                    user.put("structures",
                            new fr.wseduc.webutils.collections.JsonArray().add(structure.getExternalId()));
                    user.put("profiles", new fr.wseduc.webutils.collections.JsonArray().add(profile));
                    List<String[]> classes = new ArrayList<>();
                    for (int j = 0; j < strings.length; j++) {
                        if (j >= columns.size()) {
                            addErrorByFile(profile, "out.columns", "" + i);
                            return;
                        }
                        final String c = columns.get(j);
                        final String v = strings[j].trim();
                        if (v.isEmpty() && !c.startsWith("child"))
                            continue;
                        switch (validator.getType(c)) {
                        case "string":
                            if ("birthDate".equals(c)) {
                                Matcher m = frenchDatePatter.matcher(v);
                                if (m.find()) {
                                    user.put(c, m.group(3) + "-" + m.group(2) + "-" + m.group(1));
                                } else {
                                    user.put(c, v);
                                }
                            } else {
                                user.put(c, v);
                            }
                            break;
                        case "array-string":
                            JsonArray a = user.getJsonArray(c);
                            if (a == null) {
                                a = new fr.wseduc.webutils.collections.JsonArray();
                                user.put(c, a);
                            }
                            if (("classes".equals(c) || "subjectTaught".equals(c) || "functions".equals(c))
                                    && !v.startsWith(structure.getExternalId() + "$")) {
                                a.add(structure.getExternalId() + "$" + v);
                            } else {
                                a.add(v);
                            }
                            break;
                        case "boolean":
                            user.put(c, "true".equals(v.toLowerCase()));
                            break;
                        default:
                            Object o = user.getValue(c);
                            final String v2;
                            if ("childClasses".equals(c) && !v.startsWith(structure.getExternalId() + "$")) {
                                v2 = structure.getExternalId() + "$" + v;
                            } else {
                                v2 = v;
                            }
                            if (o != null) {
                                if (o instanceof JsonArray) {
                                    ((JsonArray) o).add(v2);
                                } else {
                                    JsonArray array = new fr.wseduc.webutils.collections.JsonArray();
                                    array.add(o).add(v2);
                                    user.put(c, array);
                                }
                            } else {
                                user.put(c, v2);
                            }
                        }
                        if ("classes".equals(c)) {
                            String eId = structure.getExternalId() + '$' + v;
                            String[] classId = new String[2];
                            classId[0] = structure.getExternalId();
                            classId[1] = eId;
                            classes.add(classId);
                            classesNames.add(v);
                        }
                    }
                    String ca;
                    long seed;
                    JsonArray classesA;
                    Object co = user.getValue("classes");
                    if (co != null && co instanceof JsonArray) {
                        classesA = (JsonArray) co;
                    } else if (co instanceof String) {
                        classesA = new fr.wseduc.webutils.collections.JsonArray().add(co);
                    } else {
                        classesA = null;
                    }
                    if ("Student".equals(profile) && classesA != null && classesA.size() == 1) {
                        seed = defaultStudentSeed;
                        ca = classesA.getString(0);
                    } else {
                        ca = String.valueOf(i);
                        seed = System.currentTimeMillis();
                    }
                    final State state;
                    final String externalId = user.getString("externalId");
                    if (externalId == null || externalId.trim().isEmpty()) {
                        generateUserExternalId(user, ca, structure, seed);
                        state = State.NEW;
                    } else {
                        if (existExternalId.contains(externalId)) {
                            state = State.UPDATED;
                            studentExternalIdMapping.put(getHashMapping(user, ca, structure, seed), externalId);
                        } else {
                            state = State.NEW;
                        }
                    }
                    switch (profile) {
                    case "Relative":
                        boolean checkChildMapping = true;
                        JsonArray linkStudents = new fr.wseduc.webutils.collections.JsonArray();
                        if ("Intitul".equals(strings[0]) && "Adresse Organisme".equals(strings[1])) {
                            break csvParserWhile;
                        }
                        user.put("linkStudents", linkStudents);
                        for (String attr : user.fieldNames()) {
                            if ("childExternalId".equals(attr)) {
                                if (checkChildMapping) {
                                    checkChildMapping = false;
                                }
                                Object o = user.getValue(attr);
                                if (o instanceof JsonArray) {
                                    for (Object c : (JsonArray) o) {
                                        linkStudents.add(c);
                                    }
                                } else {
                                    linkStudents.add(o);
                                }
                            } else if ("childUsername".equals(attr)) {
                                Object childUsername = user.getValue(attr);
                                Object childLastName = user.getValue("childLastName");
                                Object childFirstName = user.getValue("childFirstName");
                                Object childClasses;
                                if (isNotEmpty(structure.getOverrideClass())) {
                                    childClasses = structure.getOverrideClass();
                                } else {
                                    childClasses = user.getValue("childClasses");
                                }
                                if (childUsername instanceof JsonArray && childLastName instanceof JsonArray
                                        && childFirstName instanceof JsonArray
                                        && childClasses instanceof JsonArray
                                        && ((JsonArray) childClasses).size() == ((JsonArray) childLastName)
                                                .size()
                                        && ((JsonArray) childFirstName).size() == ((JsonArray) childLastName)
                                                .size()) {
                                    for (int j = 0; j < ((JsonArray) childUsername).size(); j++) {
                                        String mapping = structure.getExternalId()
                                                + ((JsonArray) childUsername).getString(j).trim()
                                                + ((JsonArray) childLastName).getString(j).trim()
                                                + ((JsonArray) childFirstName).getString(j).trim()
                                                + ((JsonArray) childClasses).getString(j).trim()
                                                + defaultStudentSeed;
                                        relativeStudentMapping(linkStudents, mapping);
                                    }
                                } else if (childUsername instanceof String && childLastName instanceof String
                                        && childFirstName instanceof String && childClasses instanceof String) {
                                    String mapping = structure.getExternalId() + childLastName.toString().trim()
                                            + childFirstName.toString().trim() + childClasses.toString().trim()
                                            + defaultStudentSeed;
                                    relativeStudentMapping(linkStudents, mapping);
                                } else {
                                    addErrorByFile(profile, "invalid.child.mapping", "" + (i + 1),
                                            "childLUsername");
                                    handler.handle(result);
                                    return;
                                }
                            } else if ("childLastName".equals(attr)
                                    && !user.fieldNames().contains("childUsername")) {
                                Object childLastName = user.getValue(attr);
                                Object childFirstName = user.getValue("childFirstName");
                                Object childClasses;
                                if (isNotEmpty(structure.getOverrideClass())) {
                                    childClasses = structure.getOverrideClass();
                                } else {
                                    childClasses = user.getValue("childClasses");
                                }
                                if (childLastName instanceof JsonArray && childFirstName instanceof JsonArray
                                        && childClasses instanceof JsonArray
                                        && ((JsonArray) childClasses).size() == ((JsonArray) childLastName)
                                                .size()
                                        && ((JsonArray) childFirstName).size() == ((JsonArray) childLastName)
                                                .size()) {
                                    for (int j = 0; j < ((JsonArray) childLastName).size(); j++) {
                                        String mapping = structure.getExternalId()
                                                + ((JsonArray) childLastName).getString(j)
                                                + ((JsonArray) childFirstName).getString(j)
                                                + ((JsonArray) childClasses).getString(j) + defaultStudentSeed;
                                        relativeStudentMapping(linkStudents, mapping);
                                    }
                                } else if (childLastName instanceof String && childFirstName instanceof String
                                        && childClasses instanceof String) {
                                    String mapping = structure.getExternalId() + childLastName.toString().trim()
                                            + childFirstName.toString().trim() + childClasses.toString().trim()
                                            + defaultStudentSeed;
                                    relativeStudentMapping(linkStudents, mapping);
                                } else {
                                    addErrorByFile(profile, "invalid.child.mapping", "" + (i + 1),
                                            "childLastName & childFirstName");
                                    handler.handle(result);
                                    return;
                                }
                            }
                        }
                        if (checkChildMapping || classesNamesMapping.size() > 0) {
                            for (Object o : linkStudents) {
                                if (!(o instanceof String))
                                    continue;
                                if (classesNamesMapping.get(o) != null) {
                                    classesNames.add(classesNamesMapping.get(o));
                                }
                            }
                            if (classesNames.size() == 0) {
                                addSoftErrorByFile(profile, "missing.student.soft", "" + (i + 1),
                                        user.getString("firstName"), user.getString("lastName"));
                            }
                        } else {
                            Object c = user.getValue("childExternalId");
                            JsonObject u = new JsonObject().put("lastName", user.getString("lastName"))
                                    .put("firstName", user.getString("firstName")).put("line", i);
                            if (c instanceof String) {
                                c = new JsonArray().add(c);
                            }
                            if (c instanceof JsonArray) {
                                for (Object ceId : ((JsonArray) c)) {
                                    if (isEmpty((String) ceId))
                                        continue;
                                    JsonArray jr = checkChildExists.getJsonArray((String) ceId);
                                    if (jr == null) {
                                        jr = new JsonArray();
                                        checkChildExists.put((String) ceId, jr);
                                    }
                                    jr.add(u);
                                }
                            }
                        }
                        break;
                    }
                    String error = validator.validate(user, acceptLanguage);
                    if (error != null) {
                        log.warn(error);
                        addErrorByFile(profile, "validator.errorWithLine", "" + (i + 1), error); // Note that 'error' is already translated
                    } else {
                        final String classesStr = Joiner.on(", ").join(classesNames);
                        if (!"Relative".equals(profile)) {
                            classesNamesMapping.put(user.getString("externalId"), classesStr);
                        }
                        addUser(profile, user.put("state", translate(state.name()))
                                .put("translatedProfile", translate(profile)).put("classesStr", classesStr));
                    }
                    i++;
                }
            } catch (Exception e) {
                addError(profile, "csv.exception");
                log.error("csv.exception", e);
            }
            if (!checkChildExists.isEmpty()) {
                final String query = "MATCH (u:User) " + "WHERE u.externalId IN {childExternalIds} "
                        + "RETURN COLLECT(u.externalId) as childExternalIds ";
                final JsonObject params = new JsonObject().put("childExternalIds",
                        new JsonArray(new ArrayList<>(checkChildExists.fieldNames())));
                Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))) {
                            JsonArray existsChilds = getOrElse(
                                    getOrElse(getOrElse(event.body().getJsonArray("result"), new JsonArray())
                                            .getJsonObject(0), new JsonObject())
                                                    .getJsonArray("childExternalIds"),
                                    new JsonArray());
                            for (String cexternalId : checkChildExists.fieldNames()) {
                                if (!existsChilds.contains(cexternalId)) {
                                    for (Object o : checkChildExists.getJsonArray(cexternalId)) {
                                        if (!(o instanceof JsonObject))
                                            continue;
                                        JsonObject user = (JsonObject) o;
                                        addSoftErrorByFile(profile, "missing.student.soft",
                                                "" + (user.getInteger("line") + 1), user.getString("firstName"),
                                                user.getString("lastName"));
                                    }
                                }
                            }
                        }
                        handler.handle(result);
                    }
                });
            } else {
                handler.handle(result);
            }
        }
    });

}

From source file:org.entcore.feeder.dictionary.structures.PostImport.java

License:Open Source License

private void wsCall(JsonObject object) {
    for (String url : object.fieldNames()) {
        final JsonArray endpoints = object.getJsonArray(url);
        if (endpoints == null || endpoints.size() < 1)
            continue;
        try {//from   ww w.  j  a  v a2s. c  o m
            final URI uri = new URI(url);
            HttpClientOptions options = new HttpClientOptions().setDefaultHost(uri.getHost())
                    .setDefaultPort(uri.getPort()).setMaxPoolSize(16).setSsl("https".equals(uri.getScheme()))
                    .setConnectTimeout(10000).setKeepAlive(false);
            final HttpClient client = vertx.createHttpClient(options);

            final Handler[] handlers = new Handler[endpoints.size() + 1];
            handlers[handlers.length - 1] = new Handler<Void>() {
                @Override
                public void handle(Void v) {
                    client.close();
                }
            };
            for (int i = endpoints.size() - 1; i >= 0; i--) {
                final int ji = i;
                handlers[i] = new Handler<Void>() {
                    @Override
                    public void handle(Void v) {
                        final JsonObject j = endpoints.getJsonObject(ji);
                        logger.info("endpoint : " + j.encode());
                        final HttpClientRequest req = client.request(HttpMethod.valueOf(j.getString("method")),
                                j.getString("uri"), new Handler<HttpClientResponse>() {
                                    @Override
                                    public void handle(HttpClientResponse resp) {
                                        if (resp.statusCode() >= 300) {
                                            logger.warn("Endpoint " + j.encode() + " error : "
                                                    + resp.statusCode() + " " + resp.statusMessage());
                                        }
                                        handlers[ji + 1].handle(null);
                                    }
                                });
                        JsonObject headers = j.getJsonObject("headers");
                        if (headers != null && headers.size() > 0) {
                            for (String h : headers.fieldNames()) {
                                req.putHeader(h, headers.getString(h));
                            }
                        }
                        req.exceptionHandler(
                                e -> logger.error("Error in ws call post import : " + j.encode(), e));
                        if (j.getString("body") != null) {
                            req.end(j.getString("body"));
                        } else {
                            req.end();
                        }
                    }
                };
            }
            handlers[0].handle(null);
        } catch (URISyntaxException e) {
            logger.error("Invalid uri in ws call after import : " + url, e);
        }
    }
}

From source file:org.entcore.feeder.dictionary.users.AbstractUser.java

License:Open Source License

public JsonObject applyMapping(JsonObject object) throws ValidationException {
    if (mapping != null) {
        final JsonObject res = new JsonObject();
        for (String attr : object.fieldNames()) {
            if (mapping.containsKey(attr)) {
                String s = object.getString(attr);
                JsonObject j = mapping.getJsonObject(attr);
                if (j == null) {
                    throw new ValidationException("Unknown attribute " + attr);
                }//w  w w .  j  ava 2 s  .c  o  m
                // TODO implement types management
                //String type = j.getString("type");
                String attribute = j.getString("attribute");
                if ("birthDate".equals(attribute)) {
                    s = convertDate(s);
                } else if ("deprecated".equals(attribute)) {
                    continue;
                }
                res.put(attribute, s);
            }
        }
        return res;
    }
    return null;
}

From source file:org.entcore.feeder.dictionary.users.PersEducNat.java

License:Open Source License

public void createOrUpdatePersonnel(JsonObject object, String profileExternalId,
        JsonArray structuresByFunctions, String[][] linkClasses, String[][] linkGroups, boolean nodeQueries,
        boolean relationshipQueries) {
    final String error = personnelValidator.validate(object);
    if (error != null) {
        if (object.getJsonArray("profiles") != null && object.getJsonArray("profiles").size() == 1) {
            report.addIgnored(object.getJsonArray("profiles").getString(0), error, object);
        } else {/*from w  w  w .  j  ava 2 s  . c  om*/
            report.addIgnored("Personnel", error, object);
        }
        log.warn(error);
    } else {
        if (nodeQueries) {
            object.put("source", currentSource);
            if (userImportedExternalId != null) {
                userImportedExternalId.add(object.getString("externalId"));
            }
            StringBuilder sb = new StringBuilder();
            JsonObject params;
            sb.append("MERGE (u:`User` { externalId : {externalId}}) ");
            sb.append("ON CREATE SET u.id = {id}, u.login = {login}, u.activationCode = {activationCode}, ");
            sb.append("u.displayName = {displayName}, u.created = {created} ");
            sb.append("WITH u ");
            if (!EDTImporter.EDT.equals(currentSource)) {
                sb.append("WHERE u.checksum IS NULL OR u.checksum <> {checksum} ");
            }
            sb.append("SET ").append(Neo4jUtils.nodeSetPropertiesFromJson("u", object, "id", "externalId",
                    "login", "activationCode", "displayName", "email", "created"));
            if (EDTImporter.EDT.equals(currentSource)) {
                sb.append("RETURN u.id as id, u.IDPN as IDPN, head(u.profiles) as profile");
            }
            params = object;
            transactionHelper.add(sb.toString(), params);
            checkUpdateEmail(object);
        }
        if (relationshipQueries) {
            final String externalId = object.getString("externalId");
            JsonArray structures = getMappingStructures(object.getJsonArray("structures"));
            if (externalId != null && structures != null && structures.size() > 0) {
                String query;
                JsonObject p = new JsonObject().put("userExternalId", externalId);
                if (structures.size() == 1) {
                    query = "MATCH (s:Structure {externalId : {structureAdmin}}), (u:User {externalId : {userExternalId}}) "
                            + "MERGE u-[:ADMINISTRATIVE_ATTACHMENT]->s ";
                    p.put("structureAdmin", structures.getString(0));
                } else {
                    query = "MATCH (s:Structure), (u:User {externalId : {userExternalId}}) "
                            + "WHERE s.externalId IN {structuresAdmin} "
                            + "MERGE u-[:ADMINISTRATIVE_ATTACHMENT]->s ";
                    p.put("structuresAdmin", structures);
                }
                transactionHelper.add(query, p);
            }
            if (externalId != null && structuresByFunctions != null && structuresByFunctions.size() > 0) {
                String query;
                structuresByFunctions = getMappingStructures(structuresByFunctions);
                JsonObject p = new JsonObject().put("userExternalId", externalId);
                if (structuresByFunctions.size() == 1) {
                    query = "MATCH (s:Structure {externalId : {structureAdmin}})<-[:DEPENDS]-(g:ProfileGroup)-[:HAS_PROFILE]->(p:Profile {externalId : {profileExternalId}}), "
                            + "(u:User { externalId : {userExternalId}}) " + "WHERE NOT(HAS(u.mergedWith)) "
                            + "MERGE u-[:IN]->g";
                    p.put("structureAdmin", structuresByFunctions.getString(0)).put("profileExternalId",
                            profileExternalId);
                } else {
                    query = "MATCH (s:Structure)<-[:DEPENDS]-(g:ProfileGroup)-[:HAS_PROFILE]->(p:Profile), "
                            + "(u:User { externalId : {userExternalId}}) "
                            + "WHERE s.externalId IN {structuresAdmin} AND NOT(HAS(u.mergedWith)) "
                            + "AND p.externalId = {profileExternalId} " + "MERGE u-[:IN]->g ";
                    p.put("structuresAdmin", structuresByFunctions).put("profileExternalId", profileExternalId);
                }
                transactionHelper.add(query, p);
                String qs = "MATCH (:User {externalId : {userExternalId}})-[r:IN|COMMUNIQUE]-(:Group)-[:DEPENDS]->(s:Structure) "
                        + "WHERE NOT(s.externalId IN {structures}) AND (NOT(HAS(r.source)) OR r.source = {source}) "
                        + "DELETE r";
                JsonObject ps = new JsonObject().put("userExternalId", externalId).put("source", currentSource)
                        .put("structures", structuresByFunctions);
                transactionHelper.add(qs, ps);
                final String daa = "MATCH (u:User {externalId : {userExternalId}})-[r:ADMINISTRATIVE_ATTACHMENT]->(s:Structure) "
                        + "WHERE NOT(s.externalId IN {structures}) AND (NOT(HAS(r.source)) OR r.source = {source}) "
                        + "DELETE r";
                transactionHelper.add(daa, ps.copy().put("structures", getOrElse(structures, new JsonArray())));
            }
            final JsonObject fosm = new JsonObject();
            final JsonArray classes = new fr.wseduc.webutils.collections.JsonArray();
            if (externalId != null && linkClasses != null) {
                final JsonObject fcm = new JsonObject();
                for (String[] structClass : linkClasses) {
                    if (structClass != null && structClass[0] != null && structClass[1] != null) {
                        classes.add(structClass[1]);
                        if (structClass.length > 2 && isNotEmpty(structClass[2])) {
                            JsonArray fClasses = fcm.getJsonArray(structClass[2]);
                            if (fClasses == null) {
                                fClasses = new fr.wseduc.webutils.collections.JsonArray();
                                fcm.put(structClass[2], fClasses);
                            }
                            fClasses.add(structClass[1]);
                        }
                    }
                }
                String query = "MATCH (c:Class)<-[:DEPENDS]-(g:ProfileGroup)"
                        + "-[:DEPENDS]->(pg:ProfileGroup)-[:HAS_PROFILE]->(p:Profile {externalId : {profileExternalId}}), "
                        + "(u:User { externalId : {userExternalId}}) "
                        + "WHERE c.externalId IN {classes} AND NOT(HAS(u.mergedWith)) " + "MERGE u-[:IN]->g";
                JsonObject p0 = new JsonObject().put("userExternalId", externalId)
                        .put("profileExternalId", profileExternalId).put("classes", classes);
                transactionHelper.add(query, p0);
                JsonObject p = new JsonObject().put("userExternalId", externalId).put("source", currentSource)
                        .put("classes", classes);
                fosm.mergeIn(fcm);
                for (String fos : fcm.fieldNames()) {
                    String q2 = "MATCH (u:User {externalId : {userExternalId}}), (f:FieldOfStudy {externalId:{feId}}) "
                            + "MERGE u-[r:TEACHES_FOS]->f " + "SET r.classes = {classes} ";
                    transactionHelper.add(q2, p.copy().put("classes", fcm.getJsonArray(fos)).put("feId", fos));
                }
            }
            if (externalId != null) {
                String q = "MATCH (:User {externalId : {userExternalId}})-[r:IN|COMMUNIQUE]-(:Group)-[:DEPENDS]->(c:Class) "
                        + "WHERE NOT(c.externalId IN {classes}) AND (NOT(HAS(r.source)) OR r.source = {source}) "
                        + "DELETE r";
                JsonObject p = new JsonObject().put("userExternalId", externalId).put("source", currentSource)
                        .put("classes", classes);
                transactionHelper.add(q, p);
            }
            final JsonArray groups = new fr.wseduc.webutils.collections.JsonArray();
            final JsonObject fgm = new JsonObject();
            if (externalId != null && linkGroups != null) {
                for (String[] structGroup : linkGroups) {
                    if (structGroup != null && structGroup[0] != null && structGroup[1] != null) {
                        groups.add(structGroup[1]);
                        if (structGroup.length > 2 && isNotEmpty(structGroup[2])) {
                            JsonArray fGroups = fgm.getJsonArray(structGroup[2]);
                            if (fGroups == null) {
                                fGroups = new fr.wseduc.webutils.collections.JsonArray();
                                fgm.put(structGroup[2], fGroups);
                            }
                            fGroups.add(structGroup[1]);
                        }
                    }
                }
                String query = "MATCH (g:Group), (u:User {externalId : {userExternalId}}) "
                        + "WHERE (g:FunctionalGroup OR g:FunctionGroup OR g:HTGroup) AND g.externalId IN {groups} "
                        + "MERGE u-[:IN]->g";
                JsonObject p = new JsonObject().put("userExternalId", externalId).put("groups", groups);
                transactionHelper.add(query, p);
            }
            if (externalId != null) {
                final String qdfg = "MATCH (:User {externalId : {userExternalId}})-[r:IN|COMMUNIQUE]-(g:Group) "
                        + "WHERE (g:FunctionalGroup OR g:FunctionGroup OR g:HTGroup) AND "
                        + "NOT(g.externalId IN {groups}) AND (NOT(HAS(r.source)) OR r.source = {source}) "
                        + "DELETE r";
                final JsonObject pdfg = new JsonObject().put("userExternalId", externalId)
                        .put("source", currentSource).put("groups", groups);
                transactionHelper.add(qdfg, pdfg);
                fosm.mergeIn(fgm);
                final String deleteOldFoslg = "MATCH (u:User {externalId : {userExternalId}})-[r:TEACHES_FOS]->(f:FieldOfStudy) "
                        + "WHERE NOT(f.externalId IN {fos}) AND (NOT(HAS(r.source)) OR r.source = {source}) "
                        + "DELETE r";
                transactionHelper.add(deleteOldFoslg, pdfg.copy().put("fos",
                        new fr.wseduc.webutils.collections.JsonArray(new ArrayList<>(fosm.fieldNames()))));
                for (String fos : fgm.fieldNames()) {
                    String q2 = "MATCH (u:User {externalId : {userExternalId}}), (f:FieldOfStudy {externalId:{feId}}) "
                            + "MERGE u-[r:TEACHES_FOS]->f " + "SET r.groups = {groups} ";
                    transactionHelper.add(q2,
                            pdfg.copy().put("groups", fgm.getJsonArray(fos)).put("feId", fos));
                }
            }
        }
    }
}

From source file:org.entcore.feeder.export.eliot.BaseExportProcessing.java

License:Open Source License

private void addAttribute(JsonObject object, Object value, XMLEventWriter writer, XMLEventFactory eventFactory)
        throws XMLStreamException {
    final Object v = AAFUtil.convert(value, object.getString("converter"));
    if (v instanceof JsonObject) {
        JsonObject j = (JsonObject) v;
        for (String attr : j.fieldNames()) {
            addSingleAttribute(attr, j.getValue(attr), writer, eventFactory);
        }/*from   w w  w .  j  av a2  s .c  o m*/
    } else {
        String attr = object.getString("attribute");
        if (attr != null) {
            addSingleAttribute(attr, v, writer, eventFactory);
        }
    }
}

From source file:org.entcore.feeder.Feeder.java

License:Open Source License

@Override
public void start() {
    super.start();
    String node = (String) vertx.sharedData().getLocalMap("server").get("node");
    if (node == null) {
        node = "";
    }// w w  w.  ja  va 2 s.  c o m
    String neo4jConfig = (String) vertx.sharedData().getLocalMap("server").get("neo4jConfig");
    if (neo4jConfig != null) {
        neo4j = Neo4j.getInstance();
        neo4j.init(vertx, new JsonObject(neo4jConfig));
    }
    MongoDb.getInstance().init(vertx.eventBus(), node + "wse.mongodb.persistor");
    TransactionManager.getInstance().setNeo4j(neo4j);
    EventStoreFactory.getFactory().setVertx(vertx);
    defaultFeed = config.getString("feeder", "AAF");
    feeds.put("AAF", new AafFeeder(vertx, getFilesDirectory("AAF")));
    feeds.put("AAF1D", new Aaf1dFeeder(vertx, getFilesDirectory("AAF1D")));
    feeds.put("CSV", new CsvFeeder(vertx, config.getJsonObject("csvMappings", new JsonObject())));
    final long deleteUserDelay = config.getLong("delete-user-delay", 90 * 24 * 3600 * 1000l);
    final long preDeleteUserDelay = config.getLong("pre-delete-user-delay", 90 * 24 * 3600 * 1000l);
    final String deleteCron = config.getString("delete-cron", "0 0 2 * * ? *");
    final String preDeleteCron = config.getString("pre-delete-cron", "0 0 3 * * ? *");
    final String importCron = config.getString("import-cron");
    final JsonObject imports = config.getJsonObject("imports");
    final JsonObject preDelete = config.getJsonObject("pre-delete");
    final TimelineHelper timeline = new TimelineHelper(vertx, eb, config);
    try {
        new CronTrigger(vertx, deleteCron).schedule(new User.DeleteTask(deleteUserDelay, eb, vertx));
        if (preDelete != null) {
            if (preDelete.size() == ManualFeeder.profiles.size()
                    && ManualFeeder.profiles.keySet().containsAll(preDelete.fieldNames())) {
                for (String profile : preDelete.fieldNames()) {
                    final JsonObject profilePreDelete = preDelete.getJsonObject(profile);
                    if (profilePreDelete == null || profilePreDelete.getString("cron") == null
                            || profilePreDelete.getLong("delay") == null)
                        continue;
                    new CronTrigger(vertx, profilePreDelete.getString("cron")).schedule(
                            new User.PreDeleteTask(profilePreDelete.getLong("delay"), profile, timeline));
                }
            }
        } else {
            new CronTrigger(vertx, preDeleteCron)
                    .schedule(new User.PreDeleteTask(preDeleteUserDelay, timeline));
        }
        if (imports != null) {
            if (feeds.keySet().containsAll(imports.fieldNames())) {
                for (String f : imports.fieldNames()) {
                    final JsonObject i = imports.getJsonObject(f);
                    if (i != null && i.getString("cron") != null) {
                        new CronTrigger(vertx, i.getString("cron"))
                                .schedule(new ImporterTask(vertx, f, i.getBoolean("auto-export", false),
                                        config.getLong("auto-export-delay", 1800000l)));
                    }
                }
            } else {
                logger.error("Invalid imports configuration.");
            }
        } else if (importCron != null && !importCron.trim().isEmpty()) {
            new CronTrigger(vertx, importCron).schedule(new ImporterTask(vertx, defaultFeed,
                    config.getBoolean("auto-export", false), config.getLong("auto-export-delay", 1800000l)));
        }
    } catch (ParseException e) {
        logger.fatal(e.getMessage(), e);
        vertx.close();
        return;
    }
    Validator.initLogin(neo4j, vertx);
    manual = new ManualFeeder(neo4j);
    duplicateUsers = new DuplicateUsers(config.getBoolean("timetable", true),
            config.getBoolean("autoMergeOnlyInSameStructure", true), vertx.eventBus());
    postImport = new PostImport(vertx, duplicateUsers, config);
    vertx.eventBus().localConsumer(config.getString("address", FEEDER_ADDRESS), this);
    switch (config.getString("exporter", "")) {
    case "ELIOT":
        exporter = new EliotExporter(config.getString("export-path", "/tmp"),
                config.getString("export-destination"), config.getBoolean("concat-export", false),
                config.getBoolean("delete-export", true), vertx);
        break;
    }
    final JsonObject edt = config.getJsonObject("edt");
    if (edt != null) {
        final String pronotePrivateKey = edt.getString("pronote-private-key");
        if (isNotEmpty(pronotePrivateKey)) {
            edtUtils = new EDTUtils(vertx, pronotePrivateKey,
                    config.getString("pronote-partner-name", "NEO-Open"));
            final String edtPath = edt.getString("path");
            final String edtCron = edt.getString("cron");
            if (isNotEmpty(edtPath) && isNotEmpty(edtCron)) {
                try {
                    new CronTrigger(vertx, edtCron).schedule(new ImportsLauncher(vertx, edtPath, postImport,
                            edtUtils, config.getBoolean("udt-user-creation", true)));
                } catch (ParseException e) {
                    logger.error("Error in cron edt", e);
                }
            }
        }
    }
    final JsonObject udt = config.getJsonObject("udt");
    if (udt != null) {
        final String udtPath = udt.getString("path");
        final String udtCron = udt.getString("cron");
        if (isNotEmpty(udtPath) && isNotEmpty(udtCron)) {
            try {
                new CronTrigger(vertx, udtCron).schedule(new ImportsLauncher(vertx, udtPath, postImport,
                        edtUtils, config.getBoolean("udt-user-creation", true)));
            } catch (ParseException e) {
                logger.error("Error in cron udt", e);
            }
        }
    }
    final JsonObject csv = config.getJsonObject("csv");
    if (csv != null) {
        final String csvPath = csv.getString("path");
        final String csvCron = csv.getString("cron");
        final JsonObject csvConfig = csv.getJsonObject("config");
        if (isNotEmpty(csvPath) && isNotEmpty(csvCron) && csvConfig != null) {
            try {
                new CronTrigger(vertx, csvCron)
                        .schedule(new CsvImportsLauncher(vertx, csvPath, csvConfig, postImport));
            } catch (ParseException e) {
                logger.error("Error in cron csv", e);
            }
        }
    }
    I18n.getInstance().init(vertx);
}

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

License:Open Source License

void addCourse(JsonObject currentEntity) {
    final List<Long> weeks = new ArrayList<>();
    final List<JsonObject> items = new ArrayList<>();

    for (String attr : currentEntity.fieldNames()) {
        if (!ignoreAttributes.contains(attr) && currentEntity.getValue(attr) instanceof JsonArray) {
            for (Object o : currentEntity.getJsonArray(attr)) {
                if (!(o instanceof JsonObject))
                    continue;
                final JsonObject j = (JsonObject) o;
                j.put("itemType", attr);
                final String week = j.getString("Semaines");
                if (week != null) {
                    weeks.add(Long.valueOf(week));
                    items.add(j);/* w  w  w .  j  a  va 2 s.com*/
                }
            }
        }
    }

    if (log.isDebugEnabled() && currentEntity.containsKey("SemainesAnnulation")) {
        log.debug(currentEntity.encode());
    }
    final Long cancelWeek = (currentEntity.getString("SemainesAnnulation") != null)
            ? Long.valueOf(currentEntity.getString("SemainesAnnulation"))
            : null;
    BitSet lastWeek = new BitSet(weeks.size());
    int startCourseWeek = 0;
    for (int i = 1; i < 53; i++) {
        final BitSet currentWeek = new BitSet(weeks.size());
        boolean enabledCurrentWeek = false;
        for (int j = 0; j < weeks.size(); j++) {
            if (cancelWeek != null && ((1L << i) & cancelWeek) != 0) {
                currentWeek.set(j, false);
            } else {
                final Long week = weeks.get(j);
                currentWeek.set(j, ((1L << i) & week) != 0);
            }
            enabledCurrentWeek = enabledCurrentWeek | currentWeek.get(j);
        }
        if (!currentWeek.equals(lastWeek)) {
            if (startCourseWeek > 0) {
                persistCourse(generateCourse(startCourseWeek, i - 1, lastWeek, items, currentEntity));
            }
            startCourseWeek = enabledCurrentWeek ? i : 0;
            lastWeek = currentWeek;
        }
    }
}

From source file:org.entcore.feeder.utils.JsonUtil.java

License:Open Source License

public static String checksum(JsonObject object, HashAlgorithm hashAlgorithm) throws NoSuchAlgorithmException {
    if (object == null) {
        return null;
    }/*from w  ww  .  ja  va2  s .  c o  m*/
    final TreeSet<String> sorted = new TreeSet<>(object.fieldNames());
    final JsonObject j = new JsonObject();
    for (String attr : sorted) {
        j.put(attr, object.getValue(attr));
    }
    switch (hashAlgorithm) {
    case MD5:
        return Md5.hash(j.encode());
    default:
        return Sha256.hash(j.encode());
    }
}

From source file:org.entcore.feeder.utils.Report.java

License:Open Source License

private JsonObject cloneAndFilterResults(Optional<String> prefixAcademy) {
    JsonObject results = this.result.copy();
    if (prefixAcademy.isPresent()) {
        // filter each ignored object by externalId starting with academy name
        String prefix = prefixAcademy.get();
        JsonObject ignored = results.getJsonObject("ignored");
        Set<String> domains = ignored.fieldNames();
        for (String domain : domains) {
            JsonArray filtered = ignored.getJsonArray(domain, new JsonArray()).stream().filter(ig -> {
                if (ig instanceof JsonObject && ((JsonObject) ig).containsKey("object")) {
                    JsonObject object = ((JsonObject) ig).getJsonObject("object");
                    String externalId = object.getString("externalId");
                    return StringUtils.startsWithIgnoreCase(externalId, prefix);
                } else {
                    // keep in list because it is not a concerned object
                    return true;
                }//from w ww.  ja  v a  2  s  .c  om
            }).collect(JsonArray::new, JsonArray::add, JsonArray::addAll);//
            ignored.put(domain, filtered);
        }
        // userExternalIds FIltered
        JsonArray usersExternalIdsFiltered = results.getJsonArray("usersExternalIds", new JsonArray()).stream()
                .filter(value -> {
                    return (value instanceof String
                            && StringUtils.startsWithIgnoreCase((String) value, prefix));
                }).collect(JsonArray::new, JsonArray::add, JsonArray::addAll);//
        results.put("usersExternalIds", usersExternalIdsFiltered);
    }
    return results;
}