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

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

Introduction

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

Prototype

public String encode() 

Source Link

Document

Encode the JSON array to a string

Usage

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

License:Open Source License

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

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

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

License:Open Source License

private void decrementWriteToFS(AtomicInteger count, JsonArray errors, Handler<JsonObject> handler) {
    if (count.decrementAndGet() <= 0) {
        JsonObject j = new JsonObject();
        if (errors.size() == 0) {
            handler.handle(j.put("status", "ok"));
        } else {/*from   w  w w .j a  v a  2s. co m*/
            handler.handle(j.put("status", "error").put("errors", errors).put("message", errors.encode()));
        }
    }
}

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

License:Open Source License

@Override
public void writeToFileSystem(String[] ids, String destinationPath, JsonObject alias,
        final Handler<JsonObject> handler) {
    final AtomicInteger count = new AtomicInteger(ids.length);
    final JsonArray errors = new fr.wseduc.webutils.collections.JsonArray();
    for (final String id : ids) {
        if (id == null || id.isEmpty()) {
            count.decrementAndGet();//from  ww w .j  a  v a 2 s .  com
            continue;
        }
        String d = destinationPath + File.separator + alias.getString(id, id);
        swiftClient.writeToFileSystem(id, d, new Handler<AsyncResult<String>>() {
            @Override
            public void handle(AsyncResult<String> event) {
                if (event.failed()) {
                    errors.add(new JsonObject().put("id", id).put("message", event.cause().getMessage()));
                }
                if (count.decrementAndGet() <= 0) {
                    JsonObject j = new JsonObject();
                    if (errors.size() == 0) {
                        handler.handle(j.put("status", "ok"));
                    } else {
                        handler.handle(
                                j.put("status", "error").put("errors", errors).put("message", errors.encode()));
                    }
                }
            }
        });
    }
}

From source file:org.entcore.common.user.LogRepositoryEvents.java

License:Open Source License

@Override
public void deleteGroups(JsonArray groups) {
    log.info(groups.encode());
}

From source file:org.entcore.common.user.LogRepositoryEvents.java

License:Open Source License

@Override
public void deleteUsers(JsonArray users) {
    log.info(users.encode());
}

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

License:Open Source License

@Override
public void handle(Long event) {
    final Sql sql = Sql.getInstance();
    final SqlStatementsBuilder builder = new SqlStatementsBuilder();
    builder.raw(DELETE_ORPHAN_MESSAGE);// ww  w .  j  a  va  2 s.  c  o m
    builder.raw(SELECT_ORPHAN_ATTACHMENT);
    sql.transaction(builder.build(), new DeliveryOptions().setSendTimeout(TIMEOUT),
            SqlResult.validResultHandler(1, new Handler<Either<String, JsonArray>>() {
                @Override
                public void handle(Either<String, JsonArray> res) {
                    if (res.isRight()) {
                        log.info("Successful delete orphan conversation messages.");
                        final JsonArray attachments = res.right().getValue();
                        if (attachments != null && attachments.size() > 0) {
                            log.info("Orphan attachments : " + attachments.encode());
                            JsonArray ids = new fr.wseduc.webutils.collections.JsonArray();
                            for (Object attObj : attachments) {
                                if (!(attObj instanceof JsonObject))
                                    continue;
                                JsonObject unusedAttachment = (JsonObject) attObj;
                                final String attachmentId = unusedAttachment.getString("orphanid");
                                ids.add(attachmentId);
                                storage.removeFile(attachmentId, new Handler<JsonObject>() {
                                    public void handle(JsonObject event) {
                                        if (!"ok".equals(event.getString("status"))) {
                                            log.error("Error while tying to delete attachment file (_id: {"
                                                    + attachmentId + "})");
                                        }
                                    }
                                });
                            }
                            final String deletOrphanAttachments = "delete from conversation.attachments where id IN "
                                    + Sql.listPrepared(ids.getList());
                            sql.prepared(deletOrphanAttachments, ids,
                                    new DeliveryOptions().setSendTimeout(TIMEOUT),
                                    new Handler<Message<JsonObject>>() {
                                        @Override
                                        public void handle(Message<JsonObject> event) {
                                            if (!"ok".equals(event.body().getString("status"))) {
                                                log.error("Error deleting orphan attachments : "
                                                        + event.body().getString("message", ""));
                                            } else {
                                                log.info("Successful delete orphan conversation attachments.");
                                            }
                                        }
                                    });
                        }
                    } else {
                        log.error("Orphan conversation error : " + res.left().getValue());
                    }
                }
            }));
}

From source file:org.entcore.directory.controllers.UserController.java

License:Open Source License

@Get("/user/structures/list")
@ResourceFilter(AdmlOfStructuresByUAI.class)
@SecuredAction(value = "", type = ActionType.RESOURCE)
public void listUserInStructuresByUAI(final HttpServerRequest request) {
    final String format = request.params().get("format");
    final List<String> structures = request.params().getAll("uai");

    JsonArray fields = new fr.wseduc.webutils.collections.JsonArray().add("externalId").add("lastName")
            .add("firstName").add("login");
    if ("true".equalsIgnoreCase(request.params().get("administrativeStructure"))) {
        fields.add("administrativeStructure");
    }//  w  ww  . j  a va 2  s.  co m
    JsonArray types = new fr.wseduc.webutils.collections.JsonArray(request.params().getAll("type"));

    boolean isExportFull = false;
    String isExportFullParameter = request.params().get("full");
    if (null != isExportFullParameter && !isExportFullParameter.isEmpty()
            && "true".equals(isExportFullParameter)) {
        isExportFull = true;
    }

    if ("XML".equalsIgnoreCase(format)) {
        userService.listByUAI(structures, types, isExportFull, fields,
                new Handler<Either<String, JsonArray>>() {
                    @Override
                    public void handle(Either<String, JsonArray> event) {
                        if (event.isRight()) {
                            JsonArray r = event.right().getValue();
                            ObjectMapper mapper = new ObjectMapper();
                            try {
                                List<Users.User> users = mapper.readValue(r.encode(),
                                        new TypeReference<List<Users.User>>() {
                                        });
                                StringWriter response = new StringWriter();
                                JAXBContext context = JAXBContext.newInstance(Users.class);
                                Marshaller marshaller = context.createMarshaller();
                                marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
                                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                                marshaller.marshal(new Users(users), response);
                                request.response().putHeader("content-type", "application/xml");
                                request.response().end(response.toString());
                            } catch (IOException | JAXBException e) {
                                log.error(e.toString(), e);
                                request.response().setStatusCode(500);
                                request.response().end(e.getMessage());
                            }
                        } else {
                            leftToResponse(request, event.left());
                        }
                    }
                });
    } else {
        userService.listByUAI(structures, types, isExportFull, fields, arrayResponseHandler(request));
    }
}

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

License:Open Source License

private void queryNotModifiableIds(final Handler<Message<JsonObject>> handler, JsonArray externalIds) {
    if (externalIds.size() > 0) {
        String query = "MATCH (u:User) where u.externalId IN {ids} AND u.source IN ['AAF', 'AAF1D'] "
                + "AND NOT(HAS(u.deleteDate)) AND NOT(HAS(u.disappearanceDate)) "
                + "RETURN COLLECT(u.externalId) as ids";
        TransactionManager.getNeo4jHelper().execute(query, new JsonObject().put("ids", externalIds),
                new Handler<Message<JsonObject>>() {
                    @Override/* w  w  w. j  a  v a2s  . c  om*/
                    public void handle(Message<JsonObject> event) {
                        if ("ok".equals(event.body().getString("status"))) {
                            JsonArray res = event.body().getJsonArray("result");
                            JsonArray ids;
                            if (res != null && res.size() > 0 && res.getJsonObject(0) != null
                                    && (ids = res.getJsonObject(0).getJsonArray("ids")) != null
                                    && ids.size() > 0) {
                                handler.handle(
                                        new ResultMessage().error("unmodifiable.externalId-" + ids.encode()));
                            } else {
                                handler.handle(new ResultMessage());
                            }
                        } else {
                            handler.handle(event);
                        }
                    }
                });
    } else {
        handler.handle(new ResultMessage());
    }
}

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

License:Open Source License

private void findUsers(final String path, final String profile, List<String> columns, int eii,
        final String charset, final Handler<JsonObject> handler) {
    mappingFinder.findExternalIds(structureId, path, profile, columns, eii, charset, new Handler<JsonArray>() {
        @Override/*from  w ww  .  j a  v  a  2  s  .  c om*/
        public void handle(JsonArray errors) {
            if (errors.size() > 0) {
                for (Object o : errors) {
                    if (!(o instanceof JsonObject))
                        continue;
                    JsonObject j = (JsonObject) o;
                    JsonArray p = j.getJsonArray("params");
                    log.info(j.encode());
                    if (p != null && p.size() > 0) {
                        addErrorByFile(profile, j.getString("key"), p.encode()
                                .substring(1, p.encode().length() - 1).replaceAll("\"", "").split(","));
                    } else if (j.getString("key") != null) {
                        addError(profile, j.getString("key"));
                    } else {
                        addError(profile, "mapping.unknown.error");
                    }
                }
                handler.handle(result);
            } else {
                //validateFile(path, profile, columns, null, handler);
                checkFile(path, profile, charset, handler);
            }
        }
    });
}

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

License:Open Source License

public static void publishDeleteGroups(EventBus eb, Logger logger, JsonArray groups) {
    logger.info("Delete groups : " + groups.encode());
    eb.publish(Feeder.USER_REPOSITORY,/*from   www  . jav a2 s .c om*/
            new JsonObject().put("action", "delete-groups").put("old-groups", groups));
}