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

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

Introduction

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

Prototype

public Set<String> fieldNames() 

Source Link

Document

Return the set of field names in the JSON objects

Usage

From source file:org.entcore.feeder.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);
    }/*  w  w  w.  j ava 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);
}

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

License:Open Source License

public String modifiableValidate(JsonObject object) {
    if (object == null) {
        return "Null object.";
    }//from   ww  w  .j  ava  2s .  c o  m
    final Set<String> attributes = new HashSet<>(object.fieldNames());
    JsonObject generatedAttributes = null;
    for (String attr : attributes) {
        JsonObject v = validate.getJsonObject(attr);
        if (v == null || !modifiable.contains(attr)) {
            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":
                if (!required.contains(attr)
                        && (value == null || (value instanceof String && ((String) value).isEmpty()))) {
                    err = null;
                } else {
                    err = validString(attr, value, validator);
                }
                break;
            case "array-string":
                if (!required.contains(attr)
                        && (value == null || (value instanceof JsonArray && ((JsonArray) value).size() == 0))) {
                    err = null;
                } else {
                    err = validStringArray(attr, value, validator);
                }
                break;
            case "boolean":
                err = validBoolean(attr, value);
                break;
            case "login-alias":
                err = validLoginAlias(attr, value, validator);
                break;
            default:
                err = "Missing type validator: " + type;
            }
            if (err != null) {
                return err;
            }
            if (value != null && generate.containsKey(attr)) {
                JsonObject g = generate.getJsonObject(attr);
                if (g != null && "displayName".equals(g.getString("generator"))) {
                    if (generatedAttributes == null) {
                        generatedAttributes = new JsonObject();
                    }
                    generatedAttributes.put(attr + SEARCH_FIELD, removeAccents(value.toString()).toLowerCase());
                }
            }
        }
    }
    if (generatedAttributes != null) {
        object.mergeIn(generatedAttributes);
    }
    JsonObject g = generate.getJsonObject("modified");
    if (g != null) {
        nowDate("modified", object);
    }
    return (object.size() > 0) ? null : "Empty object.";
}

From source file:org.entcore.infra.controllers.MonitoringController.java

License:Open Source License

private Handler<Message<JsonObject>> getResponseHandler(final String module, final long timerId,
        final JsonObject result, final AtomicInteger count, final HttpServerRequest request,
        final AtomicBoolean closed) {
    return new Handler<Message<JsonObject>>() {
        @Override//  w  w  w. jav  a  2s  .co  m
        public void handle(Message<JsonObject> event) {
            result.put(module, event.body().getString("status"));
            if (count.decrementAndGet() <= 0 && !closed.get()) {
                vertx.cancelTimer(timerId);
                boolean error = false;
                for (String element : result.fieldNames()) {
                    if (!"ok".equals(result.getString(element))) {
                        error = true;
                        break;
                    }
                }
                if (error) {
                    renderError(request, result);
                } else {
                    renderJson(request, result);
                }
            }
        }
    };
}

From source file:org.entcore.infra.Starter.java

License:Open Source License

@Override
public void start() {
    try {//from   w  ww.ja v a  2s  . com
        super.start();
        final LocalMap<Object, Object> serverMap = vertx.sharedData().getLocalMap("server");

        serverMap.put("signKey", config.getString("key", "zbxgKWuzfxaYzbXcHnK3WnWK" + Math.random()));
        CookieHelper.getInstance().init((String) vertx.sharedData().getLocalMap("server").get("signKey"), log);

        JsonObject swift = config.getJsonObject("swift");
        if (swift != null) {
            serverMap.put("swift", swift.encode());
        }
        JsonObject emailConfig = config.getJsonObject("emailConfig");
        if (emailConfig != null) {
            serverMap.put("emailConfig", emailConfig.encode());
        }
        JsonObject filesystem = config.getJsonObject("file-system");
        if (filesystem != null) {
            serverMap.put("file-system", filesystem.encode());
        }
        JsonObject neo4jConfig = config.getJsonObject("neo4jConfig");
        if (neo4jConfig != null) {
            serverMap.put("neo4jConfig", neo4jConfig.encode());
        }
        final String csp = config.getString("content-security-policy");
        if (isNotEmpty(csp)) {
            serverMap.put("contentSecurityPolicy", csp);
        }
        serverMap.put("gridfsAddress", config.getString("gridfs-address", "wse.gridfs.persistor"));
        //initModulesHelpers(node);

        /* sharedConf sub-object */
        JsonObject sharedConf = config.getJsonObject("sharedConf", new JsonObject());
        for (String field : sharedConf.fieldNames()) {
            serverMap.put(field, sharedConf.getValue(field));
        }

        vertx.sharedData().getLocalMap("skins")
                .putAll(config.getJsonObject("skins", new JsonObject()).getMap());

        final MessageConsumer<JsonObject> messageConsumer = vertx.eventBus()
                .localConsumer("app-registry.loaded");
        messageConsumer.handler(message -> {
            //            JsonSchemaValidator validator = JsonSchemaValidator.getInstance();
            //            validator.setEventBus(getEventBus(vertx));
            //            validator.setAddress(node + "json.schema.validator");
            //            validator.loadJsonSchema(getPathPrefix(config), vertx);
            registerGlobalWidgets(
                    config.getString("widgets-path", config.getString("assets-path", ".") + "/assets/widgets"));
            loadInvalidEmails();
            messageConsumer.unregister();
        });
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
    JsonObject eventConfig = config.getJsonObject("eventConfig", new JsonObject());
    EventStoreService eventStoreService = new MongoDbEventStore();
    EventStoreController eventStoreController = new EventStoreController(eventConfig);
    eventStoreController.setEventStoreService(eventStoreService);
    addController(eventStoreController);
    addController(new MonitoringController());
    addController(new EmbedController());
    if (config.getBoolean("antivirus", false)) {
        ClamAvService antivirusService = new ClamAvService();
        antivirusService.setVertx(vertx);
        antivirusService.setTimeline(new TimelineHelper(vertx, getEventBus(vertx), config));
        antivirusService.setRender(new Renders(vertx, config));
        antivirusService.init();
        AntiVirusController antiVirusController = new AntiVirusController();
        antiVirusController.setAntivirusService(antivirusService);
        addController(antiVirusController);
        vertx.deployVerticle(ExecCommandWorker.class.getName(), new DeploymentOptions().setWorker(true));
    }
}

From source file:org.entcore.portal.controllers.PortalController.java

License:Open Source License

@Override
public void init(final Vertx vertx, JsonObject config, RouteMatcher rm,
        Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) {
    super.init(vertx, config, rm, securedActions);
    this.staticRessources = vertx.sharedData().getLocalMap("staticRessources");
    dev = "dev".equals(config.getString("mode"));
    assetsPath = config.getString("assets-path", ".");
    JsonObject skins = new JsonObject(vertx.sharedData().<String, Object>getLocalMap("skins"));
    defaultSkin = config.getString("skin", "raw");
    themes = new HashMap<>();
    themesDetails = new HashMap<>();
    this.hostSkin = new HashMap<>();
    for (final String domain : skins.fieldNames()) {
        final String skin = skins.getString(domain);
        this.hostSkin.put(domain, skin);
        ThemeUtils.availableThemes(vertx, assetsPath + "/assets/themes/" + skin + "/skins", false,
                new Handler<List<String>>() {
                    @Override//from  w w w . java2 s .  c  om
                    public void handle(List<String> event) {
                        themes.put(skin, event);
                        JsonArray a = new fr.wseduc.webutils.collections.JsonArray();
                        for (final String s : event) {
                            String path = assetsPath + "/assets/themes/" + skin + "/skins/" + s + "/";
                            final JsonObject j = new JsonObject().put("_id", s).put("path",
                                    path.substring(assetsPath.length()));
                            if ("default".equals(s)) {
                                vertx.fileSystem().readFile(path + "/details.json",
                                        new Handler<AsyncResult<Buffer>>() {
                                            @Override
                                            public void handle(AsyncResult<Buffer> event) {
                                                if (event.succeeded()) {
                                                    JsonObject d = new JsonObject(event.result().toString());
                                                    j.put("displayName", d.getString("displayName"));
                                                } else {
                                                    j.put("displayName", s);
                                                }
                                            }
                                        });
                            } else {
                                j.put("displayName", s);
                            }
                            a.add(j);
                        }
                        themesDetails.put(skin, a);
                    }
                });
    }
    eventStore = EventStoreFactory.getFactory().getEventStore(Portal.class.getSimpleName());
    adminConsoleEventStore = EventStoreFactory.getFactory().getEventStore(ADMIN_CONSOLE_MODULE);
    vertx.sharedData().getLocalMap("server").put("assetPath", assetsPath);
}

From source file:org.entcore.timeline.events.DefaultTimelineEventStore.java

License:Open Source License

private JsonObject validAndGet(JsonObject json) {
    if (json != null) {
        JsonObject e = json.copy();/*  w ww . j  ava 2s  .c  om*/
        for (String attr : json.fieldNames()) {
            if (!FIELDS.contains(attr) || e.getValue(attr) == null) {
                e.remove(attr);
            }
        }
        if (e.getMap().keySet().containsAll(REQUIRED_FIELDS)) {
            return e;
        }
    }
    return null;
}

From source file:org.entcore.timeline.services.impl.FlashMsgServiceSqlImpl.java

License:Open Source License

@Override
public void update(String id, JsonObject data, Handler<Either<String, JsonObject>> handler) {
    StringBuilder sb = new StringBuilder();
    JsonArray values = new fr.wseduc.webutils.collections.JsonArray();
    for (String attr : data.fieldNames()) {
        if ("startDate".equals(attr) || "endDate".equals(attr)) {
            sb.append("\"" + attr + "\"").append(" = ?::timestamptz, ");
        } else if ("contents".equals(attr) || "profiles".equals(attr)) {
            sb.append("\"" + attr + "\"").append(" = ?::jsonb, ");
        } else {/*from   w ww. j a v  a2 s  .com*/
            sb.append("\"" + attr + "\"").append(" = ?, ");
        }
        values.add(data.getValue(attr));
    }
    String query = "UPDATE " + resourceTable + " SET " + sb.toString() + "modified = NOW() " + "WHERE id = ? ";
    sql.prepared(query, values.add(parseId(id)), validRowsResultHandler(handler));
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

@Get("/workspace")
@SecuredAction("workspace.view")
public void view(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override//from ww w . ja  v a  2  s  .c om
        public void handle(final UserInfos user) {
            if (user != null) {
                if (user.getAttribute("storage") != null && user.getAttribute("quota") != null) {
                    renderView(request);
                    eventStore.createAndStoreEvent(WokspaceEvent.ACCESS.name(), request);
                    return;
                }
                quotaService.quotaAndUsage(user.getUserId(), new Handler<Either<String, JsonObject>>() {
                    @Override
                    public void handle(Either<String, JsonObject> r) {
                        if (r.isRight()) {
                            JsonObject j = r.right().getValue();
                            for (String attr : j.fieldNames()) {
                                UserUtils.addSessionAttribute(eb, user.getUserId(), attr, j.getLong(attr),
                                        null);
                            }
                        }
                        renderView(request);
                        eventStore.createAndStoreEvent(WokspaceEvent.ACCESS.name(), request);
                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void emptySize(final UserInfos userInfos, final Handler<Long> emptySizeHandler) {
    try {/*from   w w  w .java  2  s.  com*/
        long quota = Long.valueOf(userInfos.getAttribute("quota").toString());
        long storage = Long.valueOf(userInfos.getAttribute("storage").toString());
        emptySizeHandler.handle(quota - storage);
    } catch (Exception e) {
        quotaService.quotaAndUsage(userInfos.getUserId(), new Handler<Either<String, JsonObject>>() {
            @Override
            public void handle(Either<String, JsonObject> r) {
                if (r.isRight()) {
                    JsonObject j = r.right().getValue();
                    if (j != null) {
                        long quota = j.getLong("quota", 0l);
                        long storage = j.getLong("storage", 0l);
                        for (String attr : j.fieldNames()) {
                            UserUtils.addSessionAttribute(eb, userInfos.getUserId(), attr, j.getLong(attr),
                                    null);
                        }
                        emptySizeHandler.handle(quota - storage);
                    }
                }
            }
        });
    }
}

From source file:org.entcore.workspace.service.WorkspaceService.java

License:Open Source License

private void emptySize(final String userId, final Handler<Long> emptySizeHandler) {
    quotaService.quotaAndUsage(userId, new Handler<Either<String, JsonObject>>() {
        @Override/*from w ww.  ja  v  a 2 s  .co  m*/
        public void handle(Either<String, JsonObject> r) {
            if (r.isRight()) {
                JsonObject j = r.right().getValue();
                if (j != null) {
                    long quota = j.getLong("quota", 0l);
                    long storage = j.getLong("storage", 0l);
                    for (String attr : j.fieldNames()) {
                        UserUtils.addSessionAttribute(eb, userId, attr, j.getLong(attr), null);
                    }
                    emptySizeHandler.handle(quota - storage);
                }
            }
        }
    });
}