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

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

Introduction

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

Prototype

public JsonObject getJsonObject(String key) 

Source Link

Document

Get the JsonObject value with the specified key

Usage

From source file:com.cyngn.vertx.bosun.OpenTsDbMetric.java

License:Apache License

public OpenTsDbMetric(JsonObject obj) {
    if (obj == null) {
        throw new IllegalArgumentException("You must supply a non-null JsonObject");
    }/*from  w  w w  .  ja v  a  2  s . c om*/

    this.metric = obj.getString(METRIC_FIELD);
    this.value = obj.getValue(VALUE_FIELD);
    this.tags = obj.getJsonObject(TAGS_FIELD);
    timestamp = System.currentTimeMillis();
    validateObj();
}

From source file:com.cyngn.vertx.opentsdb.service.MetricsParser.java

License:Apache License

/**
 * Given a event bus message take the metric data from it and create an OpenTsDb string to send to OpenTsDb
 *
 * @param message the event bus message//from w  w w.j  a  v  a 2s .  co  m
 * @param metric the metric object
 * @return the metric string or null if it is invalid
 */
@SuppressWarnings("unchecked")
public String createMetricString(Message message, JsonObject metric) {
    String metricName = metric.getString(NAME_FIELD, "");
    if (StringUtils.isEmpty(metricName)) {
        errorHandler.accept(message, "All metrics need a 'name' field");
        return null;
    }

    String metricValue = metric.getString(VALUE_FIELD, "");
    if (metricValue.length() == 0) {
        errorHandler.accept(message, "All metrics need a 'value' field");
        return null;
    }

    String tags = getTagString(metric.getJsonObject(TAGS_FIELD));

    // this is an OpenTsDB requirement
    if (StringUtils.isEmpty(tags.trim())) {
        errorHandler.accept(message, "You must specify at least one tag");
        return null;
    }

    return getMetricString(metricName, metricValue, tags);
}

From source file:com.deblox.releaseboard.ReleaseBoardVerticle.java

License:Apache License

/**
 * Start the verticle//from  www. java  2 s .c o m
 *
 * @param startFuture
 * @throws Exception
 */
public void start(Future<Void> startFuture) throws Exception {

    logger.info("starup with config: " + config().toString());

    // get expire_release in seconds
    int expire_timeout = config().getInteger("expire_timeout", 86000);

    // map of releases, should contain date events were fired in  / updated also
    releasesData = new HashMap<>();

    stateFile = config().getString("state_file", "/state.json");

    // connect to the eventbus
    eb = vertx.eventBus();

    // load the state file if exists
    vertx.fileSystem().exists(stateFile, h -> {
        if (h.succeeded()) {
            try {
                JsonArray history = Util.loadConfig(stateFile).getJsonArray("releases");
                for (Object release : history) {
                    JsonObject releaseJson = new JsonObject(release.toString());
                    logger.info("loading release: " + releaseJson.getString("id"));
                    releasesData.put(releaseJson.getString("id"), releaseJson.getJsonObject("data"));
                }

            } catch (IOException e) {
                logger.warn("unable to load state file, it will be created / overwritten");
                e.printStackTrace();
            }

        }
    });

    /*
     * listen for release events from other verticles / clients
     *
     * example release-event published direct to the eventbus ( see Server.java )
     *
            
      {
          "code": 205,
          "component": "maximus",
          "environment": "CI1",
          "status": "Deploy Succeeded",
          "version": "1.0.0.309"
      }
            
     *
     *
     */
    eb.consumer("release-event", event -> {
        logger.info(event.body().toString());

        JsonObject body = null;

        // create a json object from the message
        try {
            body = new JsonObject(event.body().toString());
        } catch (Exception e) {
            logger.warn("not a json object");
            event.reply(new JsonObject().put("result", "failure").put("reason", "that wasn't json"));
        }

        // create check if a id is specified, else combine component and version
        body.put("id", body.getString("id", body.getValue("component") + "-" + body.getValue("version")));

        // used for marking expired messages when time is not enough or too much
        body.put("expired", false);

        // add the date now
        body.put("date", LocalDateTime.now().format(formatter));

        // pop the old matching JIRA release
        releasesData.remove(body.getString("id"));

        // put the updated one
        releasesData.put(body.getString("id"), body);

        event.reply(new JsonObject().put("result", "success"));

    });

    // expire a release event and remove it from the map
    eb.consumer("expire-release-event", event -> {
        try {
            logger.info("delete event: " + event.body().toString());
            JsonObject request = new JsonObject(event.body().toString());
            releasesData.remove(request.getString("id"));

            // forulate the expire message
            JsonObject msg = new JsonObject().put("topic", "releases").put("action", "expire");
            JsonArray arr = new JsonArray().add(request.getString("id"));
            msg.put("data", arr);

            eb.publish("releases", msg);

            event.reply(new JsonObject().put("result", "success"));
        } catch (Exception e) {
            event.reply(new JsonObject().put("result", "error"));
        }
    });

    vertx.setPeriodic(10000, tid -> {

        JsonObject msg = new JsonObject();
        msg.put("topic", "releases");
        msg.put("action", "default");

        JsonArray rel = new JsonArray();

        Iterator<Map.Entry<String, JsonObject>> iter = releasesData.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, JsonObject> entry = iter.next();
            rel.add(entry.getValue());
        }

        msg.put("data", rel);

        eb.publish("releases", msg);

    });

    // periodically expire old releases in the map
    vertx.setPeriodic(config().getInteger("check_expiry", 1000), res -> {
        // iterate over map, check dates for each, expire as needed

        Iterator<Map.Entry<String, JsonObject>> iter = releasesData.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, JsonObject> entry = iter.next();

            logger.debug("checking expiry on " + entry.getKey() + " v " + entry.getValue());

            // now
            LocalDateTime now = LocalDateTime.now();

            // then
            LocalDateTime then = LocalDateTime.parse(entry.getValue().getString("date"), formatter);

            // delta
            Long delta = now.toEpochSecond(ZoneOffset.UTC) - then.toEpochSecond(ZoneOffset.UTC);

            if (delta >= expire_timeout) {
                logger.info("expiring stale release: " + entry.getValue() + " delta: " + delta.toString());
                iter.remove();
            }

        }

    });

    // save the current pile of releases into a JSON periodically
    vertx.setPeriodic(config().getInteger("save_interval", 60000), t -> {
        saveState();
    });

    startFuture.complete();

}

From source file:com.deblox.server.Server.java

License:Apache License

@Override
public void start(Future<Void> startFuture) {
    logger.info("starting with config: " + config().toString());

    Router router = Router.router(vertx);

    // Allow events for the designated addresses in/out of the event bus bridge
    BridgeOptions opts = new BridgeOptions().addInboundPermitted(new PermittedOptions())
            .addOutboundPermitted(new PermittedOptions());

    // Create the event bus bridge and add it to the router.
    SockJSHandler ebHandler = SockJSHandler.create(vertx).bridge(opts);
    router.route("/eventbus/*").handler(ebHandler);

    // broadcast some arbitary message
    router.post("/api/event").handler(ctx -> {
        ctx.response().putHeader("content-type", "text/json");

        // curl -H "Content-Type: application/json" -X POST -d '{"topic":"release-event", "data":"something"}' localhost:8080/api/event
        ctx.request().bodyHandler(req -> {

            try {
                JsonObject msg = new JsonObject(req.toString());
                logger.info(msg);/*from   w  w  w.  j  av a  2  s  .  co  m*/

                eb.send(msg.getString("topic", "unknown"), msg.getJsonObject("data"), resp -> {
                    ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                            .end(resp.result().body().toString());
                });

            } catch (Exception ex) {
                logger.error(ex.getMessage());
                ctx.fail(500);
            }

        });

    });

    // Serve the static pages
    router.route().handler(StaticHandler.create().setCachingEnabled(false)
            .setWebRoot(config().getString("webroot", "webroot")).setDirectoryListing(false));

    // the server itself
    vertx.createHttpServer().requestHandler(router::accept).listen(config().getInteger("port", 8080));

    // need a bus!
    eb = vertx.eventBus();

    // send back deployment complete
    startFuture.complete();
}

From source file:com.emikra.vertx.oak.OakServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
        throw new IllegalStateException("action not specified");
    }/*w  ww .j a  va  2 s .  co m*/
    accessed();
    switch (action) {

    case "createNode": {
        service.createNode(
                json.getJsonObject("options") == null ? null
                        : new com.emikra.vertx.oak.CreateNodeOptions(json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    default: {
        throw new IllegalStateException("Invalid action: " + action);
    }
    }
}

From source file:com.emikra.vertx.orientdb.OrientDBServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
        throw new IllegalStateException("action not specified");
    }/*from   w  w w .  j  av  a  2 s  .  c om*/
    accessed();
    switch (action) {

    case "createDatabase": {
        service.createDatabase(json.getJsonObject("options") == null ? null
                : new com.emikra.vertx.orientdb.database.data.CreateDatabaseParams(
                        json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    case "createDocument": {
        service.createDocument((io.vertx.core.json.JsonObject) json.getValue("document"), createHandler(msg));
        break;
    }
    case "createVertex": {
        service.createVertex((io.vertx.core.json.JsonObject) json.getValue("vertexDoc"), createHandler(msg));
        break;
    }
    case "createEdge": {
        service.createEdge((io.vertx.core.json.JsonObject) json.getValue("edgeDoc"), createHandler(msg));
        break;
    }
    case "createClass": {
        service.createClass(
                json.getJsonObject("params") == null ? null
                        : new com.emikra.vertx.orientdb.CreateClassParams(json.getJsonObject("params")),
                createHandler(msg));
        break;
    }
    case "getDocument": {
        service.getDocument((io.vertx.core.json.JsonObject) json.getValue("docQuery"), createHandler(msg));
        break;
    }
    case "getVertex": {
        service.getVertex((io.vertx.core.json.JsonObject) json.getValue("vertexQuery"), createHandler(msg));
        break;
    }
    case "getEdge": {
        service.getEdge((io.vertx.core.json.JsonObject) json.getValue("edgeQuery"), createHandler(msg));
        break;
    }
    default: {
        throw new IllegalStateException("Invalid action: " + action);
    }
    }
}

From source file:com.englishtown.vertx.elasticsearch.ElasticSearchAdminServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {/*from   www.j  a v a  2s  .  co m*/
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {

        case "putMapping": {
            service.putMapping(convertList(json.getJsonArray("indices").getList()),
                    (java.lang.String) json.getValue("type"),
                    (io.vertx.core.json.JsonObject) json.getValue("source"),
                    json.getJsonObject("options") == null ? null
                            : new com.englishtown.vertx.elasticsearch.MappingOptions(
                                    json.getJsonObject("options")),
                    createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.englishtown.vertx.elasticsearch.ElasticSearchServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
        throw new IllegalStateException("action not specified");
    }/*  w  ww .jav a 2s.  co  m*/
    accessed();
    switch (action) {

    case "start": {
        service.start();
        break;
    }
    case "stop": {
        service.stop();
        break;
    }
    case "index": {
        service.index((java.lang.String) json.getValue("index"), (java.lang.String) json.getValue("type"),
                (io.vertx.core.json.JsonObject) json.getValue("source"),
                json.getJsonObject("options") == null ? null
                        : new com.englishtown.vertx.elasticsearch.IndexOptions(json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    case "update": {
        service.update((java.lang.String) json.getValue("index"), (java.lang.String) json.getValue("type"),
                (java.lang.String) json.getValue("id"),
                json.getJsonObject("options") == null ? null
                        : new com.englishtown.vertx.elasticsearch.UpdateOptions(json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    case "get": {
        service.get((java.lang.String) json.getValue("index"), (java.lang.String) json.getValue("type"),
                (java.lang.String) json.getValue("id"),
                json.getJsonObject("options") == null ? null
                        : new com.englishtown.vertx.elasticsearch.GetOptions(json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    case "search": {
        service.search(convertList(json.getJsonArray("indices").getList()),
                json.getJsonObject("options") == null ? null
                        : new com.englishtown.vertx.elasticsearch.SearchOptions(json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    case "searchScroll": {
        service.searchScroll((java.lang.String) json.getValue("scrollId"), json.getJsonObject("options") == null
                ? null
                : new com.englishtown.vertx.elasticsearch.SearchScrollOptions(json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    case "delete": {
        service.delete((java.lang.String) json.getValue("index"), (java.lang.String) json.getValue("type"),
                (java.lang.String) json.getValue("id"),
                json.getJsonObject("options") == null ? null
                        : new com.englishtown.vertx.elasticsearch.DeleteOptions(json.getJsonObject("options")),
                createHandler(msg));
        break;
    }
    default: {
        throw new IllegalStateException("Invalid action: " + action);
    }
    }
}

From source file:com.englishtown.vertx.mail.MailServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {/*from  w  w  w.  jav a 2  s  . c om*/
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {

        case "start": {
            service.start();
            break;
        }
        case "stop": {
            service.stop();
            break;
        }
        case "send": {
            service.send(
                    json.getJsonObject("options") == null ? null
                            : new com.englishtown.vertx.mail.SendOptions(json.getJsonObject("options")),
                    createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.englishtown.vertx.solr.SolrServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {// w ww  . j a  v a  2 s  .  c  o m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {

        case "start": {
            service.start();
            break;
        }
        case "stop": {
            service.stop();
            break;
        }
        case "query": {
            service.query((io.vertx.core.json.JsonObject) json.getValue("query"),
                    json.getJsonObject("options") == null ? null
                            : new com.englishtown.vertx.solr.QueryOptions(json.getJsonObject("options")),
                    createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.fail(-1, t.getMessage());
        throw t;
    }
}