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.glencoesoftware.omero.ms.thumbnail.ThumbnailVerticle.java

License:Open Source License

/**
 * Get thumbnails event handler. Responds with a JSON dictionary of Base64
 * encoded <code>image/jpeg</code> thumbnails keyed by {@link Image}
 * identifier. Each dictionary value is prefixed with
 * <code>data:image/jpeg;base64,</code> so that it can be used with
 * <a href="http://caniuse.com/#feat=datauri">data URIs</a>.
 * @param message JSON encoded event data. Required keys are
 * <code>omeroSessionKey</code> (String), <code>longestSide</code>
 * (Integer), and <code>imageIds</code> (List<Long>).
 *///from  www.  j a  v a  2 s  . co m
private void getThumbnails(Message<String> message) {
    JsonObject data = new JsonObject(message.body());
    String omeroSessionKey = data.getString("omeroSessionKey");
    int longestSide = data.getInteger("longestSide");
    JsonArray imageIdsJson = data.getJsonArray("imageIds");
    List<Long> imageIds = new ArrayList<Long>();
    for (int i = 0; i < imageIdsJson.size(); i++) {
        imageIds.add(imageIdsJson.getLong(i));
    }
    log.debug("Render thumbnail request ImageIds:{} longest side {}", imageIds, longestSide);

    try (OmeroRequest request = new OmeroRequest(host, port, omeroSessionKey)) {
        Map<Long, byte[]> thumbnails = request
                .execute(new ThumbnailsRequestHandler(longestSide, imageIds)::renderThumbnails);

        if (thumbnails == null) {
            message.fail(404, "Cannot find one or more Images");
        } else {
            Map<Long, String> thumbnailsJson = new HashMap<Long, String>();
            for (Entry<Long, byte[]> v : thumbnails.entrySet()) {
                thumbnailsJson.put(v.getKey(), "data:image/jpeg;base64," + Base64.encode(v.getValue()));
            }
            message.reply(Json.encode(thumbnailsJson));
        }
    } catch (PermissionDeniedException | CannotCreateSessionException e) {
        String v = "Permission denied";
        log.debug(v);
        message.fail(403, v);
    } catch (Exception e) {
        String v = "Exception while retrieving thumbnail";
        log.error(v, e);
        message.fail(500, v);
    }
}

From source file:com.groupon.vertx.memcache.MemcacheConfig.java

License:Apache License

public MemcacheConfig(JsonObject jsonConfig) {
    if (jsonConfig == null) {
        log.error("initialize", "exception", "noConfigFound");
        throw new MemcacheException("No Memcache config found");
    }/*from   w ww  .  j  av  a  2  s. co m*/

    if (jsonConfig.getJsonArray(SERVERS_KEY) != null && jsonConfig.getString(EVENT_BUS_ADDRESS_KEY) != null
            && !jsonConfig.getString(EVENT_BUS_ADDRESS_KEY).isEmpty()) {
        this.servers.addAll(processServers(jsonConfig.getJsonArray(SERVERS_KEY)));
        this.eventBusAddress = jsonConfig.getString(EVENT_BUS_ADDRESS_KEY);
        this.namespace = jsonConfig.getString(NAMESPACE_KEY);
        this.pointsPerServer = jsonConfig.getInteger(POINTS_PER_SERVER, DEFAULT_POINTS_PER_SERVER);
        this.retryInterval = jsonConfig.getLong(RETRY_INTERVAL, DEFAULT_RETRY_INTERVAL);

        final HashAlgorithm defaultHashAlgorithm = HashAlgorithm.FNV1_32_HASH;
        String algorithmStr = jsonConfig.getString(ALGORITHM_KEY, defaultHashAlgorithm.name());
        this.algorithm = algorithmStr == null ? defaultHashAlgorithm : HashAlgorithm.valueOf(algorithmStr);

        final ContinuumType defaultContinuumType = ContinuumType.KETAMA;
        String continuumStr = jsonConfig.getString(CONTINUUM_KEY, defaultContinuumType.name());
        this.continuum = continuumStr == null ? defaultContinuumType : ContinuumType.valueOf(continuumStr);
    } else {
        log.error("initialize", "exception", "invalidConfigFound", new String[] { "config" },
                jsonConfig.encode());
        throw new MemcacheException("Invalid Memcache config defined");
    }

    log.info("initialize", "success", new String[] { "eventBusAddress", "namespace", "servers", "algorithm" },
            eventBusAddress, namespace, servers.size(), algorithm);
}

From source file:com.groupon.vertx.redis.RedisTransaction.java

License:Apache License

private JsonObject constructTransactionCommandResult(JsonObject response, int index) {
    JsonArray responses = response.getJsonArray("data");
    if (responses != null && responses.size() > index) {
        Object commandResult = responses.getValue(index);
        JsonObject result = new JsonObject();
        result.put("status", response.getString("status"));
        if (commandResult instanceof JsonArray) {
            result.put("data", (JsonArray) commandResult);
        } else if (commandResult instanceof String) {
            result.put("data", (String) commandResult);
        } else if (commandResult instanceof Number) {
            result.put("data", (Number) commandResult);
        }/*from   w  w w  .j  a v  a2 s .  c om*/
        return result;
    }
    return response;
}

From source file:com.groupon.vertx.utils.config.VerticleConfig.java

License:Apache License

public VerticleConfig(String name, JsonObject deployConfig) {

    if (name == null) {
        throw new IllegalStateException("Field `name` not specified for verticle");
    }/*  ww w.  ja v a2 s  .c o m*/

    if (deployConfig == null) {
        throw new IllegalStateException(String.format("Verticle %s config cannot be null", name));
    }

    this.name = name;
    final Object instancesAsObject = deployConfig.getValue("instances");
    if (instancesAsObject instanceof Integer) {
        instances = (Integer) instancesAsObject;
    } else if (instancesAsObject instanceof String) {
        instances = parseInstances((String) instancesAsObject);
    } else {
        throw new ClassCastException("Unsupported class type for 'instances'");
    }
    className = deployConfig.getString("class");
    config = deployConfig.getValue("config");
    isWorker = deployConfig.getBoolean("worker", false);
    isMultiThreaded = deployConfig.getBoolean("multiThreaded", false);

    JsonArray dependencyJson = deployConfig.getJsonArray("dependencies");
    if (dependencyJson != null) {
        dependencies = new HashSet<>(dependencyJson.size());
        for (Object dep : dependencyJson) {
            if (dep instanceof String) {
                dependencies.add((String) dep);
            }
        }
    } else {
        dependencies = Collections.emptySet();
    }

    if (instances < 1) {
        throw new IllegalStateException(
                String.format("Field `instances` not specified or less than 1 for verticle %s", name));
    }

    if (className == null) {
        throw new IllegalStateException(
                String.format("Field `className` not specified for for verticle %s", name));
    }
}

From source file:com.groupon.vertx.utils.MainVerticle.java

License:Apache License

static void registerMessageCodecs(final Vertx vertx, final JsonObject config,
        final boolean abortOnFailure) throws CodecRegistrationException {

    final JsonArray messageCodecs = config.getJsonArray(MESSAGE_CODECS_FIELD);
    if (messageCodecs != null) {
        for (final Object messageCodecClassNameObject : messageCodecs.getList()) {
            if (messageCodecClassNameObject instanceof String) {
                final String messageCodecClassName = (String) messageCodecClassNameObject;
                try {
                    final MessageCodec<?, ?> messageCodec = (MessageCodec<?, ?>) Class
                            .forName(messageCodecClassName).newInstance();
                    vertx.eventBus().registerCodec(messageCodec);
                } catch (final InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                    log.warn("registerMessageCodecs", "start",
                            new String[] { "message", "messageCodecClassName" },
                            "Failed to instantiate message codec", messageCodecClassName, e);
                    if (abortOnFailure) {
                        throw new CodecRegistrationException(
                                String.format("Failed to instantiate message codec %s", messageCodecClassName),
                                e);// w  ww  .  j  a va  2  s.c om
                    }
                }
            } else {
                log.warn("registerMessageCodecs", "start", new String[] { "message", "messageCodecClassName" },
                        "Ignoring non-string message codec class name", messageCodecClassNameObject);
                if (abortOnFailure) {
                    throw new CodecRegistrationException("Ignoring non-string message codec class name");
                }
            }
        }
    }
}

From source file:com.hpe.sw.cms.verticle.ApiVerticle.java

License:Apache License

/**
 * Handler to handle Docker Registry event
 *
 * @return handler context//from ww  w  . j  a v  a 2 s. c  o  m
 */
private Handler<RoutingContext> registryEventHandler() {
    return routingContext -> {
        JsonObject body = routingContext.getBodyAsJson();
        LOG.info("Docker Registry events received from {}", routingContext.request().getParam("registry"));
        JsonArray events = body.getJsonArray("events");
        JsonArray updated = new JsonArray();
        JsonArray deleted = new JsonArray();
        events.forEach(e -> {
            JsonObject event = (JsonObject) e;
            if (event.getString("action").equals("push")) {
                JsonObject obj = createObj(event);
                if (obj != null) {
                    updated.add(obj);
                }
            } else if (event.getString("action").equals("delete")) {
                JsonObject obj = createObj(event);
                if (obj != null) {
                    deleted.add(obj);
                }
            }
        });
        if (updated.size() != 0)
            vertx.eventBus().publish(Events.EVENT_IMAGES_UPDATED.name(), updated);
        if (deleted.size() != 0) //TODO
            vertx.eventBus().publish(Events.EVENT_IMAGES_DELETED.name(), deleted);
        //Always return 200 OK.
        routingContext.response().setStatusCode(200).end("OK");

    };
}

From source file:com.hpe.sw.cms.verticle.WatcherVerticle.java

License:Apache License

private void handler(Long h) {
    try {//from   w  w w .j a v a  2  s .c  o m
        String protocol = config().getString("registry.protocol");
        String host = config().getString("registry.host");
        httpClient.getAbs(protocol + host + "/v2/_catalog", new Handler<HttpClientResponse>() {
            @Override
            public void handle(HttpClientResponse httpClientResponse) {
                httpClientResponse.bodyHandler(new Handler<Buffer>() {
                    @Override
                    public void handle(Buffer buffer) {
                        JsonObject repositoryLib = buffer.toJsonObject();
                        JsonArray repos = repositoryLib.getJsonArray("repositories");
                        repos.forEach(repo -> {
                            if (repo != null && !((String) repo).trim().equals("")) {
                                try {
                                    repo = ((String) repo).trim();
                                    String[] imagePart = ((String) repo).split("/");
                                    String imageName = String.join("/", imagePart);
                                    httpClient.getAbs(protocol + host + "/v2/" + imageName + "/tags/list",
                                            new Handler<HttpClientResponse>() {
                                                @Override
                                                public void handle(HttpClientResponse httpClientResponse) {
                                                    httpClientResponse.bodyHandler(new Handler<Buffer>() {
                                                        @Override
                                                        public void handle(Buffer buffer) {
                                                            JsonObject tagLib = buffer.toJsonObject();
                                                            JsonArray tags = tagLib.getJsonArray("tags");
                                                            for (Object tag : tags) {
                                                                if (tag != null
                                                                        && !((String) tag).trim().equals("")) {
                                                                    JsonObject imageObj = new JsonObject();
                                                                    imageObj.put("name", imageName);
                                                                    imageObj.put("tag", tag);
                                                                    String dest = host;
                                                                    imageObj.put("host", dest);
                                                                    populateAndSendImage(imageObj);
                                                                }
                                                            }
                                                        }
                                                    });
                                                }
                                            }).end();

                                } catch (Exception e) {
                                    LOG.error("error in reading registry", e);
                                }
                            }
                        });
                    }
                });
            }
        }).end();
    } catch (Exception e) {
        LOG.error("error in registry handler", e);
    }
}

From source file:com.hpe.sw.cms.verticle.WatcherVerticle.java

License:Apache License

private void populateAndSendImage(JsonObject imageObj) {
    try {//  ww w  .  j av a 2 s.  co m
        String protocol = config().getString("registry.protocol");
        String host = config().getString("registry.host");
        httpClient.getAbs(protocol + host + "/v2/" + imageObj.getString("name") + "/manifests/"
                + imageObj.getString("tag"), new Handler<HttpClientResponse>() {
                    @Override
                    public void handle(HttpClientResponse httpClientResponse) {
                        httpClientResponse.bodyHandler(new Handler<Buffer>() {
                            @Override
                            public void handle(Buffer buffer) {
                                JsonObject maniFestLib = buffer.toJsonObject();
                                JsonArray signs = maniFestLib.getJsonArray("signatures");
                                if (signs != null && signs.size() > 0) {
                                    StringBuffer fullSign = new StringBuffer();
                                    for (Object sign : signs.getList()) {
                                        fullSign.append(((Map) sign).get("signature")).append("|");
                                    }
                                    imageObj.put(Image.SIGN, fullSign);
                                    imageObj.put(Image.IS_SCANNED, false);
                                    imageObj.put(Image.IS_ENRICHED, false);
                                    imageObj.put(Image.IS_SCANNED_FAILED, false);
                                    if (imageObj.getLong(Image.TIMESTAMP) == null) {
                                        imageObj.put(Image.TIMESTAMP, new Date().getTime());
                                    }
                                    vertx.eventBus().publish(Events.NEW_IMAGE.name(), imageObj);
                                    LOG.info("Event Image with populateSignToImage", imageObj);
                                }
                            }
                        });
                    }
                }).end();
    } catch (Exception e) {
        LOG.error("error in populateSignToImage", e);
    }
}

From source file:com.hubrick.vertx.rest.RestClientOptions.java

License:Apache License

public RestClientOptions(final JsonObject json) {
    super(json);//from  w w w .  j a  v a2s.  c om
    final JsonObject jsonObjectGlobalRequestCacheOptions = json.getJsonObject("globalRequestCacheOptions");
    if (jsonObjectGlobalRequestCacheOptions != null) {
        final RequestCacheOptions requestCacheOptions = new RequestCacheOptions();
        final Integer ttlInMillis = jsonObjectGlobalRequestCacheOptions.getInteger("ttlInMillis");
        final Boolean evictBefore = jsonObjectGlobalRequestCacheOptions.getBoolean("evictBefore");
        if (jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes") != null) {
            final Set<Integer> cachedStatusCodes = jsonObjectGlobalRequestCacheOptions
                    .getJsonArray("cachedStatusCodes").stream().map(e -> (Integer) e)
                    .collect(Collectors.toSet());
            requestCacheOptions.withCachedStatusCodes(cachedStatusCodes);
        }

        if (ttlInMillis != null) {
            requestCacheOptions.withExpiresAfterWriteMillis(ttlInMillis);
        }
        if (evictBefore != null) {
            requestCacheOptions.withEvictBefore(evictBefore);
        }
        globalRequestCacheOptions = requestCacheOptions;
    }
    globalHeaders = new CaseInsensitiveHeaders();
    globalRequestTimeoutInMillis = json.getLong("globalRequestTimeoutInMillis",
            DEFAULT_GLOBAL_REQUEST_TIMEOUT_IN_MILLIS);
}

From source file:com.nasa.Transformer.java

public static JsonObject conditionToMap(JsonObject jsonObject) {

    //        private String conditionsMap = "{\n"
    //            + "  \"Diseases\": [\n"
    //            + "    {\n"
    //            + "      \"lat\": 46.77029284,\n"
    //            + "      \"lng\": 23.57641889,\n"
    //            + "      \"type\": \"something good\",\n"
    //            + "      \"description\": \"good\",\n"
    //            + "      \"rating\": 1.23\n"
    //            + "    },\n"
    //            + "    {\n"
    //            + "      \"lat\": 46.78185201,\n"
    //            + "      \"lng\": 23.68522613,\n"
    //            + "      \"type\": \"something not bad\",\n"
    //            + "      \"description\": \"not bad\",\n"
    //            + "      \"rating\": 3.99\n"
    //            + "    },\n"
    //            + "    {\n"
    //            + "      \"lat\": 46.7558097,\n"
    //            + "      \"lng\": 23.5940353,\n"
    //            + "      \"type\": \"something bad\",\n"
    //            + "      \"description\": \"bad\",\n"
    //            + "      \"rating\": 4.75\n"
    //            + "    }\n"
    //            + "  ]\n"
    //            + "}";

    JsonObject result = new JsonObject();
    JsonArray featuresArr = new JsonArray();

    JsonArray items = jsonObject.getJsonObject("hits").getJsonArray("hits");

    for (Object hit : items) {
        JsonObject source = ((JsonObject) hit).getJsonObject("_source");

        JsonObject feature = new JsonObject();

        Float lon = source.getJsonObject("location").getFloat("lon");
        Float lat = source.getJsonObject("location").getFloat("lat");
        feature.put("lat", lat);
        feature.put("lng", lon);

        feature.put("type", source.getString("condition"));

        String symptoms = "";
        int ratingSum = 0;
        int ratingCount = 0;

        JsonArray symptomsJ = source.getJsonArray("symptoms");

        for (Object sym : symptomsJ) {
            JsonObject symJ = (JsonObject) sym;
            symptoms += symJ.getString("name") + ", ";
            ratingSum += symJ.getInteger("rating");
            ratingCount++;/*  ww w .ja  v a2  s. c  o  m*/
        }

        feature.put("description", symptoms);

        if (ratingCount > 0) {
            feature.put("rating", ratingSum / ratingCount);
        } else {
            feature.put("rating", 0);
        }

        featuresArr.add(feature);
    }

    result.put("Diseases", featuresArr);

    return result;
}