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

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

Introduction

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

Prototype

public JsonArray add(Object value) 

Source Link

Document

Add an Object to the JSON array.

Usage

From source file:org.eclipse.hono.deviceregistry.FileBasedRegistrationService.java

License:Open Source License

private void saveToFile(final Future<Void> writeResult) {

    if (!dirty) {
        log.trace("registry does not need to be persisted");
        return;// w  w w  .j av  a2 s.  c  o  m
    }

    final FileSystem fs = vertx.fileSystem();
    if (!fs.existsBlocking(getConfig().getFilename())) {
        fs.createFileBlocking(getConfig().getFilename());
    }
    final AtomicInteger idCount = new AtomicInteger();
    JsonArray tenants = new JsonArray();
    for (Entry<String, Map<String, JsonObject>> entry : identities.entrySet()) {
        JsonArray devices = new JsonArray();
        for (Entry<String, JsonObject> deviceEntry : entry.getValue().entrySet()) {
            devices.add(new JsonObject().put(FIELD_DEVICE_ID, deviceEntry.getKey()).put(FIELD_DATA,
                    deviceEntry.getValue()));
            idCount.incrementAndGet();
        }
        tenants.add(new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_DEVICES, devices));
    }
    fs.writeFile(getConfig().getFilename(), Buffer.factory.buffer(tenants.encodePrettily()), writeAttempt -> {
        if (writeAttempt.succeeded()) {
            dirty = false;
            log.trace("successfully wrote {} device identities to file {}", idCount.get(),
                    getConfig().getFilename());
            writeResult.complete();
        } else {
            log.warn("could not write device identities to file {}", getConfig().getFilename(),
                    writeAttempt.cause());
            writeResult.fail(writeAttempt.cause());
        }
    });
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

Future<Void> saveToFile() {

    if (!getConfig().isSaveToFile()) {
        return Future.succeededFuture();
    } else if (dirty) {
        return checkFileExists(true).compose(s -> {

            final JsonArray tenantsJson = new JsonArray();
            tenants.values().stream().forEach(tenant -> {
                tenantsJson.add(JsonObject.mapFrom(tenant));
            });//from  w ww  .  j  av  a  2s  .  c  o m

            final Future<Void> writeHandler = Future.future();
            vertx.fileSystem().writeFile(getConfig().getFilename(),
                    Buffer.factory.buffer(tenantsJson.encodePrettily()), writeHandler.completer());
            return writeHandler.map(ok -> {
                dirty = false;
                log.trace("successfully wrote {} tenants to file {}", tenantsJson.size(),
                        getConfig().getFilename());
                return (Void) null;
            }).otherwise(t -> {
                log.warn("could not write tenants to file {}", getConfig().getFilename(), t);
                return (Void) null;
            });
        });
    } else {
        log.trace("tenants registry does not need to be persisted");
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.service.credentials.impl.FileBasedCredentialsService.java

License:Open Source License

protected void loadCredentialsData() {
    if (filename != null) {
        final FileSystem fs = vertx.fileSystem();
        log.debug("trying to load credentials information from file {}", filename);
        if (fs.existsBlocking(filename)) {
            final AtomicInteger credentialsCount = new AtomicInteger();
            fs.readFile(filename, readAttempt -> {
                if (readAttempt.succeeded()) {
                    JsonArray allObjects = new JsonArray(new String(readAttempt.result().getBytes()));
                    for (Object obj : allObjects) {
                        JsonObject tenant = (JsonObject) obj;
                        String tenantId = tenant.getString(FIELD_TENANT);
                        Map<String, JsonArray> credentialsMap = new HashMap<>();
                        for (Object credentialsObj : tenant.getJsonArray(ARRAY_CREDENTIALS)) {
                            JsonObject credentials = (JsonObject) credentialsObj;
                            JsonArray authIdCredentials;
                            if (credentialsMap.containsKey(credentials.getString(FIELD_AUTH_ID))) {
                                authIdCredentials = credentialsMap.get(credentials.getString(FIELD_AUTH_ID));
                            } else {
                                authIdCredentials = new JsonArray();
                            }/*from  ww  w  .j  a v a2  s  . co m*/
                            authIdCredentials.add(credentials);
                            credentialsMap.put(credentials.getString(FIELD_AUTH_ID), authIdCredentials);
                            credentialsCount.incrementAndGet();
                        }
                        credentials.put(tenantId, credentialsMap);
                    }
                    log.info("successfully loaded {} credentials from file [{}]", credentialsCount.get(),
                            filename);
                } else {
                    log.warn("could not load credentials from file [{}]", filename, readAttempt.cause());
                }
            });
        } else {
            log.debug("credentials file {} does not exist (yet)", filename);
        }
    }
}

From source file:org.eclipse.hono.service.credentials.impl.FileBasedCredentialsService.java

License:Open Source License

protected void saveToFile(final Future<Void> writeResult) {

    if (!dirty) {
        log.trace("credentials registry does not need to be persisted");
        return;//  w  w w.  ja  v a2 s  . c  o  m
    }

    final FileSystem fs = vertx.fileSystem();
    if (!fs.existsBlocking(filename)) {
        fs.createFileBlocking(filename);
    }
    final AtomicInteger idCount = new AtomicInteger();
    JsonArray tenants = new JsonArray();
    for (Entry<String, Map<String, JsonArray>> entry : credentials.entrySet()) {
        JsonArray credentialsArray = new JsonArray();
        for (Entry<String, JsonArray> credentialEntry : entry.getValue().entrySet()) { // authId -> full json attributes object
            JsonArray singleAuthIdCredentials = credentialEntry.getValue(); // from one authId

            credentialsArray.add(singleAuthIdCredentials);
            idCount.incrementAndGet();
        }
        tenants.add(
                new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_CREDENTIALS, credentialsArray));
    }
    fs.writeFile(filename, Buffer.factory.buffer(tenants.encodePrettily()), writeAttempt -> {
        if (writeAttempt.succeeded()) {
            dirty = false;
            log.trace("successfully wrote {} credentials to file {}", idCount.get(), filename);
            writeResult.complete();
        } else {
            log.warn("could not write credentials to file {}", filename, writeAttempt.cause());
            writeResult.fail(writeAttempt.cause());
        }
    });
}

From source file:org.eclipse.hono.service.registration.impl.FileBasedRegistrationService.java

License:Open Source License

private void saveToFile(final Future<Void> writeResult) {

    if (!dirty) {
        log.trace("registry does not need to be persisted");
        return;// w w  w .java  2 s.c  o  m
    }

    final FileSystem fs = vertx.fileSystem();
    if (!fs.existsBlocking(filename)) {
        fs.createFileBlocking(filename);
    }
    final AtomicInteger idCount = new AtomicInteger();
    JsonArray tenants = new JsonArray();
    for (Entry<String, Map<String, JsonObject>> entry : identities.entrySet()) {
        JsonArray devices = new JsonArray();
        for (Entry<String, JsonObject> deviceEntry : entry.getValue().entrySet()) {
            devices.add(new JsonObject().put(FIELD_HONO_ID, deviceEntry.getKey()).put(FIELD_DATA,
                    deviceEntry.getValue()));
            idCount.incrementAndGet();
        }
        tenants.add(new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_DEVICES, devices));
    }
    fs.writeFile(filename, Buffer.factory.buffer(tenants.encodePrettily()), writeAttempt -> {
        if (writeAttempt.succeeded()) {
            dirty = false;
            log.trace("successfully wrote {} device identities to file {}", idCount.get(), filename);
            writeResult.complete();
        } else {
            log.warn("could not write device identities to file {}", filename, writeAttempt.cause());
            writeResult.fail(writeAttempt.cause());
        }
    });
}

From source file:org.eclipse.hono.util.TenantObject.java

License:Open Source License

/**
 * Gets the configuration information for this tenant's
 * configured adapters.//from  w w  w  .ja  va2  s. c  o  m
 * 
 * @return The configuration properties for this tenant's
 *         configured adapters or {@code null} if no specific
 *         configuration has been set for any protocol adapter.
 */
@JsonIgnore
public JsonArray getAdapterConfigurations() {
    if (adapterConfigurations == null) {
        return null;
    } else {
        final JsonArray result = new JsonArray();
        adapterConfigurations.values().forEach(config -> result.add((JsonObject) config));
        return result;
    }
}

From source file:org.entcore.archive.services.impl.DeleteOldExports.java

License:Open Source License

@Override
public void handle(Long event) {
    Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    c.add(Calendar.HOUR, -delay);
    final JsonObject query = new JsonObject().put("date",
            new JsonObject().put("$lt", new JsonObject().put("$date", c.getTime().getTime())));
    mongo.find(Archive.ARCHIVES, query, new Handler<Message<JsonObject>>() {
        @Override// w w  w  .  jav  a  2s .c o  m
        public void handle(Message<JsonObject> event) {
            JsonArray res = event.body().getJsonArray("results");
            if ("ok".equals(event.body().getString("status")) && res != null && res.size() > 0) {
                JsonArray ids = new fr.wseduc.webutils.collections.JsonArray();
                for (Object object : res) {
                    if (!(object instanceof JsonObject))
                        continue;
                    ids.add(((JsonObject) object).getString("file_id"));
                }
                storage.removeFiles(ids, new Handler<JsonObject>() {
                    @Override
                    public void handle(JsonObject event) {
                        mongo.delete(Archive.ARCHIVES, query);
                    }
                });
            }
        }
    });
}

From source file:org.entcore.auth.adapter.UserInfoAdapterV1_0Json.java

License:Open Source License

protected JsonObject getCommonFilteredInfos(JsonObject info, String clientId) {
    JsonObject filteredInfos = info.copy();
    String type = Utils.getOrElse(types.get(info.getString("type", "")), "");
    filteredInfos.put("type", type);
    filteredInfos.remove("cache");
    if (filteredInfos.getString("level") == null) {
        filteredInfos.put("level", "");
    } else if (filteredInfos.getString("level").contains("$")) {
        String[] level = filteredInfos.getString("level").split("\\$");
        filteredInfos.put("level", level[level.length - 1]);
    }/*www . j a v a 2s  .co  m*/
    if (clientId != null && !clientId.trim().isEmpty()) {
        JsonArray classNames = filteredInfos.getJsonArray("classNames");
        filteredInfos.remove("classNames");
        JsonArray structureNames = filteredInfos.getJsonArray("structureNames");
        filteredInfos.remove("structureNames");
        filteredInfos.remove("federated");
        if (classNames != null && classNames.size() > 0) {
            filteredInfos.put("classId", classNames.getString(0));
        }
        if (structureNames != null && structureNames.size() > 0) {
            filteredInfos.put("schoolName", structureNames.getString(0));
        }
        filteredInfos.remove("functions");
        filteredInfos.remove("groupsIds");
        filteredInfos.remove("structures");
        filteredInfos.remove("classes");
        filteredInfos.remove("apps");
        filteredInfos.remove("authorizedActions");
        filteredInfos.remove("children");
        JsonArray authorizedActions = new fr.wseduc.webutils.collections.JsonArray();
        for (Object o : info.getJsonArray("authorizedActions")) {
            JsonObject j = (JsonObject) o;
            String name = j.getString("name");
            if (name != null && name.startsWith(clientId + "|")) {
                authorizedActions.add(j);
            }
        }
        if (authorizedActions.size() > 0) {
            filteredInfos.put("authorizedActions", authorizedActions);
        }
    }
    return filteredInfos;
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

@Post("/forgot-id")
public void forgetId(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, new io.vertx.core.Handler<JsonObject>() {
        public void handle(JsonObject data) {
            final String mail = data.getString("mail");
            final String service = data.getString("service");
            final String firstName = data.getString("firstName");
            final String structure = data.getString("structureId");
            if (mail == null || mail.trim().isEmpty()) {
                badRequest(request);/* w  ww  . java2  s  .c o m*/
                return;
            }
            userAuthAccount.findByMailAndFirstNameAndStructure(mail, firstName, structure,
                    new io.vertx.core.Handler<Either<String, JsonArray>>() {
                        @Override
                        public void handle(Either<String, JsonArray> event) {
                            //No user with that email, or more than one found.
                            if (event.isLeft()) {
                                badRequest(request, event.left().getValue());
                                return;
                            }
                            JsonArray results = event.right().getValue();
                            if (results.size() == 0) {
                                badRequest(request, "no.match");
                                return;
                            }
                            JsonArray structures = new fr.wseduc.webutils.collections.JsonArray();
                            if (results.size() > 1) {
                                for (Object ob : results) {
                                    JsonObject j = (JsonObject) ob;
                                    j.remove("login");
                                    j.remove("mobile");
                                    if (!structures.toString().contains(j.getString("structureId")))
                                        structures.add(j);
                                }
                                if (firstName != null && structures.size() == 1)
                                    badRequest(request, "non.unique.result");
                                else
                                    renderJson(request, new JsonObject().put("structures", structures));
                                return;
                            }
                            JsonObject match = results.getJsonObject(0);
                            final String id = match.getString("login", "");
                            final String mobile = match.getString("mobile", "");

                            //Force mail
                            if ("mail".equals(service)) {
                                userAuthAccount.sendForgottenIdMail(request, id, mail,
                                        new io.vertx.core.Handler<Either<String, JsonObject>>() {
                                            public void handle(Either<String, JsonObject> event) {
                                                if (event.isLeft()) {
                                                    badRequest(request, event.left().getValue());
                                                    return;
                                                }
                                                if (smsProvider != null && !smsProvider.isEmpty()) {
                                                    final String obfuscatedMobile = StringValidation
                                                            .obfuscateMobile(mobile);
                                                    renderJson(request,
                                                            new JsonObject().put("mobile", obfuscatedMobile));
                                                } else {
                                                    renderJson(request, new JsonObject());
                                                }
                                            }
                                        });
                            } else if ("mobile".equals(service) && !mobile.isEmpty() && smsProvider != null
                                    && !smsProvider.isEmpty()) {
                                eventStore.createAndStoreEvent(AuthEvent.SMS.name(), id);
                                userAuthAccount.sendForgottenIdSms(request, id, mobile,
                                        DefaultResponseHandler.defaultResponseHandler(request));
                            } else {
                                badRequest(request);
                            }
                        }
                    });
        }
    });
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

@Get("/saml/wayf")
public void wayf(HttpServerRequest request) {
    if (samlWayfParams != null) {
        if (samlWayfMustacheFormat == null) {
            final JsonArray wmf = new fr.wseduc.webutils.collections.JsonArray();
            for (String attr : samlWayfParams.fieldNames()) {
                JsonObject i = samlWayfParams.getJsonObject(attr);
                if (i == null)
                    continue;
                final String acs = i.getString("acs");
                if (isEmpty(acs))
                    continue;
                URI uri;/*from   ww  w .j ava2s  .  c om*/
                try {
                    uri = new URI(acs);
                } catch (URISyntaxException e) {
                    log.error("Invalid acs URI", e);
                    continue;
                }
                JsonObject o = new JsonObject().put("name", attr).put("uri",
                        uri.getScheme() + "://" + uri.getHost()
                                + (attr.startsWith("login") ? "/auth/login" : "/auth/saml/authn/" + attr));
                wmf.add(o);
            }
            samlWayfMustacheFormat = new JsonObject().put("providers", wmf);
        }
        String callBack = request.params().get("callBack");
        final JsonObject swmf;
        if (isNotEmpty(callBack)
                && (ignoreCallBackPattern == null || !callBack.matches(ignoreCallBackPattern))) {
            try {
                callBack = URLEncoder.encode(callBack, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error("Error encode wayf callback.", e);
            }
            swmf = samlWayfMustacheFormat.copy();
            for (Object o : swmf.getJsonArray("providers")) {
                if (!(o instanceof JsonObject))
                    continue;
                final String uri = ((JsonObject) o).getString("uri");
                if (isNotEmpty(uri) && !uri.contains("callBack")) {
                    ((JsonObject) o).put("uri", uri + (uri.contains("?") ? "&" : "?") + "callBack=" + callBack);
                }
            }
        } else {
            swmf = samlWayfMustacheFormat;
        }
        renderView(request, swmf, "wayf.html", null);
    } else {
        request.response().setStatusCode(401).setStatusMessage("Unauthorized")
                .putHeader("content-type", "text/html").end(DefaultPages.UNAUTHORIZED.getPage());
    }
}