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

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

Introduction

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

Prototype

public JsonObject(Buffer buf) 

Source Link

Document

Create an instance from a buffer.

Usage

From source file:RestAPI.java

private void handleAddProduct(RoutingContext routingContext) {

    JsonObject project = new JsonObject(routingContext.getBodyAsString());

    project.getString("name");
    project.getString("board");
    project.getString("ic");
    project.getString("detail");
    project.getString("visibility");
    //        System.out.println("from post "+routingContext.getBodyAsString());
    //        String productID = routingContext.request().getParam("productID");
    HttpServerResponse response = routingContext.response();
    //        if (productID == null) {
    //            sendError(400, response);
    //        } else {
    //            JsonObject product = routingContext.getBodyAsJson();
    //            if (product == null) {
    //                sendError(400, response);
    //            } else {
    //                products.put(productID, product);
    response.end();/*from ww w .ja  v a 2 s .c  o  m*/
    //            }
    //        }
}

From source file:DbHelper.java

public JsonObject openProject(String userName, String projectName) {
    String project = "{\n" + "    \"id\": 234,\n" + "    \"name\": \"nama project\",\n"
            + "    \"detail\": \" detail of project\",\n" + "    \"config\": {\n"
            + "        \"arduinoType\": \"arduino uno\",\n" + "        \"icType\": \"atmega 328p\",\n"
            + "        \"acessbility\": \"private|public|friend\",\n" + "        \"port\": \"com3\"\n"
            + "    },\n" + "    \"sourceCode\": {\n" + "        \"folders\": [\n" + "            {\n"
            + "                \"name\": \"name folder\",\n" + "                \"id\": 345,\n"
            + "                \"dateModified\": \"11-feb-2014\",\n"
            + "                \"dateCreated\": \"11-feb-2014\",\n"
            + "                \"modifiedBy\": \"userId\",\n" + "                \"files\": [\n"
            + "                    {\n" + "                        \"name\": \"file4.c\",\n"
            + "                        \"id\": 4,\n"
            + "                        \"dateModified\": \"11-feb-2014\",\n"
            + "                        \"dateCreated\": \"11-feb-2014\",\n"
            + "                        \"modifiedBy\": \"userId\"\n" + "                    },\n"
            + "                    {\n" + "                        \"name\": \"file3.c\",\n"
            + "                        \"id\": 3,\n"
            + "                        \"dateModified\": \"11-feb-2014\",\n"
            + "                        \"dateCreated\": \"11-feb-2014\",\n"
            + "                        \"modifiedBy\": \"userId\"\n" + "                    }\n"
            + "                ]\n" + "            }\n" + "        ],\n" + "        \"files\": [\n"
            + "            {\n" + "                \"name\": \"file1.c\",\n" + "                \"id\": 1,\n"
            + "                \"dateModified\": \"11-feb-2014\",\n"
            + "                \"dateCreated\": \"11-feb-2014\",\n"
            + "                \"modifiedBy\": \"userId\"\n" + "            },\n" + "            {\n"
            + "                \"name\": \"file2.c\",\n" + "                \"id\": 2,\n"
            + "                \"dateModified\": \"11-feb-2014\",\n"
            + "                \"dateCreated\": \"11-feb-2014\",\n"
            + "                \"modifiedBy\": \"userId\"\n" + "            }\n" + "        ]\n" + "    }\n"
            + "}\n" + "";

    return new JsonObject(project);
}

From source file:DbHelper.java

public JsonObject getProject(String userName, String projectName) {
    String returnDummy = "{\n" + "    \"project\":\n" + "            {\n"
            + "                \"name\": \"blinking\",\n"
            + "                \"create_date\": \"11-feb-2014\",\n"
            + "                \"modify_date\": \"11-feb-2014\",\n"
            + "                \"detail\": \"some detail\",\n" + "                \"visibility\": \"public\",\n"
            + "                \"visibility\": \"public\",\n"
            + "                \"arduino_type\": \"arduino uno\",\n"
            + "                \"arduino_IC\": \"atmega 328\"\n" + "            },\n"
            + "    \"project_structure\":\n" + "            {\n" + "                \"folders\": [\n"
            + "                    {\n" + "                        \"name\": \"lib\",\n"
            + "                        \"create_date\": \"11-feb-2014\",\n"
            + "                        \"modify_date\": \"11-feb-2014\",\n"
            + "                        \"files\": [\n" + "                            {\n"
            + "                                \"name\": \"lcd.c\",\n"
            + "                                \"source\": \"text of source\",\n"
            + "                                \"create_date\": \"11-feb-2014\",\n"
            + "                                \"modify_date\": \"11-feb-2014\"\n"
            + "                            },\n" + "                            {\n"
            + "                                \"name\": \"lcd.h\",\n"
            + "                                \"source\": \"text of source\",\n"
            + "                                \"create_date\": \"11-feb-2014\",\n"
            + "                                \"modify_date\": \"11-feb-2014\"\n"
            + "                            },\n" + "                            {\n"
            + "                                \"name\": \"dht.c\",\n"
            + "                                \"source\": \"text of source\",\n"
            + "                                \"create_date\": \"11-feb-2014\",\n"
            + "                                \"modify_date\": \"11-feb-2014\"\n"
            + "                            },\n" + "                            {\n"
            + "                                \"name\": \"dht.h\",\n"
            + "                                \"source\": \"text of source\",\n"
            + "                                \"create_date\": \"11-feb-2014\",\n"
            + "                                \"modify_date\": \"11-feb-2014\"\n"
            + "                            }\n" + "                        ]\n" + "\n"
            + "                    }\n" + "                ],\n" + "                \"files\": [\n"
            + "                    {\n" + "                        \"name\": \"lcd.c\",\n"
            + "                        \"source\": \"text of source\",\n"
            + "                        \"create_date\": \"11-feb-2014\",\n"
            + "                        \"modify_date\": \"11-feb-2014\"\n" + "                    },\n"
            + "                    {\n" + "                        \"name\": \"lcd.h\",\n"
            + "                        \"source\": \"text of source\",\n"
            + "                        \"create_date\": \"11-feb-2014\",\n"
            + "                        \"modify_date\": \"11-feb-2014\"\n" + "                    },\n"
            + "                    {\n" + "                        \"name\": \"dht.c\",\n"
            + "                        \"source\": \"text of source\",\n"
            + "                        \"create_date\": \"11-feb-2014\",\n"
            + "                        \"modify_date\": \"11-feb-2014\"\n" + "                    },\n"
            + "                    {\n" + "                        \"name\": \"dht.h\",\n"
            + "                        \"source\": \"text of source\",\n"
            + "                        \"create_date\": \"11-feb-2014\",\n"
            + "                        \"modify_date\": \"11-feb-2014\"\n" + "                    }\n"
            + "                ]\n" + "            }\n" + "}\n" + "\n" + "";
    return new JsonObject(returnDummy);
}

From source file:cm.study.vertx.database.WikiDatabaseServiceVertxEBProxy.java

License:Apache License

private <T> Map<String, T> convertMap(Map map) {
    if (map.isEmpty()) {
        return (Map<String, T>) map;
    }//from   w ww . ja v a 2  s .  c  o  m

    Object elem = map.values().stream().findFirst().get();
    if (!(elem instanceof Map) && !(elem instanceof List)) {
        return (Map<String, T>) map;
    } else {
        Function<Object, T> converter;
        if (elem instanceof List) {
            converter = object -> (T) new JsonArray((List) object);
        } else {
            converter = object -> (T) new JsonObject((Map) object);
        }
        return ((Map<String, T>) map).entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, converter::apply));
    }
}

From source file:cm.study.vertx.database.WikiDatabaseServiceVertxEBProxy.java

License:Apache License

private <T> List<T> convertList(List list) {
    if (list.isEmpty()) {
        return (List<T>) list;
    }/*from w  ww  .  j  a v a 2 s.c  o m*/

    Object elem = list.get(0);
    if (!(elem instanceof Map) && !(elem instanceof List)) {
        return (List<T>) list;
    } else {
        Function<Object, T> converter;
        if (elem instanceof List) {
            converter = object -> (T) new JsonArray((List) object);
        } else {
            converter = object -> (T) new JsonObject((Map) object);
        }
        return (List<T>) list.stream().map(converter).collect(Collectors.toList());
    }
}

From source file:co.runrightfast.core.utils.JsonUtils.java

License:Apache License

static JsonObject toVertxJsonObject(@NonNull final javax.json.JsonObject json) {
    return new JsonObject(json.toString());
}

From source file:com.camelcookbook.runtimes.vertx.HttpVerticle.java

License:Apache License

@Override
public void start(Future<Void> startFuture) throws Exception {

    Router router = Router.router(vertx);
    router.route("/greetings/:name").handler(routingContext -> {
        HttpServerResponse response = routingContext.response();
        Map<String, Object> values = new HashMap<>();
        values.put("name", routingContext.request().params().get("name"));
        values.put("increment", 1);

        // publish a message that we got a new counter to anyone listening
        // on the eventbus ... the eventbus is our bridge to Camel
        vertx.eventBus().publish("greetings-counter", new JsonObject(values));

        response.putHeader("content-type", "text/html").end("<h1>Hello from vertx</h1>");
    });// www .j  av  a2  s.  c om

    int port = config().getInteger("http.port", 8080);

    vertx.createHttpServer().requestHandler(router::accept).listen(port, result -> {
        if (result.succeeded()) {
            startFuture.complete();
        } else {
            startFuture.fail(result.cause());
        }
    });
}

From source file:com.deblox.auth.AuthVerticle.java

License:Apache License

/**
 * Start the verticle//from   w ww. ja  v a 2  s.c o  m
 *
 * @param startFuture
 * @throws Exception
 */
public void start(Future<Void> startFuture) throws Exception {

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

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

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

    // listen for release events from other verticles / clients
    eb.consumer("auth-request", 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"));
        }

        // call some auth mechanism

        // create some profile
        JsonObject profile = new JsonObject().put("date", new Date());

        // create a uuid
        String uuid = UUID.randomUUID().toString();

        // put the updated one
        sessionData.put(uuid, profile);

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

    });

    startFuture.complete();

}

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

License:Apache License

/**
 * Start the verticle/*from  www.j a v  a  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. ja va  2  s .com*/

                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();
}