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

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

Introduction

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

Prototype

public Object getValue(String key) 

Source Link

Document

Get the value with the specified key, as an Object with types respecting the limitations of JSON.

Usage

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

License:Open Source License

public SqlStatementsBuilder insert(String table, JsonObject params, String returning) {
    if (params == null) {
        return this;
    }/*w  w w . ja va  2s. c o  m*/
    JsonArray fields = new fr.wseduc.webutils.collections.JsonArray();
    JsonArray values = new fr.wseduc.webutils.collections.JsonArray();
    for (String attr : params.fieldNames()) {
        fields.add(attr);
        values.add(params.getValue(attr));
    }
    insert(table, fields, new fr.wseduc.webutils.collections.JsonArray().add(values), returning);
    return this;
}

From source file:org.entcore.common.storage.impl.PostgresqlApplicationStorage.java

License:Open Source License

private String generateColumns(JsonObject j, JsonArray params) {
    StringBuilder sb = new StringBuilder();
    for (String attr : j.fieldNames()) {
        sb.append(attr).append("= ?, ");
        params.add(j.getValue(attr));
    }/* w w w  .j  av  a2 s  .  co m*/
    return sb.toString().substring(0, sb.length() - 2);
}

From source file:org.entcore.conversation.service.impl.SqlConversationService.java

License:Open Source License

private void update(String messageId, JsonObject message, UserInfos user,
        Handler<Either<String, JsonObject>> result) {
    message.put("date", System.currentTimeMillis());
    JsonObject m = Utils.validAndGet(message, UPDATE_DRAFT_FIELDS, UPDATE_DRAFT_REQUIRED_FIELDS);
    if (validationError(user, m, result, messageId))
        return;// w ww .  jav  a 2  s . co m

    StringBuilder sb = new StringBuilder();
    JsonArray values = new fr.wseduc.webutils.collections.JsonArray();

    for (String attr : message.fieldNames()) {
        if ("to".equals(attr) || "cc".equals(attr) || "displayNames".equals(attr)) {
            sb.append("\"" + attr + "\"").append(" = CAST(? AS JSONB),");
        } else {
            sb.append("\"" + attr + "\"").append(" = ?,");
        }
        values.add(message.getValue(attr));
    }
    if (sb.length() > 0)
        sb.deleteCharAt(sb.length() - 1);

    String query = "UPDATE " + messageTable + " SET " + sb.toString() + " " + "WHERE id = ? AND state = ?";
    values.add(messageId).add("DRAFT");

    sql.prepared(query, values, SqlResult.validUniqueResultHandler(result));
}

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. ja  v a 2  s .c om

    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);/*  www. java 2  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.export.eliot.BaseExportProcessing.java

License:Open Source License

private void writeElement(XMLEventWriter writer, XMLEventFactory eventFactory, JsonObject element)
        throws XMLStreamException {
    if (element.getJsonArray("joinKey") == null && element.getString("externalId") != null) {
        element.put("joinKey",
                new fr.wseduc.webutils.collections.JsonArray().add(element.getString("externalId")));
    }// w w w . ja va2 s. c  om
    writer.add(eventFactory.createStartElement("", "", "addRequest"));
    writer.add(eventFactory.createDTD("\n"));
    writer.add(eventFactory.createStartElement("", "", "operationalAttributes"));
    writer.add(eventFactory.createStartElement("", "", "attr"));
    process(writer, eventFactory);
    writer.add(eventFactory.createEndElement("", "", "attr"));
    writer.add(eventFactory.createEndElement("", "", "operationalAttributes"));
    writer.add(eventFactory.createDTD("\n"));
    writer.add(eventFactory.createStartElement("", "", "identifier"));
    writer.add(eventFactory.createStartElement("", "", "id"));
    writer.add(eventFactory.createCharacters(element.getString("externalId")));
    writer.add(eventFactory.createEndElement("", "", "id"));
    writer.add(eventFactory.createEndElement("", "", "identifier"));
    writer.add(eventFactory.createDTD("\n"));
    writer.add(eventFactory.createStartElement("", "", "attributes"));
    writer.add(eventFactory.createDTD("\n"));
    for (String attr : exportMapping.fieldNames()) {
        Object mapping = exportMapping.getValue(attr);
        Object value = element.getValue(attr);
        if (mapping instanceof JsonObject) {
            addAttribute((JsonObject) mapping, value, writer, eventFactory);
        } else {
            for (Object o : ((JsonArray) mapping)) {
                if (!(o instanceof JsonObject))
                    continue;
                addAttribute((JsonObject) o, value, writer, eventFactory);
            }
        }
    }
    writer.add(eventFactory.createEndElement("", "", "attributes"));
    writer.add(eventFactory.createDTD("\n"));
    writer.add(eventFactory.createEndElement("", "", "addRequest"));
    writer.add(eventFactory.createDTD("\n\n"));
}

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  a  va 2  s. c  o m
    } else {
        String attr = object.getString("attribute");
        if (attr != null) {
            addSingleAttribute(attr, v, writer, eventFactory);
        }
    }
}

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);/*from w ww . j  a v  a  2s  .  co m*/
                }
            }
        }
    }

    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;
    }/*ww  w.j  a v a  2  s.  c  om*/
    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.Validator.java

License:Open Source License

public String validate(JsonObject object, String acceptLanguage) {
    if (object == null) {
        return i18n.translate("null.object", I18n.DEFAULT_DOMAIN, acceptLanguage);
    }//  ww  w  .  j  a v  a  2s  . c om
    final StringBuilder calcChecksum = new StringBuilder();
    final Set<String> attributes = new HashSet<>(object.fieldNames());
    for (String attr : attributes) {
        JsonObject v = validate.getJsonObject(attr);
        if (v == null) {
            object.remove(attr);
        } else {
            Object value = object.getValue(attr);
            String validator = v.getString("validator");
            String type = v.getString("type", "");
            String err;
            switch (type) {
            case "string":
                err = validString(attr, value, validator, acceptLanguage);
                break;
            case "array-string":
                err = validStringArray(attr, value, validator, acceptLanguage);
                break;
            case "boolean":
                err = validBoolean(attr, value, acceptLanguage);
                break;
            case "login-alias":
                err = validLoginAlias(attr, value, validator, acceptLanguage);
                break;
            default:
                err = i18n.translate("missing.type.validator", I18n.DEFAULT_DOMAIN, acceptLanguage, type);
            }
            if (err != null) {
                if (required.contains(attr)) {
                    return err;
                } else {
                    log.info(err);
                    object.remove(attr);
                    continue;
                }
            }

            if (value instanceof JsonArray) {
                calcChecksum.append(((JsonArray) value).encode());
            } else if (value instanceof JsonObject) {
                calcChecksum.append(((JsonObject) value).encode());
            } else {
                calcChecksum.append(value.toString());
            }
        }
    }
    try {
        checksum(object, calcChecksum.toString());
    } catch (NoSuchAlgorithmException e) {
        return e.getMessage();
    }
    generate(object);
    return required(object, acceptLanguage);
}