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

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

Introduction

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

Prototype

public Long getLong(String key) 

Source Link

Document

Get the Long value with the specified key

Usage

From source file:pt.davidafsilva.ushortx.http.RestVerticle.java

License:Open Source License

/**
 * Shortens an arbitrary URL specified inside the POST request
 *
 * @param context the routing context of the request
 *//*from  w w w .j  ava 2  s  . com*/
private void shortenUrlRequest(final RoutingContext context) {
    // extract the url
    final String url = protocolify(context.request().getParam("url"));
    LOGGER.info("shorten request for " + url);
    // url validation
    if (url == null || !URL_VALIDATOR.isValid(url)) {
        context.response().setStatusCode(400).end();
        return;
    }

    // send the request or fail the request
    LOGGER.debug("sending url save message for " + url);
    vertx.eventBus().send("ushortx-persistence-save",
            // the request data
            new JsonObject().put("url", url),
            // the result callback
            (AsyncResult<Message<JsonObject>> result) -> {
                if (result.succeeded()) {
                    // extract the json data
                    final JsonObject json = result.result().body();
                    LOGGER.debug(url + " -> " + json);

                    // get the id
                    final long id = json.getLong("id");

                    // generate an hash for the identifier
                    final String hash = Hash.generate(config().getString("salt", DEFAULT_SALT), id);

                    // write the response
                    final String jsonResponse = new JsonObject().put("original", url).put("shortened", String
                            .format(URL_REDIRECT_FORMAT, context.request().localAddress().toString(), hash))
                            .encode();
                    context.response().setStatusCode(200).putHeader("Content-Type", "application/json")
                            .end(jsonResponse);
                } else {
                    LOGGER.error("unable to save url", result.cause());
                    // fail with an internal error
                    context.response().setStatusCode(500).end();
                }
            });
}