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

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

Introduction

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

Prototype

public String getString(String key) 

Source Link

Document

Get the string value with the specified key, special cases are addressed for extended JSON types Instant , byte[] and Enum which can be converted to String.

Usage

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

License:Apache License

public MemcacheClusterConfig(JsonObject jsonConfig) {
    if (jsonConfig == null) {
        log.error("initialize", "exception", "noConfigFound");
        throw new MemcacheException("No Memcache cluster config found");
    }// w ww . j  av  a2 s.  c om

    this.eventBusAddressPrefix = jsonConfig.getString(EVENT_BUS_ADDRESS_PREFIX_KEY);
    this.retryInterval = jsonConfig.getLong(RETRY_INTERVAL, MemcacheConfig.DEFAULT_RETRY_INTERVAL);
    JsonObject clusters = jsonConfig.getJsonObject(CLUSTERS_KEY, new JsonObject());

    if (eventBusAddressPrefix != null && !eventBusAddressPrefix.isEmpty() && clusters.size() > 0) {
        for (String clusterKey : clusters.fieldNames()) {
            JsonObject clusterConfig = clusters.getJsonObject(clusterKey, new JsonObject()).copy();
            clusterConfig.put(EVENT_BUS_ADDRESS_KEY, eventBusAddressPrefix);
            clusterConfig.put(RETRY_INTERVAL, retryInterval);
            clusterMap.put(clusterKey, new MemcacheConfig(clusterConfig));
        }
    } else {
        log.error("initialize", "exception", "invalidConfigFound", new String[] { "config" },
                jsonConfig.encode());
        throw new MemcacheException("Invalid Memcache config defined");
    }

    log.info("initialize", "success", new String[] { "eventBusAddressPrefix", "clusters" },
            eventBusAddressPrefix, clusterMap.size());
}

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 w  w  .  jav  a 2  s. c  om*/

    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.RedisCommand.java

License:Apache License

/**
 * If the command represented by the JsonObject doesn't come in the form:
 * <br>// ww w.jav  a  2s  .  c o m
 * <code>
 * {
 *   'command': 'GET',
 *   'arguments': [ 'somekey' ]
 * }
 * </code>
 * <br>
 * Then an exception will be thrown.
 *
 * @param commandJson - The command to be created.
 */
public RedisCommand(JsonObject commandJson) {
    if (commandJson == null || commandJson.size() != 2) {
        log.warn("initRedisCommand", "failure", new String[] { "reason" }, "Invalid command format");
        throw new IllegalArgumentException("Invalid command format");
    }

    try {
        type = RedisCommandType.valueOf(commandJson.getString("command"));
    } catch (Exception ex) {
        log.warn("initRedisCommand", "failure", new String[] { "reason" }, "Invalid command");
        throw new IllegalArgumentException("Invalid or unsupported command provided");
    }

    Object objectArguments = commandJson.getValue("arguments");
    if (objectArguments != null) {
        if (objectArguments instanceof JsonArray) {
            for (Object arg : (JsonArray) objectArguments) {
                if (arg instanceof String) {
                    arguments.add((String) arg);
                } else {
                    arguments.add(arg.toString());
                }
            }
        } else {
            arguments.add(objectArguments.toString());
        }
    }
}

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

License:Apache License

public RedisConfig(JsonObject redisConfigObj) throws Exception {
    this.host = redisConfigObj.getString(HOST_KEY);
    this.port = redisConfigObj.getInteger(PORT_KEY, port);
    this.eventBusAddress = redisConfigObj.getString(EVENT_BUS_ADDRESS_KEY);
    this.retryInterval = redisConfigObj.getLong(RETRY_INTERVAL_KEY, retryInterval);
    this.replyTimeout = redisConfigObj.getLong(REPLY_TIMEOUT_KEY, replyTimeout);

    if (host == null || host.isEmpty() || eventBusAddress == null || eventBusAddress.isEmpty()) {
        throw new Exception("Invalid Redis config.");
    }/*from www .ja v  a 2 s .c o m*/
}

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  ww.  j  a  va2s .  c  o  m
        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");
    }//from  ww w . j  a  v a 2s . co  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.hpe.sw.cms.store.Image.java

License:Apache License

public static String getImageKey(JsonObject image) {
    return image.getString(HOST) + "/" + image.getString(NAME) + ":" + image.getString(TAG);
}

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

License:Apache License

/**
 * Handler to handle GET /images/:id request. Response is the image scan files (with/without enrich).
 *
 * @return/*from  w  w  w.j  a va 2 s . com*/
 */
private Handler<RoutingContext> downloadHandler() {
    return routingContext -> {
        String category = routingContext.request().getParam("fileCategory");
        JsonObject params = new JsonObject();
        if (routingContext.request().getParam("id") != null) {
            params.put(Image.IMAGE_ID, routingContext.request().getParam("id"));
        } else {
            params.put(Image.HOST, routingContext.request().getParam(Image.HOST));
            params.put(Image.NAME, routingContext.request().getParam(Image.NAME));
            params.put(Image.TAG, routingContext.request().getParam(Image.TAG));
        }
        vertx.eventBus().send(Events.DOWNLOAD_FILE.name(), params, event -> {
            if (event.succeeded() && event.result() != null) {
                Message msg = event.result();
                JsonObject file = (JsonObject) msg.body();
                routingContext.response().setChunked(true);
                if (file == null) {
                    routingContext.response().setStatusCode(404).end("There is no image  found.");
                    return;
                }
                if ("enrich".equals(category) && file.getBinary(Image.ENRICHED_FILE) != null) {
                    String fileName = file.getString(Image.HOST) + "___" + file.getString(Image.NAME) + "___"
                            + file.getString(Image.IMAGE_ID) + ".xsf";
                    routingContext.response().putHeader("Content-Disposition",
                            "attachment; filename = " + fileName);
                    Buffer buffer = Buffer.buffer(file.getBinary(Image.ENRICHED_FILE));
                    routingContext.response().end(buffer);
                } else if ("enrich_xml".equals(category) && file.getBinary(Image.SCANNED_FILE) != null) {
                    routingContext.response().end(decompressGzip(file.getBinary(Image.ENRICHED_FILE)));
                } else if ("scan".equals(category) && file.getBinary(Image.SCANNED_FILE) != null) {
                    String fileName = file.getString(Image.HOST) + "___" + file.getString(Image.NAME) + "___"
                            + file.getString(Image.IMAGE_ID) + ".xsf";
                    routingContext.response().putHeader("Content-Disposition",
                            "attachment; filename = " + fileName);
                    Buffer buffer = Buffer.buffer(file.getBinary(Image.SCANNED_FILE));
                    routingContext.response().end(buffer);
                } else if ("scan_xml".equals(category) && file.getBinary(Image.SCANNED_FILE) != null) {
                    routingContext.response().end(decompressGzip(file.getBinary(Image.SCANNED_FILE)));
                }
            } else if (event.result() == null) {
                routingContext.response().setStatusCode(404).end("There is no image  found.");
            } else {
                routingContext.response().setStatusCode(500).end("Server has error.");
            }
        });
    };
}

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

License:Apache License

/**
 * Handler to handle Docker Registry event
 *
 * @return handler context//from  w  w w.  j a  va  2 s.  com
 */
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.ApiVerticle.java

License:Apache License

private JsonObject createObj(JsonObject event) {
    try {//from  w w w  .  ja  v a2  s.c o  m
        JsonObject image = new JsonObject();
        String timestamp = event.getString("timestamp");
        if (timestamp != null && timestamp.length() > 19) {
            timestamp = timestamp.substring(0, 10) + " " + timestamp.substring(11, 19);
            image.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timestamp).getTime());
        }
        String url = event.getJsonObject("target").getString("url");
        image.put("name", event.getJsonObject("target").getString("repository"));
        image.put("host", event.getJsonObject("request").getString("host"));
        image.put(Image.EVENT_URL, url);
        return image;
    } catch (Exception e) {
        LOG.error("Error in reading event to object ", e);
        return null;
    }
}