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

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

Introduction

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

Prototype

public String encode() 

Source Link

Document

Encode this JSON object as a string.

Usage

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

License:Apache License

static javax.json.JsonObject toJsonObject(@NonNull final JsonObject json) {
    try (final JsonReader reader = Json.createReader(new StringReader(json.encode()))) {
        return reader.readObject();
    }//ww  w.  j a v a2s  .  c  o  m
}

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 -> {// w w  w . ja v a  2  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.opentsdb.client.MetricPublisher.java

License:Apache License

/**
 * Send a metric via the event bus/* ww w .j av a2s .  com*/
 * @param message the metric data to send
 */
private void sendMetrics(JsonObject message) {
    bus.send(address, message, result -> {
        if (result.failed()) {
            logger.error(String.format("Failed to send message on event bus,  address: %s  metrics: %s",
                    address, message.encode()), result.cause());
        }
    });
}

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

License:Apache License

private void initializeWorkers(Future<Void> startedResult) {
    final AtomicInteger count = new AtomicInteger();
    processor = new MetricsProcessor(workers, options.getMaxBufferBytes(), vertx.eventBus());
    JsonArray hosts = options.getHosts();
    for (int i = 0; i < hosts.size(); i++) {
        JsonObject jsonHost = hosts.getJsonObject(i);

        // we setup one worker dedicated to each endpoint, the same worker always rights to the same outbound socket
        OpenTsDbClient worker = new OpenTsDbClient(jsonHost.getString("host"), jsonHost.getInteger("port"),
                vertx, success -> {//from  www  .jav  a2s  . c om
                    if (!success) {
                        String error = String.format("Failed to connect to host: %s", jsonHost.encode());
                        logger.error(error);
                        vertx.close();
                        startedResult.fail(error);
                        return;
                    }

                    count.incrementAndGet();
                    if (count.get() == hosts.size()) {
                        flushTimerId = vertx.setPeriodic(options.getFlushInterval(),
                                timerId -> processor.processMetrics(metrics));
                        logger.info(options);
                        startReporter();
                        startedResult.complete();
                    }
                });
        workers.add(worker);
    }
}

From source file:com.dinstone.example.HelloResource.java

License:Apache License

@Get("/g/:name")
public void hello(@Context RoutingContext ctx) {
    String message = "hello";
    String name = ctx.request().getParam("name");
    if (name != null) {
        message += " " + name;
    }//from  w  ww  .  jav  a  2 s  .  c  o m

    JsonObject json = new JsonObject().put("message", message);
    ctx.response().end(json.encode());
}

From source file:com.dinstone.vertx.web.resource.HelloResourceSubclass.java

License:Apache License

public void hello(RoutingContext ctx) {
    String message = "hello";
    String name = ctx.request().getParam("name");
    if (name != null) {
        message += " " + name;
    }/*from w w  w. j  av  a2s . co  m*/

    JsonObject json = new JsonObject().put("message", message);
    ctx.response().end(json.encode());
}

From source file:com.github.ithildir.numbers.game.util.ConversationUtil.java

License:Open Source License

public static void ask(HttpServerResponse httpServerResponse, String conversationToken, String initialPrompt,
        String[] noInputPrompts) {

    httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
    httpServerResponse.putHeader("Google-Assistant-API-Version", "v1");

    JsonObject responseJSON = new JsonObject();

    if (conversationToken != null) {
        responseJSON.put("conversation_token", conversationToken);
    }//from   w ww.  ja  v a2 s  .  co m

    responseJSON.put("expect_user_response", true);
    responseJSON.put("expected_inputs",
            JsonUtil.getArray(_getExpectedInputJSON(initialPrompt, noInputPrompts)));

    httpServerResponse.end(responseJSON.encode());
}

From source file:com.github.ithildir.numbers.game.util.ConversationUtil.java

License:Open Source License

public static void tell(HttpServerResponse httpServerResponse, String textToSpeech) {

    httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
    httpServerResponse.putHeader("Google-Assistant-API-Version", "v1");

    JsonObject responseJSON = new JsonObject();

    JsonObject finalResponseJSON = new JsonObject();

    finalResponseJSON.put("speech_response", _getPromptJSON(textToSpeech));

    responseJSON.put("final_response", finalResponseJSON);

    httpServerResponse.end(responseJSON.encode());
}

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");
    }//from ww  w  .  jav  a 2s. 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 ww.j a  v  a2 s  . c o  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);
}