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

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

Introduction

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

Prototype

public JsonArray add(Object value) 

Source Link

Document

Add an Object to the JSON array.

Usage

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

License:Open Source License

protected JsonArray parseRelativeField(JsonArray relative) {
    JsonArray res = null;
    if (relative != null && relative.size() > 0) {
        res = new fr.wseduc.webutils.collections.JsonArray();
        for (Object o : relative) {
            if (!(o instanceof String))
                continue;
            String[] r = ((String) o).split("\\$");
            if (r.length == 6 && !"0".equals(r[3])) {
                res.add(r[0]);
            }/*from   w ww.j  a  va 2 s  . c  o  m*/
        }
    }
    return res;
}

From source file:org.entcore.feeder.aaf1d.StudentImportProcessing1d.java

License:Open Source License

static JsonArray parseRelativeField1d(JsonArray relative) {
    JsonArray res = null;
    if (relative != null && relative.size() > 0) {
        res = new fr.wseduc.webutils.collections.JsonArray();
        for (Object o : relative) {
            if (!(o instanceof String))
                continue;
            String[] r = ((String) o).split("\\$");
            res.add(r[0]);
        }//from ww  w.  ja v a2 s. co m
    }
    return res;
}

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

License:Open Source License

JsonArray getColumsNames(String[] strings, List<String> columns, String profile) {
    JsonArray errors = new fr.wseduc.webutils.collections.JsonArray();
    for (int j = 0; j < strings.length; j++) {
        String cm = columnsNameMapping(strings[j], profile);
        if (namesMapping.containsValue(cm)) {
            columns.add(j, cm);/*from w  w  w.j av  a  2  s. c om*/
        } else {
            errors.add(cm);
            return errors;
        }
    }
    return errors;
}

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

License:Open Source License

private void checkNotModifiableExternalId(List<String> files, final String path,
        final Handler<Message<JsonObject>> handler) {
    final List<String> columns = new ArrayList<>();
    final AtomicInteger externalIdIdx = new AtomicInteger(-1);
    final JsonArray externalIds = new fr.wseduc.webutils.collections.JsonArray();
    final AtomicInteger count = new AtomicInteger(files.size());
    for (final String file : files) {
        CSVUtil.getCharset(vertx, file, new Handler<String>() {
            @Override//from   ww  w. ja  va2  s. c o  m
            public void handle(String charset) {
                try {
                    CSVReader csvReader = getCsvReader(file, charset);
                    String[] strings;
                    int i = 0;
                    while ((strings = csvReader.readNext()) != null) {
                        if (i == 0) {
                            final String profile = file.substring(path.length() + 1).replaceFirst(".csv", "");
                            columnsMapper.getColumsNames(strings, columns, profile, handler);
                            if (columns.isEmpty()) {
                                handler.handle(new ResultMessage().error("invalid.columns"));
                                return;
                            }
                            for (int j = 0; j < columns.size(); j++) {
                                if ("externalId".equals(columns.get(j))) {
                                    externalIdIdx.set(j);
                                    break;
                                }
                            }
                        } else if (externalIdIdx.get() >= 0 && !emptyLine(strings)) {
                            externalIds.add(strings[externalIdIdx.get()]);
                        }
                        i++;
                    }
                    if (count.decrementAndGet() == 0) {
                        queryNotModifiableIds(handler, externalIds);
                    }
                } catch (Exception e) {
                    handler.handle(new ResultMessage().error("csv.exception"));
                    log.error("csv.exception", e);
                }
            }
        });

    }
}

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  w w  .  ja  v  a 2  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.CsvFeeder.java

License:Open Source License

private void relativeStudentMapping(JsonArray linkStudents, String mapping) {
    if (mapping.trim().isEmpty())
        return;/*from w ww. j a  v a2 s.co m*/
    try {
        String hash = Hash.sha1(mapping.getBytes("UTF-8"));
        String childId = studentExternalIdMapping.get(hash);
        if (childId != null) {
            linkStudents.add(childId);
        }
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }
}

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

License:Open Source License

private void checkFile(final String path, final String profile, final String charset,
        final Handler<JsonObject> handler) {
    final List<String> columns = new ArrayList<>();
    final AtomicInteger filterExternalId = new AtomicInteger(-1);
    final JsonArray externalIds = new fr.wseduc.webutils.collections.JsonArray();
    try {/*from  w  w w.ja va 2  s.  c o m*/
        CSVReader csvParser = getCsvReader(path, charset);

        String[] strings;
        int i = 0;
        while ((strings = csvParser.readNext()) != null) {
            if (i == 0) {
                JsonArray invalidColumns = columnsMapper.getColumsNames(strings, columns, profile);
                if (invalidColumns.size() > 0) {
                    parseErrors("invalid.column", invalidColumns, profile, handler);
                } else if (columns.contains("externalId")) {
                    int j = 0;
                    for (String c : columns) {
                        if ("externalId".equals(c)) {
                            filterExternalId.set(j);
                        }
                        j++;
                    }
                } else if (structureId != null && !structureId.trim().isEmpty()) {
                    findUsersEnabled = false;
                    findUsers(path, profile, columns, charset, handler);
                } else {
                    validateFile(path, profile, columns, null, charset, handler);
                }
            } else if (filterExternalId.get() >= 0 && !emptyLine(strings)) {
                if (strings[filterExternalId.get()] != null && !strings[filterExternalId.get()].isEmpty()) {
                    externalIds.add(strings[filterExternalId.get()]);
                } else if (findUsersEnabled) { // TODO add check to empty lines
                    findUsersEnabled = false;
                    final int eii = filterExternalId.get();
                    filterExternalId.set(-1);
                    findUsers(path, profile, columns, eii, charset, handler);
                }
            }
            i++;
        }
    } catch (Exception e) {
        addError(profile, "csv.exception");
        log.error("csv.exception", e);
        handler.handle(result);
        return;
    }
    if (filterExternalId.get() >= 0) {
        filterExternalIdExists(externalIds, new Handler<JsonArray>() {
            @Override
            public void handle(JsonArray externalIdsExists) {
                if (externalIdsExists != null) {
                    validateFile(path, profile, columns, externalIdsExists, charset, handler);
                } else {
                    addError(profile, "error.find.externalIds");
                    handler.handle(result);
                }
            }
        });
    }
}

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   w w  w. j  a  v  a 2s .  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.csv.CsvValidator.java

License:Open Source License

private void relativeStudentMapping(JsonArray linkStudents, String mapping) {
    if (mapping.trim().isEmpty())
        return;//w  ww  . ja  v  a  2  s .  c  om
    try {
        String hash = Hash.sha1(mapping.getBytes("UTF-8"));
        linkStudents.add(getOrElse(studentExternalIdMapping.get(hash), hash));
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }
}

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

License:Open Source License

public void findExternalIds(final String structureId, final String path, final String profile,
        final List<String> columns, final int eII, final String charset, final Handler<JsonArray> handler) {
    final boolean additionalColumn;
    final int externalIdIdx;
    if (eII >= 0) {
        additionalColumn = false;/*from   w  ww  .java  2s  .c  o  m*/
        externalIdIdx = eII;
    } else {
        additionalColumn = true;
        externalIdIdx = 0;
    }
    final JsonArray errors = new fr.wseduc.webutils.collections.JsonArray();
    String filter = "";
    if ("Student".equals(profile)) {
        filter = "AND u.birthDate = {birthDate} ";
    }
    final String query = "MATCH (s:Structure {externalId : {id}})<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User) "
            + "WHERE u.firstNameSearchField = {firstName} AND u.lastNameSearchField = {lastName} AND head(u.profiles) = {profile} "
            + filter + "RETURN DISTINCT u.externalId as externalId";
    final List<String[]> lines = new ArrayList<>();
    final TransactionHelper tx;
    try {
        tx = TransactionManager.getTransaction();
    } catch (TransactionException e) {
        addError(errors, "transaction.error");
        handler.handle(errors);
        return;
    }

    try {
        CSVReader csvReader = getCsvReader(path, charset);
        final int nbColumns = columns.size();
        String[] values;
        int rowIdx = 0;
        while ((values = csvReader.readNext()) != null) {
            if (emptyLine(values)) {
                continue;
            }
            if (values.length > nbColumns) {
                values = Arrays.asList(values).subList(0, nbColumns).toArray(new String[nbColumns]);
            } else if (values.length < nbColumns) {
                values = Arrays.copyOf(values, nbColumns);
            }
            final List<String> line = new LinkedList<>(Arrays.asList(values));
            if (additionalColumn) {
                line.add(0, "");
            }
            lines.add(line.toArray(new String[line.size()]));
            if (rowIdx == 0) {
                if (additionalColumn) {
                    lines.get(0)[externalIdIdx] = "externalId";
                }
                rowIdx++;
                continue;
            }

            final JsonObject params = new JsonObject();
            if (!additionalColumn && values[externalIdIdx] != null && !values[externalIdIdx].isEmpty()) {
                tx.add(NOP_QUERY, params.put("externalId", values[externalIdIdx]));
            } else {
                params.put("id", structureId).put("profile", profile);
                try {
                    int i = 0;
                    for (String c : columns) {
                        //   if (i >=  values.length) break;
                        switch (c) {
                        case "lastName":
                            params.put("lastName", sanitize(values[i]));
                            break;
                        case "firstName":
                            params.put("firstName", sanitize(values[i]));
                            break;
                        case "birthDate":
                            if ("Student".equals(profile)) {
                                Matcher m;

                                if (values[i] != null
                                        && (m = CsvFeeder.frenchDatePatter.matcher(values[i])).find()) {
                                    params.put("birthDate", m.group(3) + "-" + m.group(2) + "-" + m.group(1));
                                } else {
                                    params.put("birthDate", values[i]);
                                }
                            }
                            break;
                        }
                        i++;
                    }
                } catch (Exception e) {
                    errors.add(new JsonObject().put("key", "parse.line.error").put("params",
                            new fr.wseduc.webutils.collections.JsonArray().add(Integer.toString(rowIdx))));
                }

                tx.add(query, params);
            }
            rowIdx++;
        }
    } catch (Exception e) {
        addError(errors, "error.read.file", path);
        handler.handle(errors);
    }
    tx.commit(new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> event) {
            JsonArray results = event.body().getJsonArray("results");
            if ("ok".equals(event.body().getString("status")) && results != null
                    && results.size() + 1 == lines.size()) {
                for (int i = 0; i < results.size(); i++) {
                    JsonArray line = results.getJsonArray(i);
                    if (line.size() == 1) { // Si 0 ou plusieurs utilisateurs, on laisse la ligne d'origine
                        String eId = line.getJsonObject(0).getString("externalId", "");
                        lines.get(i + 1)[externalIdIdx] = eId;
                    }
                }
                vertx.fileSystem().deleteBlocking(path);

                try {
                    CSVWriter writer = getCsvWriter(path, charset);
                    writer.writeAll(lines);
                    writer.close();
                } catch (IOException e) {
                    log.error("Error writing file.", e);
                    addError(errors, "error.write.file", path);
                }
                if ("Relative".equals(profile) && columns.contains("childLastName")
                        && !columns.contains("childExternalId")) {
                    if (additionalColumn) {
                        columns.add(0, "externalId");
                    }
                    findChildExternalIds(structureId, path, charset, columns, errors, handler);
                } else {
                    handler.handle(errors);
                }
            } else {
                addError(errors, "error.find.ids");
                handler.handle(errors);
            }
        }
    });
}