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

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

Introduction

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

Prototype

public JsonObject put(String key, Object value) 

Source Link

Document

Put an Object into the JSON object with the specified key.

Usage

From source file:com.appdocker.iop.InternetOfPeopleServiceVertxEBProxy.java

License:Apache License

public void hello(String message, Handler<AsyncResult<String>> resultHandler) {
    if (closed) {
        resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
        return;/*from  w w  w.j  a  va  2  s .  co  m*/
    }
    JsonObject _json = new JsonObject();
    _json.put("message", message);
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options)
            : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "hello");
    _vertx.eventBus().<String>send(_address, _json, _deliveryOptions, res -> {
        if (res.failed()) {
            resultHandler.handle(Future.failedFuture(res.cause()));
        } else {
            resultHandler.handle(Future.succeededFuture(res.result().body()));
        }
    });
}

From source file:com.baldmountain.depot.models.BaseModel.java

License:Open Source License

void setDates(JsonObject json) {
    json.put("createdOn", dateFormat.format(createdOn));
    setUpdatedOn();/*from ww w .  jav a 2 s .  c  om*/
    if (updatedOn != null) {
        json.put("updatedOn", dateFormat.format(updatedOn));
    } else {
        json.put("updatedOn", "");
    }
}

From source file:com.chibchasoft.vertx.verticle.deployment.DependentsDeployment.java

License:Open Source License

/**
 * Returns a JsonObject populated with the information from this object
 * @return The JsonObject/*  w  ww .ja v a2  s . c o  m*/
 */
public JsonObject toJson() {
    JsonObject json = new JsonObject();
    if (this.getConfigurations() != null) {
        JsonArray array = new JsonArray();
        this.getConfigurations().forEach(item -> array.add(item.toJson()));
        json.put("configurations", array);
    }
    return json;
}

From source file:com.chibchasoft.vertx.verticle.deployment.DeploymentConfiguration.java

License:Open Source License

/**
 * Returns a JsonObject populated with the information from this object
 * @return The JsonObject//from ww  w  .  j ava2s  .co m
 */
public JsonObject toJson() {
    JsonObject json = new JsonObject();
    json.put("name", name);
    if (deploymentOptions != null) {
        JsonObject depOptJson = new JsonObject();
        DeploymentOptionsConverter.toJson(deploymentOptions, depOptJson);
        json.put("deploymentOptions", depOptJson);
    }
    if (this.getDependents() != null) {
        JsonArray array = new JsonArray();
        this.getDependents().forEach(item -> array.add(item.toJson()));
        json.put("dependents", array);
    }
    return json;
}

From source file:com.company.vertxstarter.MainVerticle.java

@Override
public void start(Future<Void> fut) {
    // Create a router object.
    Router router = Router.router(vertx);
    //CORS handler
    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.OPTIONS).allowedHeader("Content-Type").allowedHeader("Accept"));

    //default headers
    router.route().handler(ctx -> {/*from w w  w .ja  va2  s. co  m*/
        ctx.response().putHeader("Cache-Control", "no-store, no-cache").putHeader("Content-Type",
                "application/json");

        if (StringUtils.isEmpty(ctx.request().getHeader("Accept"))) {
            ctx.fail(Failure.NO_MEDIA_TYPE);
            return;
        } else if (!"application/json".equalsIgnoreCase(ctx.request().getHeader("Accept"))) {
            ctx.fail(Failure.UNSUPPORTED_MEDIA_TYPE);
            return;
        }
        ctx.next();
    });

    //error handling
    router.route().failureHandler(ctx -> {
        HttpServerResponse response = ctx.response();
        final JsonObject error = new JsonObject();
        Failure ex;

        if (ctx.failure() instanceof Failure) { //specific error
            ex = (Failure) ctx.failure();
        } else { //general error
            ctx.failure().printStackTrace();
            ex = Failure.INTERNAL_ERROR;
        }
        error.put("message", ex.getMessage());
        response.setStatusCode(ex.getCode()).end(error.encode());
    });
    //default 404 handling
    router.route().last().handler(ctx -> {
        HttpServerResponse response = ctx.response();
        final JsonObject error = new JsonObject();
        error.put("message", Failure.NOT_FOUND.getMessage());
        response.setStatusCode(404).end(error.encode());
    });

    //routes
    Injector injector = Guice.createInjector(new AppInjector());
    router.route(HttpMethod.GET, "/people").handler(injector.getInstance(PersonResource.class)::get);

    // Create the HTTP server and pass the "accept" method to the request handler.
    HttpServerOptions serverOptions = new HttpServerOptions();
    serverOptions.setCompressionSupported(true);
    vertx.createHttpServer(serverOptions).requestHandler(router::accept)
            .listen(config().getInteger("http.port", 8080), result -> {
                if (result.succeeded()) {
                    fut.complete();
                } else {
                    fut.fail(result.cause());
                }
            });
}

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

License:Apache License

/**
 * Get the object as a vertx JsonOBject/*from   ww  w .j  a  v a 2 s  . c o  m*/
 *
 * @return the metric data in Json form
 */
public JsonObject asJson() {
    JsonObject obj = new JsonObject().put(METRIC_FIELD, metric).put(VALUE_FIELD, value).put(TIMESTAMP_FIELD,
            timestamp);

    JsonObject tagsObj = new JsonObject();
    for (String key : tags.fieldNames()) {
        tagsObj.put(key, tags.getValue(key));
    }

    // there has to be at least one tag
    obj.put(TAGS_FIELD, tagsObj);
    return obj;
}

From source file:com.cyngn.vertx.opentsdb.client.TsMetric.java

License:Apache License

/**
 * Convert this object to a metric JsonObject suitable for transferring via the EventBus.
 *
 * @return the TsMetric in JsonObject form
 *///from   w  ww. j  a v a2s  .c om
public JsonObject asJson() {
    JsonObject jsonObject = new JsonObject().put(MetricsParser.NAME_FIELD, name).put(MetricsParser.VALUE_FIELD,
            value);

    if (tags != null && tags.size() > 0) {
        JsonObject tagMap = new JsonObject();
        for (Map.Entry<String, String> entry : tags.entrySet()) {
            tagMap.put(entry.getKey(), entry.getValue());
        }

        jsonObject.put(MetricsParser.TAGS_FIELD, tagMap);
    }

    return jsonObject;
}

From source file:com.cyngn.vertx.opentsdb.Util.java

License:Apache License

/**
 * Create a metric object for sending to the OpenTsDb lib
 *
 * @param name the metric name//  w  w w.ja v a  2s .c o  m
 * @param value the metric value
 * @param tags the tags to associate to this metric
 * @return the properly constructed metric object
 */
public static JsonObject createMetric(String name, String value, JsonObject tags) {
    JsonObject obj = new JsonObject().put(OpenTsDbService.ACTION_FIELD, OpenTsDbService.ADD_COMMAND)
            .put(MetricsParser.NAME_FIELD, name).put(MetricsParser.VALUE_FIELD, value);
    if (tags != null && tags.size() > 0) {
        obj.put(MetricsParser.TAGS_FIELD, tags);
    }
    return obj;
}

From source file:com.cyngn.vertx.opentsdb.Util.java

License:Apache License

/**
 * Create a metric object for sending to the OpenTsDb lib but with no implicit command
 *
 * @param name the metric name/*from ww w .  j  av a2s .co  m*/
 * @param value the metric value
 * @param tags the tags to associate to this metric
 * @return the properly constructed metric object
 */
public static JsonObject createRawMetric(String name, String value, JsonObject tags) {
    JsonObject obj = new JsonObject().put(MetricsParser.NAME_FIELD, name).put(MetricsParser.VALUE_FIELD, value);
    if (tags != null && tags.size() > 0) {
        obj.put(MetricsParser.TAGS_FIELD, tags);
    }
    return obj;
}

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

License:Apache License

/**
 * Start the verticle//ww  w .  jav  a 2s .co  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();

}