Search in sources :

Example 1 with Either

use of fr.wseduc.webutils.Either in project statistics by OPEN-ENT-NG.

the class StatisticsController method getData.

@Post("/data")
@SecuredAction("statistics.get.data")
public void getData(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, pathPrefix + "schoolquery", new Handler<JsonObject>() {

        @Override
        public void handle(JsonObject data) {
            // parameters from the model (schoolIdArray / indicator / startDate / endDate / module)
            final JsonObject params = data;
            UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {

                @Override
                public void handle(final UserInfos user) {
                    if (user == null) {
                        log.debug("User not found in session.");
                        unauthorized(request);
                        return;
                    }
                    JsonArray arr = params.getArray("schoolIdArray");
                    List<String> schoolIds = new ArrayList<String>();
                    for (int i = 0; i < arr.size(); i++) {
                        schoolIds.add((String) arr.get(i));
                    }
                    // final List<String> schoolIds = Arrays.asList(params.getArray("schoolIdArray"));
                    if (schoolIds == null || schoolIds.size() == 0) {
                        String errorMsg = i18n.translate("statistics.bad.request.invalid.schools", getHost(request), acceptLanguage(request));
                        badRequest(request, errorMsg);
                        return;
                    }
                    // final String indicator = request.params().get(PARAM_INDICATOR);
                    final String indicator = params.getString("indicator");
                    if (indicator == null || indicator.trim().isEmpty() || !indicators.contains(indicator)) {
                        String errorMsg = i18n.translate("statistics.bad.request.invalid.indicator", getHost(request), acceptLanguage(request));
                        badRequest(request, errorMsg);
                        return;
                    }
                    String module = "";
                    if (TRACE_TYPE_SVC_ACCESS.equals(indicator)) {
                        // module = request.params().get(PARAM_MODULE);
                        module = params.getString("module");
                        if (module != null && !module.trim().isEmpty() && !accessModules.contains(module)) {
                            String errorMsg = i18n.translate("statistics.bad.request.invalid.module", getHost(request), acceptLanguage(request));
                            badRequest(request, errorMsg);
                            return;
                        }
                    // Else (when module is not specified) return data for all modules
                    }
                    // String startDate = request.params().get(PARAM_START_DATE);
                    // String endDate = request.params().get(PARAM_END_DATE);
                    String startDate = String.valueOf(params.getInteger("startDate"));
                    String endDate = String.valueOf(params.getInteger("endDate"));
                    long start, end;
                    try {
                        start = DateUtils.parseStringDate(startDate);
                        end = DateUtils.parseStringDate(endDate);
                        if (end < start || end < 0L || start < 0L) {
                            String errorMsg = i18n.translate("statistics.bad.request.invalid.dates", getHost(request), acceptLanguage(request));
                            badRequest(request, errorMsg);
                            return;
                        }
                    } catch (Exception e) {
                        log.error("Error when casting startDate or endDate to long", e);
                        String errorMsg = i18n.translate("statistics.bad.request.invalid.date.format", getHost(request), acceptLanguage(request));
                        badRequest(request, errorMsg);
                        return;
                    }
                    final JsonObject params = new JsonObject();
                    params.putString(PARAM_INDICATOR, indicator).putNumber(PARAM_START_DATE, start).putNumber(PARAM_END_DATE, end).putString(PARAM_MODULE, module);
                    if (schoolIds.size() == 1) {
                        // if the structure choosed is not a school, we need to explore all the attached schools from the graph base
                        structureService.getAttachedStructureslist(schoolIds.get(0), new Handler<Either<String, JsonArray>>() {

                            @Override
                            public void handle(Either<String, JsonArray> either) {
                                if (either.isLeft()) {
                                    log.error(either.left().getValue());
                                    renderError(request);
                                } else {
                                    final List<String> attachedSchoolsList;
                                    final JsonArray result = either.right().getValue();
                                    if (result != null) {
                                        attachedSchoolsList = new ArrayList<String>(result.size());
                                        for (int i = 0; i < result.size(); i++) {
                                            Object obj = result.get(i);
                                            if (obj instanceof JsonObject) {
                                                final JsonObject jo = (JsonObject) obj;
                                                attachedSchoolsList.add(jo.getString("s2.id", ""));
                                            }
                                        }
                                    } else {
                                        attachedSchoolsList = new ArrayList<String>(0);
                                    }
                                    formatting(attachedSchoolsList, params, indicator, request);
                                }
                            }
                        });
                    } else {
                        formatting(schoolIds, params, indicator, request);
                    }
                }
            });
        }
    });
}
Also used : JsonObject(org.vertx.java.core.json.JsonObject) Handler(org.vertx.java.core.Handler) UserInfos(org.entcore.common.user.UserInfos) JsonArray(org.vertx.java.core.json.JsonArray) Either(fr.wseduc.webutils.Either) JsonObject(org.vertx.java.core.json.JsonObject) SecuredAction(fr.wseduc.security.SecuredAction) Post(fr.wseduc.rs.Post)

Example 2 with Either

use of fr.wseduc.webutils.Either in project statistics by OPEN-ENT-NG.

the class StatisticsController method getStructures.

@Post("/structures")
@ApiDoc("Get structures' names, UAIs and cities")
@SecuredAction("statistics.get.structures")
public void getStructures(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, pathPrefix + "schoolquery", new Handler<JsonObject>() {

        @Override
        public void handle(JsonObject data) {
            // parameters from the model (schoolIdArray / indicator / startDate / endDate / module)
            final JsonObject params = data;
            UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {

                @Override
                public void handle(final UserInfos user) {
                    if (user != null) {
                        JsonArray arr = params.getArray("schoolIdArray");
                        List<String> schoolIds = new ArrayList<String>();
                        for (int i = 0; i < arr.size(); i++) {
                            JsonObject obj = arr.get(i);
                            schoolIds.add((String) obj.getString("id"));
                        }
                        if (schoolIds == null || schoolIds.size() == 0) {
                            String errorMsg = i18n.translate("statistics.bad.request.invalid.schools", getHost(request), acceptLanguage(request));
                            badRequest(request, errorMsg);
                            return;
                        }
                        JsonArray structureIds = new JsonArray();
                        for (String school : schoolIds) {
                            structureIds.addString(school);
                        }
                        structureService.list(structureIds, new Handler<Either<String, JsonArray>>() {

                            @Override
                            public void handle(Either<String, JsonArray> event) {
                                if (event.isLeft()) {
                                    log.error(event.left().getValue());
                                    renderError(request);
                                } else {
                                    renderJson(request, event.right().getValue());
                                }
                            }
                        });
                    }
                // end if
                }
            });
        }
    });
}
Also used : JsonObject(org.vertx.java.core.json.JsonObject) Handler(org.vertx.java.core.Handler) UserInfos(org.entcore.common.user.UserInfos) JsonArray(org.vertx.java.core.json.JsonArray) Either(fr.wseduc.webutils.Either) SecuredAction(fr.wseduc.security.SecuredAction) Post(fr.wseduc.rs.Post) ApiDoc(fr.wseduc.rs.ApiDoc)

Example 3 with Either

use of fr.wseduc.webutils.Either in project statistics by OPEN-ENT-NG.

the class IndicatorCustomImpl method aggregate.

@Override
public void aggregate(final Handler<JsonObject> callBack) {
    final Date start = new Date();
    this.getAccounts(new Handler<Either<String, JsonArray>>() {

        @Override
        public void handle(Either<String, JsonArray> event) {
            if (event.isLeft()) {
                log.error(event.left().getValue());
                callBack.handle(new JsonObject());
                return;
            }
            try {
                JsonArray results = event.right().getValue();
                // If no documents found, write nothing
                if (results.size() == 0) {
                    callBack.handle(new JsonObject());
                    return;
                }
                // Synchronization handler
                final AtomicInteger countDown = new AtomicInteger(results.size());
                Handler<Message<JsonObject>> synchroHandler = new Handler<Message<JsonObject>>() {

                    @Override
                    public void handle(Message<JsonObject> message) {
                        if (!"ok".equals(message.body().getString("status"))) {
                            log.error("Error in method aggregate of IndicatorCustomImpl : " + message.body().toString());
                        }
                        if (countDown.decrementAndGet() == 0) {
                            final Date end = new Date();
                            log.info("[Aggregation]{" + IndicatorCustomImpl.this.getKey() + "} Took [" + (end.getTime() - start.getTime()) + "] ms");
                            callBack.handle(new JsonObject().putString("status", "ok"));
                        }
                    }
                };
                for (int i = 0; i < results.size(); i++) {
                    JsonObject jo = results.get(i);
                    String structure = jo.getString("structure");
                    String profile = jo.getString("profile");
                    Number accounts = jo.getNumber("accounts");
                    Number activatedAccounts = jo.getNumber("activatedAccounts");
                    String date = MongoDb.formatDate(IndicatorCustomImpl.this.getWriteDate());
                    MongoDBBuilder criteriaQuery = new MongoDBBuilder();
                    criteriaQuery.put(STATS_FIELD_DATE).is(date).put(STATS_FIELD_GROUPBY).is(TRACE_FIELD_STRUCTURES + "/" + TRACE_FIELD_PROFILE).put(PROFILE_ID).is(profile).put(STRUCTURES_ID).is(structure);
                    MongoUpdateBuilder update = new MongoUpdateBuilder().set(STATS_FIELD_ACCOUNTS, accounts).set(STATS_FIELD_ACTIVATED_ACCOUNTS, activatedAccounts);
                    // Upsert data in MongoDB
                    mongo.update(COLLECTIONS.stats.name(), MongoQueryBuilder.build(criteriaQuery), update.build(), true, true, synchroHandler);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                callBack.handle(new JsonObject());
            }
        }
    });
}
Also used : Message(org.vertx.java.core.eventbus.Message) MongoDBBuilder(org.entcore.common.aggregation.filters.dbbuilders.MongoDBBuilder) JsonObject(org.vertx.java.core.json.JsonObject) Handler(org.vertx.java.core.Handler) Neo4jResult.validResultHandler(org.entcore.common.neo4j.Neo4jResult.validResultHandler) Date(java.util.Date) JsonArray(org.vertx.java.core.json.JsonArray) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Either(fr.wseduc.webutils.Either) MongoUpdateBuilder(fr.wseduc.mongodb.MongoUpdateBuilder)

Example 4 with Either

use of fr.wseduc.webutils.Either in project statistics by OPEN-ENT-NG.

the class StatisticsController method generation.

@Get("/generation")
@SecuredAction(value = "", type = ActionType.RESOURCE)
@ResourceFilter(SuperAdminFilter.class)
public /**
 * Generation of statistics to mongoDB database. Calls the same treatment as the one called by cron
 * Before the generation, deletes the records who will be regenerated.
 */
void generation(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, pathPrefix + "schoolquery", new Handler<JsonObject>() {

        @Override
        public void handle(JsonObject data) {
            // parameters from the model (schoolIdArray / indicator / startDate / endDate / module)
            final JsonObject params = data;
            UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {

                @Override
                public void handle(final UserInfos user) {
                    final Date startDate = new Date(params.getLong("startDate") * 1000L);
                    final Date endDate = new Date(params.getLong("endDate") * 1000L);
                    // final Date startDate = new Date(Long.parseLong(request.params().get(PARAM_START_DATE)) * 1000L);
                    // final Date endDate = new Date(Long.parseLong(request.params().get(PARAM_END_DATE)) * 1000L);
                    deleteRegeneratedStatistics(startDate, endDate, new Handler<Either<String, JsonArray>>() {

                        @Override
                        public void handle(Either<String, JsonArray> event) {
                            if (event.isLeft()) {
                                log.error(event.left().getValue());
                                renderError(request);
                            } else {
                                if (user != null) {
                                    Statistics st = new Statistics();
                                    st.aggregateEvents(StatisticsController.this.vertx, startDate, endDate);
                                    JsonArray jarray = new JsonArray();
                                    jarray.add(String.valueOf(params.getInteger("startDate")));
                                    renderJson(request, jarray);
                                }
                            }
                        }
                    });
                }
            });
        }
    });
}
Also used : JsonArray(org.vertx.java.core.json.JsonArray) JsonObject(org.vertx.java.core.json.JsonObject) Handler(org.vertx.java.core.Handler) Either(fr.wseduc.webutils.Either) UserInfos(org.entcore.common.user.UserInfos) Statistics(net.atos.entng.statistics.Statistics) ResourceFilter(org.entcore.common.http.filter.ResourceFilter) SecuredAction(fr.wseduc.security.SecuredAction) Get(fr.wseduc.rs.Get)

Aggregations

Either (fr.wseduc.webutils.Either)4 Handler (org.vertx.java.core.Handler)4 JsonArray (org.vertx.java.core.json.JsonArray)4 JsonObject (org.vertx.java.core.json.JsonObject)4 SecuredAction (fr.wseduc.security.SecuredAction)3 UserInfos (org.entcore.common.user.UserInfos)3 Post (fr.wseduc.rs.Post)2 MongoUpdateBuilder (fr.wseduc.mongodb.MongoUpdateBuilder)1 ApiDoc (fr.wseduc.rs.ApiDoc)1 Get (fr.wseduc.rs.Get)1 Date (java.util.Date)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Statistics (net.atos.entng.statistics.Statistics)1 MongoDBBuilder (org.entcore.common.aggregation.filters.dbbuilders.MongoDBBuilder)1 ResourceFilter (org.entcore.common.http.filter.ResourceFilter)1 Neo4jResult.validResultHandler (org.entcore.common.neo4j.Neo4jResult.validResultHandler)1 Message (org.vertx.java.core.eventbus.Message)1