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

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

Introduction

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

Prototype

public JsonArray getJsonArray(String key) 

Source Link

Document

Get the JsonArray value with the specified key

Usage

From source file:com.reachauto.device.DeviceConverter.java

License:Apache License

public static void fromJson(JsonObject json, Device obj) {
    if (json.getValue("authInfo") instanceof String) {
        obj.setAuthInfo((String) json.getValue("authInfo"));
    }/*from w ww .j  a  va2 s. c  om*/
    if (json.getValue("delFlag") instanceof String) {
        obj.setDelFlag((String) json.getValue("delFlag"));
    }
    if (json.getValue("desc") instanceof String) {
        obj.setDesc((String) json.getValue("desc"));
    }
    if (json.getValue("id") instanceof Number) {
        obj.setId(((Number) json.getValue("id")).intValue());
    }
    if (json.getValue("location") instanceof JsonObject) {
        obj.setLocation(new com.reachauto.device.Location((JsonObject) json.getValue("location")));
    }
    if (json.getValue("other") instanceof String) {
        obj.setOther((String) json.getValue("other"));
    }
    if (json.getValue("privat") instanceof Boolean) {
        obj.setPrivat((Boolean) json.getValue("privat"));
    }
    if (json.getValue("protocol") instanceof String) {
        obj.setProtocol(com.reachauto.device.ProtocolType.valueOf((String) json.getValue("protocol")));
    }
    if (json.getValue("tags") instanceof JsonArray) {
        java.util.ArrayList<java.lang.String> list = new java.util.ArrayList<>();
        json.getJsonArray("tags").forEach(item -> {
            if (item instanceof String)
                list.add((String) item);
        });
        obj.setTags(list);
    }
    if (json.getValue("title") instanceof String) {
        obj.setTitle((String) json.getValue("title"));
    }
}

From source file:de.neofonie.deployer.DeployerVerticle.java

License:Open Source License

/**
 * Iterate and deploy verticles/*w w  w  .  ja  v  a 2 s.com*/
 */
private void deployVerticle(final Message<JsonObject> event) {

    // iterate over all candidates to be deployed
    Set<String> candidates = this.workingCopy.fieldNames();

    // detach from underlying json
    Map<String, JsonObject> initiants = new HashMap<>();
    candidates.forEach(id -> {
        JsonObject info = this.workingCopy.getJsonObject(id);
        JsonArray dependsOn = info.getJsonArray("dependsOn");
        if (dependsOn != null && deployed.getList().containsAll(dependsOn.getList()) || dependsOn == null
                || dependsOn.isEmpty()) {
            initiants.put(id, info);
        }
    });

    // remove the initiants
    initiants.keySet().forEach(id -> this.workingCopy.remove(id));

    // setup latch for the reply
    CountDownLatch latch = new CountDownLatch(initiants.size());
    if (initiants.isEmpty()) {
        event.reply(Boolean.TRUE);
        return;
    }

    // run over all dependencies
    initiants.forEach((id, info) -> {

        // get the name of the verticle
        String name = info.getString("name");
        final JsonObject localConfig = new JsonObject();
        localConfig.mergeIn(globalConfig);
        localConfig.mergeIn(info.getJsonObject("config", new JsonObject()));

        Handler<AsyncResult<String>> handler = innerEvent -> {
            if (innerEvent.succeeded()) {
                // add service to deployed-list
                deployed.add(id);

                // re-emit
                vertx.eventBus().send(LOOPBACK, workingCopy, (AsyncResult<Message<Boolean>> recursiveReply) -> {
                    // always decrease latch
                    latch.countDown();

                    if (recursiveReply.succeeded() && recursiveReply.result().body()) {
                        if (latch.getCount() == 0) {
                            event.reply(recursiveReply.result().body() & Boolean.TRUE);
                        }
                    } else {
                        event.fail(500, this.getFailure(id, recursiveReply));
                    }
                });

            } else {
                event.fail(500, id + " >> " + innerEvent.cause().getMessage());
            }
        };

        LOG.log(Level.INFO, "Deploying: ''{0}''", new Object[] { id });
        DeploymentOptions deploymentOptions = new DeploymentOptions(info);
        vertx.deployVerticle(name, deploymentOptions.setConfig(localConfig), handler);
    });
}

From source file:eu.rethink.mn.component.AllocationManager.java

License:Apache License

@Override
public void handle(PipeContext ctx) {
    final PipeMessage msg = ctx.getMessage();
    final JsonObject body = msg.getBody();

    if (msg.getType().equals("create")) {
        //process JSON msg requesting a number of available addresses
        final JsonObject msgBodyValue = body.getJsonObject("value");
        final String scheme = body.getString("scheme");

        int number = msgBodyValue.getInteger("number", 5);
        final List<String> allocated = allocate(ctx, scheme, number);

        final PipeMessage reply = new PipeMessage();
        reply.setId(msg.getId());//from   w w  w .  j a v  a2s .c  om
        reply.setFrom(name);
        reply.setTo(msg.getFrom());
        reply.setReplyCode(ReplyCode.OK);

        final JsonObject value = new JsonObject();
        value.put("allocated", new JsonArray(allocated));

        reply.getBody().put("value", value);

        ctx.reply(reply);

    } else if (msg.getType().equals("delete")) {
        //process JSON msg releasing an address
        final String resource = body.getString("resource");
        final JsonArray childrenResourcesList = body.getJsonArray("childrenResources");
        if (resource != null) {
            deallocate(ctx, resource);
        } else {
            for (Object childrenResource : childrenResourcesList) {
                deallocate(ctx, childrenResource.toString());
            }
        }

        ctx.replyOK(name);
    }
}

From source file:eu.rethink.mn.component.SubscriptionManager.java

License:Apache License

@Override
public void handle(PipeContext ctx) {
    final PipeMessage msg = ctx.getMessage();
    final JsonObject body = msg.getBody();
    logger.info("SubscriptionManager: " + msg);

    final JsonArray addressList = body.getJsonArray("resources");
    final JsonArray addressList2 = body.getJsonArray("subscribe");

    if (addressList != null && addressList2 == null) {

        addToAddressList(ctx, addressList);

    } else if (addressList == null && addressList2 != null) {

        addToAddressList(ctx, addressList2);

    } else if (addressList != null && addressList2 != null) {

        ctx.replyError(name, "You cant use field body.resources' and 'body.subscribe' at the same time");

    } else {//w  w  w. j  a v  a2  s .co  m

        ctx.replyError(name, "No mandatory field 'body.resources' or 'body.subscribe'");

    }
}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

/**
 * Copy a document from the rack to the workspace.
 * @param request Client request with file ids and destination folder (optional) in the body using json format.
 */// w  ww .  jav  a 2 s.c  o  m
@Post("/copy")
@SecuredAction(workspacecopy)
public void rackToWorkspace(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override
        public void handle(final UserInfos user) {
            if (user != null) {
                RequestUtils.bodyToJson(request, pathPrefix + "rackToWorkspace", new Handler<JsonObject>() {
                    @Override
                    public void handle(JsonObject json) {
                        JsonArray idsArray = json.getJsonArray("ids");
                        final String folder = json.getString("folder", "");
                        copyFiles(request, idsArray, folder, user, WORKSPACE_COLLECTION);
                    }
                });
            } else {
                badRequest(request);
            }
        }
    });
}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder,
        final UserInfos user, final String destinationCollection) {

    String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
    criteria += ", \"to\" : \"" + user.getUserId() + "\" }";

    mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {

        private void persist(final JsonArray insert, int remains) {
            if (remains == 0) {
                mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() {
                    @Override/*  w w  w  .  j a  v a  2s  . co  m*/
                    public void handle(Message<JsonObject> inserted) {
                        if ("ok".equals(inserted.body().getString("status"))) {
                            /* Increment quota */
                            long totalSize = 0l;
                            for (Object insertion : insert) {
                                JsonObject added = (JsonObject) insertion;
                                totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size",
                                        0l);
                            }
                            updateUserQuota(user.getUserId(), totalSize);
                            renderJson(request, inserted.body());
                        } else {
                            renderError(request, inserted.body());
                        }
                    }
                });
            }
        }

        @Override
        public void handle(Message<JsonObject> r) {
            JsonObject src = r.body();
            if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                final JsonArray origs = src.getJsonArray("results");
                final JsonArray insert = new JsonArray();
                final AtomicInteger number = new AtomicInteger(origs.size());

                emptySize(user, new Handler<Long>() {

                    @Override
                    public void handle(Long emptySize) {
                        long size = 0;

                        /* Get total file size */
                        for (Object o : origs) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                            if (metadata != null) {
                                size += metadata.getLong("size", 0l);
                            }
                        }
                        /* If total file size is too big (> quota left) */
                        if (size > emptySize) {
                            badRequest(request, "files.too.large");
                            return;
                        }

                        /* Process */
                        for (Object o : origs) {
                            JsonObject orig = (JsonObject) o;
                            final JsonObject dest = orig.copy();
                            String now = MongoDb.formatDate(new Date());
                            dest.remove("_id");
                            dest.remove("protected");
                            dest.remove("comments");
                            dest.put("application", WORKSPACE_NAME);

                            dest.put("owner", user.getUserId());
                            dest.put("ownerName", dest.getString("toName"));
                            dest.remove("to");
                            dest.remove("from");
                            dest.remove("toName");
                            dest.remove("fromName");

                            dest.put("created", now);
                            dest.put("modified", now);
                            if (folder != null && !folder.trim().isEmpty()) {
                                dest.put("folder", folder);
                            } else {
                                dest.remove("folder");
                            }
                            insert.add(dest);
                            final String filePath = orig.getString("file");

                            if (folder != null && !folder.trim().isEmpty()) {

                                //If the document has a new parent folder, replicate sharing rights
                                String parentName, parentFolder;
                                if (folder.lastIndexOf('_') < 0) {
                                    parentName = folder;
                                    parentFolder = folder;
                                } else if (filePath != null) {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 1];
                                    parentFolder = folder;
                                } else {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 2];
                                    parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                }

                                QueryBuilder parentFolderQuery = QueryBuilder.start("owner")
                                        .is(user.getUserId()).and("folder").is(parentFolder).and("name")
                                        .is(parentName);

                                mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery),
                                        new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> event) {
                                                if ("ok".equals(event.body().getString("status"))) {
                                                    JsonObject parent = event.body().getJsonObject("result");
                                                    if (parent != null && parent.getJsonArray("shared") != null
                                                            && parent.getJsonArray("shared").size() > 0)
                                                        dest.put("shared", parent.getJsonArray("shared"));

                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                } else {
                                                    renderJson(request, event.body(), 404);
                                                }
                                            }
                                        });

                            } else if (filePath != null) {
                                storage.copyFile(filePath, new Handler<JsonObject>() {

                                    @Override
                                    public void handle(JsonObject event) {
                                        if (event != null && "ok".equals(event.getString("status"))) {
                                            dest.put("file", event.getString("_id"));
                                            persist(insert, number.decrementAndGet());
                                        }
                                    }
                                });
                            } else {
                                persist(insert, number.decrementAndGet());
                            }
                        }
                    }
                });
            } else {
                notFound(request, src.toString());
            }
        }
    });

}

From source file:io.apiman.gateway.engine.vertx.polling.PolicyConfigLoader.java

License:Apache License

@SuppressWarnings("unchecked")
private <T, K> List<T> requireJsonArray(String keyName, JsonObject json, Class<K> klazz) {
    // Contains key.
    Arguments.require(json.containsKey(keyName), String.format("Must provide array of %s objects for key '%s'",
            StringUtils.capitalize(keyName), keyName));
    // Is of type array.
    Arguments.require(json.getValue(keyName) instanceof JsonArray,
            String.format("'%s' must be a Json array", keyName));
    // Transform into List<T>.
    return Json.decodeValue(json.getJsonArray(keyName).encode(), List.class, klazz);
}

From source file:io.apiman.gateway.platforms.vertx3.common.config.InheritingHttpServerOptionsConverter.java

License:Apache License

public static void fromJson(JsonObject json, InheritingHttpServerOptions obj) {
    if (json.getValue("acceptBacklog") instanceof Number) {
        obj.setAcceptBacklog(((Number) json.getValue("acceptBacklog")).intValue());
    }/*w w  w . j a  v a2  s  . c om*/
    if (json.getValue("acceptUnmaskedFrames") instanceof Boolean) {
        obj.setAcceptUnmaskedFrames((Boolean) json.getValue("acceptUnmaskedFrames"));
    }
    if (json.getValue("alpnVersions") instanceof JsonArray) {
        java.util.ArrayList<io.vertx.core.http.HttpVersion> list = new java.util.ArrayList<>();
        json.getJsonArray("alpnVersions").forEach(item -> {
            if (item instanceof String)
                list.add(io.vertx.core.http.HttpVersion.valueOf((String) item));
        });
        obj.setAlpnVersions(list);
    }
    if (json.getValue("clientAuth") instanceof String) {
        obj.setClientAuth(io.vertx.core.http.ClientAuth.valueOf((String) json.getValue("clientAuth")));
    }
    if (json.getValue("clientAuthRequired") instanceof Boolean) {
        obj.setClientAuthRequired((Boolean) json.getValue("clientAuthRequired"));
    }
    if (json.getValue("compressionLevel") instanceof Number) {
        obj.setCompressionLevel(((Number) json.getValue("compressionLevel")).intValue());
    }
    if (json.getValue("compressionSupported") instanceof Boolean) {
        obj.setCompressionSupported((Boolean) json.getValue("compressionSupported"));
    }
    if (json.getValue("crlPaths") instanceof JsonArray) {
        json.getJsonArray("crlPaths").forEach(item -> {
            if (item instanceof String)
                obj.addCrlPath((String) item);
        });
    }
    if (json.getValue("crlValues") instanceof JsonArray) {
        json.getJsonArray("crlValues").forEach(item -> {
            if (item instanceof String)
                obj.addCrlValue(io.vertx.core.buffer.Buffer
                        .buffer(java.util.Base64.getDecoder().decode((String) item)));
        });
    }
    if (json.getValue("decompressionSupported") instanceof Boolean) {
        obj.setDecompressionSupported((Boolean) json.getValue("decompressionSupported"));
    }
    if (json.getValue("enabledCipherSuites") instanceof JsonArray) {
        json.getJsonArray("enabledCipherSuites").forEach(item -> {
            if (item instanceof String)
                obj.addEnabledCipherSuite((String) item);
        });
    }
    if (json.getValue("enabledSecureTransportProtocols") instanceof JsonArray) {
        json.getJsonArray("enabledSecureTransportProtocols").forEach(item -> {
            if (item instanceof String)
                obj.addEnabledSecureTransportProtocol((String) item);
        });
    }
    if (json.getValue("handle100ContinueAutomatically") instanceof Boolean) {
        obj.setHandle100ContinueAutomatically((Boolean) json.getValue("handle100ContinueAutomatically"));
    }
    if (json.getValue("host") instanceof String) {
        obj.setHost((String) json.getValue("host"));
    }
    if (json.getValue("http2ConnectionWindowSize") instanceof Number) {
        obj.setHttp2ConnectionWindowSize(((Number) json.getValue("http2ConnectionWindowSize")).intValue());
    }
    if (json.getValue("idleTimeout") instanceof Number) {
        obj.setIdleTimeout(((Number) json.getValue("idleTimeout")).intValue());
    }
    if (json.getValue("initialSettings") instanceof JsonObject) {
        obj.setInitialSettings(
                new io.vertx.core.http.Http2Settings((JsonObject) json.getValue("initialSettings")));
    }
    if (json.getValue("jdkSslEngineOptions") instanceof JsonObject) {
        obj.setJdkSslEngineOptions(
                new io.vertx.core.net.JdkSSLEngineOptions((JsonObject) json.getValue("jdkSslEngineOptions")));
    }
    if (json.getValue("keyStoreOptions") instanceof JsonObject) {
        obj.setKeyStoreOptions(new io.vertx.core.net.JksOptions((JsonObject) json.getValue("keyStoreOptions")));
    }
    if (json.getValue("logActivity") instanceof Boolean) {
        obj.setLogActivity((Boolean) json.getValue("logActivity"));
    }
    if (json.getValue("maxChunkSize") instanceof Number) {
        obj.setMaxChunkSize(((Number) json.getValue("maxChunkSize")).intValue());
    }
    if (json.getValue("maxHeaderSize") instanceof Number) {
        obj.setMaxHeaderSize(((Number) json.getValue("maxHeaderSize")).intValue());
    }
    if (json.getValue("maxInitialLineLength") instanceof Number) {
        obj.setMaxInitialLineLength(((Number) json.getValue("maxInitialLineLength")).intValue());
    }
    if (json.getValue("maxWebsocketFrameSize") instanceof Number) {
        obj.setMaxWebsocketFrameSize(((Number) json.getValue("maxWebsocketFrameSize")).intValue());
    }
    if (json.getValue("maxWebsocketMessageSize") instanceof Number) {
        obj.setMaxWebsocketMessageSize(((Number) json.getValue("maxWebsocketMessageSize")).intValue());
    }
    if (json.getValue("openSslEngineOptions") instanceof JsonObject) {
        obj.setOpenSslEngineOptions(
                new io.vertx.core.net.OpenSSLEngineOptions((JsonObject) json.getValue("openSslEngineOptions")));
    }
    if (json.getValue("pemKeyCertOptions") instanceof JsonObject) {
        obj.setPemKeyCertOptions(
                new io.vertx.core.net.PemKeyCertOptions((JsonObject) json.getValue("pemKeyCertOptions")));
    }
    if (json.getValue("pemTrustOptions") instanceof JsonObject) {
        obj.setPemTrustOptions(
                new io.vertx.core.net.PemTrustOptions((JsonObject) json.getValue("pemTrustOptions")));
    }
    if (json.getValue("pfxKeyCertOptions") instanceof JsonObject) {
        obj.setPfxKeyCertOptions(
                new io.vertx.core.net.PfxOptions((JsonObject) json.getValue("pfxKeyCertOptions")));
    }
    if (json.getValue("pfxTrustOptions") instanceof JsonObject) {
        obj.setPfxTrustOptions(new io.vertx.core.net.PfxOptions((JsonObject) json.getValue("pfxTrustOptions")));
    }
    if (json.getValue("port") instanceof Number) {
        obj.setPort(((Number) json.getValue("port")).intValue());
    }
    if (json.getValue("receiveBufferSize") instanceof Number) {
        obj.setReceiveBufferSize(((Number) json.getValue("receiveBufferSize")).intValue());
    }
    if (json.getValue("reuseAddress") instanceof Boolean) {
        obj.setReuseAddress((Boolean) json.getValue("reuseAddress"));
    }
    if (json.getValue("sendBufferSize") instanceof Number) {
        obj.setSendBufferSize(((Number) json.getValue("sendBufferSize")).intValue());
    }
    if (json.getValue("soLinger") instanceof Number) {
        obj.setSoLinger(((Number) json.getValue("soLinger")).intValue());
    }
    if (json.getValue("ssl") instanceof Boolean) {
        obj.setSsl((Boolean) json.getValue("ssl"));
    }
    if (json.getValue("tcpKeepAlive") instanceof Boolean) {
        obj.setTcpKeepAlive((Boolean) json.getValue("tcpKeepAlive"));
    }
    if (json.getValue("tcpNoDelay") instanceof Boolean) {
        obj.setTcpNoDelay((Boolean) json.getValue("tcpNoDelay"));
    }
    if (json.getValue("trafficClass") instanceof Number) {
        obj.setTrafficClass(((Number) json.getValue("trafficClass")).intValue());
    }
    if (json.getValue("trustStoreOptions") instanceof JsonObject) {
        obj.setTrustStoreOptions(
                new io.vertx.core.net.JksOptions((JsonObject) json.getValue("trustStoreOptions")));
    }
    if (json.getValue("useAlpn") instanceof Boolean) {
        obj.setUseAlpn((Boolean) json.getValue("useAlpn"));
    }
    if (json.getValue("usePooledBuffers") instanceof Boolean) {
        obj.setUsePooledBuffers((Boolean) json.getValue("usePooledBuffers"));
    }
    if (json.getValue("websocketSubProtocols") instanceof String) {
        obj.setWebsocketSubProtocols((String) json.getValue("websocketSubProtocols"));
    }
}

From source file:io.fabric8.devops.apps.elasticsearch.helper.service.ElasticSearchOptionsConverter.java

License:Apache License

public static void fromJson(JsonObject json, ElasticSearchOptions obj) {
    if (json.getValue("configMap") instanceof String) {
        obj.setConfigMap((String) json.getValue("configMap"));
    }//w w w  .  ja v a  2 s  .c  o m
    if (json.getValue("configMapScanPeriod") instanceof Number) {
        obj.setConfigMapScanPeriod(((Number) json.getValue("configMapScanPeriod")).longValue());
    }
    if (json.getValue("host") instanceof String) {
        obj.setHost((String) json.getValue("host"));
    }
    if (json.getValue("indexes") instanceof JsonArray) {
        java.util.ArrayList<java.lang.String> list = new java.util.ArrayList<>();
        json.getJsonArray("indexes").forEach(item -> {
            if (item instanceof String)
                list.add((String) item);
        });
        obj.setIndexes(list);
    }
    if (json.getValue("indexs") instanceof JsonArray) {
        json.getJsonArray("indexs").forEach(item -> {
            if (item instanceof String)
                obj.addIndex((String) item);
        });
    }
    if (json.getValue("kubernetesNamespace") instanceof String) {
        obj.setKubernetesNamespace((String) json.getValue("kubernetesNamespace"));
    }
    if (json.getValue("port") instanceof Number) {
        obj.setPort(((Number) json.getValue("port")).intValue());
    }
    if (json.getValue("ssl") instanceof Boolean) {
        obj.setSsl((Boolean) json.getValue("ssl"));
    }
}

From source file:io.flowly.auth.ExtJwtAuthProvider.java

License:Open Source License

@Override
public String generateToken(JsonObject claims, final JWTOptions options) {
    final JsonObject jsonOptions = options.toJSON();

    // we do some "enhancement" of the claims to support roles and permissions
    if (jsonOptions.containsKey("permissions") && !claims.containsKey(permissionsClaimKey)) {
        claims.put(permissionsClaimKey, jsonOptions.getJsonArray("permissions"));
    }//from w w  w  .  j ava2s .c  o  m

    return jwt.sign(claims, options.toJSON());
}