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

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

Introduction

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

Prototype

public String getString(String key) 

Source Link

Document

Get the string value with the specified key, special cases are addressed for extended JSON types Instant , byte[] and Enum which can be converted to String.

Usage

From source file:io.nonobot.core.chat.impl.ChatRouterImpl.java

License:Apache License

private void handle(io.vertx.core.eventbus.Message<JsonObject> message) {
    JsonObject body = message.body();
    boolean respond = body.getBoolean("respond");
    String content = body.getString("content");
    String replyAddress = body.getString("replyAddress");
    String chatId = body.getString("chatId");
    for (MessageHandlerImpl handler : messageHandlers) {
        if (handler.respond == respond) {
            Matcher matcher = handler.pattern.matcher(content);
            if (matcher.matches()) {
                handler.handler.handle(new Message() {
                    boolean replied;

                    @Override//from   w  w  w .j  a  va  2 s .c  o  m
                    public String chatId() {
                        return chatId;
                    }

                    @Override
                    public String body() {
                        return content;
                    }

                    @Override
                    public String matchedGroup(int index) {
                        if (index > 0 && index <= matcher.groupCount()) {
                            return matcher.group(index);
                        } else {
                            return null;
                        }
                    }

                    @Override
                    public void reply(String msg) {
                        reply(msg, null);
                    }

                    @Override
                    public void reply(String msg, Handler<AsyncResult<Void>> ackHandler) {
                        reply(msg, DeliveryOptions.DEFAULT_TIMEOUT, ackHandler);
                    }

                    @Override
                    public void reply(String msg, long ackTimeout, Handler<AsyncResult<Void>> ackHandler) {
                        if (!replied) {
                            replied = true;
                            if (ackHandler != null) {
                                vertx.eventBus().send(replyAddress, msg,
                                        new DeliveryOptions().setSendTimeout(ackTimeout), ack -> {
                                            if (ack.succeeded()) {
                                                ackHandler.handle(Future.succeededFuture());
                                            } else {
                                                ackHandler.handle(Future.failedFuture(ack.cause()));
                                            }
                                        });
                            } else {
                                vertx.eventBus().send(replyAddress, msg);
                            }
                        } else if (ackHandler != null) {
                            ackHandler.handle(Future.failedFuture("Already replied"));
                        }
                    }
                });
                return;
            }
        }
    }
    message.reply(null);
}

From source file:io.nonobot.core.handlers.GitHubVerticle.java

License:Apache License

@Override
public void start() throws Exception {
    super.start();
    Router router = Router.router(vertx);
    bot.webRouter().mountSubRouter("/github", router);
    router.post().handler(ctx -> {/*w w w. ja  v a  2s. c om*/
        HttpServerRequest req = ctx.request();
        String event = req.getHeader("X-Github-Event");
        if (!"push".equals(event)) {
            req.response().setStatusCode(400).end("X-Github-Event " + event + " not handled");
            return;
        }
        String contentType = req.getHeader("Content-Type");
        if (!"application/json".equals(contentType)) {
            req.response().setStatusCode(400).end("Content-Type " + contentType + " not handled");
            return;
        }
        req.bodyHandler(body -> {
            JsonObject json = body.toJsonObject();
            req.response().end();
            String chatId = req.getParam("chat");
            JsonArray commits = json.getJsonArray("commits");
            if (chatId != null && commits != null && commits.size() > 0) {
                String commitWord = commits.size() > 1 ? "commits" : "commit";
                bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                        "Got " + commits.size() + " new " + commitWord + " from "
                                + json.getJsonObject("pusher").getString("name") + " on "
                                + json.getJsonObject("repository").getString("full_name"));
                for (int index = 0; index < commits.size(); index++) {
                    JsonObject commit = commits.getJsonObject(index);
                    bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                            "  * " + commit.getString("message") + " " + commit.getString("url"));
                }
            }
        });
    });
}

From source file:io.openshift.booster.service.impl.JdbcProductStore.java

License:Apache License

@Override
public Single<JsonObject> create(JsonObject item) {
    if (item == null) {
        return Single.error(new IllegalArgumentException("The item must not be null"));
    }/*from  www. j a  v  a 2 s. co  m*/
    if (item.getString("name") == null || item.getString("name").isEmpty()) {
        return Single.error(new IllegalArgumentException("The name must not be null or empty"));
    }
    if (item.getInteger("stock", 0) < 0) {
        return Single.error(new IllegalArgumentException("The stock must greater or equal to 0"));
    }
    if (item.containsKey("id")) {
        return Single.error(new IllegalArgumentException("The created item already contains an 'id'"));
    }

    return db.rxGetConnection().flatMap(conn -> {
        JsonArray params = new JsonArray().add(item.getValue("name")).add(item.getValue("stock", 0));
        return conn.rxUpdateWithParams(INSERT, params).map(ur -> item.put("id", ur.getKeys().getLong(0)))
                .doAfterTerminate(conn::close);
    });
}

From source file:io.openshift.booster.service.impl.JdbcProductStore.java

License:Apache License

@Override
public Completable update(long id, JsonObject item) {
    if (item == null) {
        return Completable.error(new IllegalArgumentException("The item must not be null"));
    }/*from   ww w .  j  a  v  a2 s .c o m*/
    if (item.getString("name") == null || item.getString("name").isEmpty()) {
        return Completable.error(new IllegalArgumentException("The name must not be null or empty"));
    }
    if (item.getInteger("stock", 0) < 0) {
        return Completable.error(new IllegalArgumentException("The stock must greater or equal to 0"));
    }
    if (item.containsKey("id") && id != item.getInteger("id")) {
        return Completable.error(new IllegalArgumentException("The 'id' cannot be changed"));
    }

    return db.rxGetConnection().flatMapCompletable(conn -> {
        JsonArray params = new JsonArray().add(item.getValue("name")).add(item.getValue("stock", 0)).add(id);
        return conn.rxUpdateWithParams(UPDATE, params).flatMapCompletable(up -> {
            if (up.getUpdated() == 0) {
                return Completable.error(new NoSuchElementException("Unknown item '" + id + "'"));
            }
            return Completable.complete();
        }).doAfterTerminate(conn::close);
    });
}

From source file:io.rhiot.kafka.bridge.JsonMessageConverter.java

License:Apache License

@Override
public Message toAmqpMessage(String amqpAddress, ConsumerRecord<String, byte[]> record) {

    Message message = Proton.message();/*from   w  w  w .  ja  v a  2s . co m*/
    message.setAddress(amqpAddress);

    // get the root JSON
    JsonObject json = new JsonObject(new String(record.value()));

    // get AMQP properties from the JSON
    JsonObject jsonProperties = json.getJsonObject(JsonMessageConverter.PROPERTIES);
    if (jsonProperties != null) {

        for (Entry<String, Object> entry : jsonProperties) {

            if (entry.getValue() != null) {

                if (entry.getKey().equals(JsonMessageConverter.MESSAGE_ID)) {
                    message.setMessageId(entry.getValue());
                } else if (entry.getKey().equals(JsonMessageConverter.TO)) {
                    message.setAddress(entry.getValue().toString());
                } else if (entry.getKey().equals(JsonMessageConverter.SUBJECT)) {
                    message.setSubject(entry.getValue().toString());
                } else if (entry.getKey().equals(JsonMessageConverter.REPLY_TO)) {
                    message.setReplyTo(entry.getValue().toString());
                } else if (entry.getKey().equals(JsonMessageConverter.CORRELATION_ID)) {
                    message.setCorrelationId(entry.getValue());
                }
            }
        }
    }

    // get AMQP application properties from the JSON
    JsonObject jsonApplicationProperties = json.getJsonObject(JsonMessageConverter.APPLICATION_PROPERTIES);
    if (jsonApplicationProperties != null) {

        Map<Symbol, Object> applicationPropertiesMap = new HashMap<>();

        for (Entry<String, Object> entry : jsonApplicationProperties) {
            applicationPropertiesMap.put(Symbol.valueOf(entry.getKey()), entry.getValue());
        }

        ApplicationProperties applicationProperties = new ApplicationProperties(applicationPropertiesMap);
        message.setApplicationProperties(applicationProperties);
    }

    // put message annotations about partition, offset and key (if not null)
    Map<Symbol, Object> messageAnnotationsMap = new HashMap<>();
    messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_PARTITION_ANNOTATION), record.partition());
    messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_OFFSET_ANNOTATION), record.offset());
    if (record.key() != null)
        messageAnnotationsMap.put(Symbol.valueOf(Bridge.AMQP_KEY_ANNOTATION), record.key());

    // get AMQP message annotations from the JSON
    JsonObject jsonMessageAnnotations = json.getJsonObject(JsonMessageConverter.MESSAGE_ANNOTATIONS);
    if (jsonMessageAnnotations != null) {

        for (Entry<String, Object> entry : jsonMessageAnnotations) {
            messageAnnotationsMap.put(Symbol.valueOf(entry.getKey()), entry.getValue());
        }
    }

    MessageAnnotations messageAnnotations = new MessageAnnotations(messageAnnotationsMap);
    message.setMessageAnnotations(messageAnnotations);

    // get the AMQP message body from the JSON
    JsonObject jsonBody = json.getJsonObject(JsonMessageConverter.BODY);

    if (jsonBody != null) {

        // type attribtute for following sectin : AMQP value or raw data/binary
        String type = jsonBody.getString(JsonMessageConverter.SECTION_TYPE);

        if (type.equals(JsonMessageConverter.SECTION_AMQP_VALUE_TYPE)) {

            // section is an AMQP value
            Object jsonSection = jsonBody.getValue(JsonMessageConverter.SECTION);

            // encoded as String
            if (jsonSection instanceof String) {
                message.setBody(new AmqpValue(jsonSection));
                // encoded as an array/List
            } else if (jsonSection instanceof JsonArray) {
                JsonArray jsonArray = (JsonArray) jsonSection;
                message.setBody(new AmqpValue(jsonArray.getList()));
                // encoded as a Map
            } else if (jsonSection instanceof JsonObject) {
                JsonObject jsonObject = (JsonObject) jsonSection;
                message.setBody(new AmqpValue(jsonObject.getMap()));
            }

        } else if (type.equals(JsonMessageConverter.SECTION_DATA_TYPE)) {

            // section is a raw binary data

            // get the section from the JSON (it's base64 encoded)
            byte[] value = jsonBody.getBinary(JsonMessageConverter.SECTION);

            message.setBody(new Data(new Binary(Base64.getDecoder().decode(value))));
        }
    }

    return message;
}

From source file:io.sqp.proxy.vertx.VertxBackendConnectionPool.java

License:Open Source License

private void loadConfigurations(JsonArray backendConfs) throws ConfigurationException {
    // first validate the configuration object
    if (backendConfs == null || backendConfs.isEmpty()) {
        throw new ConfigurationException("No backend was configured.");
    }/*from  w  w  w.j  a va2 s .c  o m*/
    if (backendConfs.size() > 1) {
        logger.log(Level.WARNING,
                "Only one backend configuration is supported at the moment. The rest is ignored.");
    }
    JsonObject firstConf = backendConfs.getJsonObject(0);
    if (firstConf == null) {
        throwInvalidConfiguration("It's not a valid JSON object.");
    }

    // Every backend needs a specific 'config' configuration map
    JsonObject backendSpecificConf = firstConf.getJsonObject("config");
    if (backendSpecificConf == null) {
        throwInvalidConfiguration("Backend specific configuration is missing.");
    }
    _backendSpecificConfiguration = backendSpecificConf.getMap();

    // The 'type' defines the subclass of BackendConnection that is the heart of the backend
    String backendType = firstConf.getString("type");
    if (backendType == null) {
        throwInvalidConfiguration("No type specified.");
    }
    // Get the class from the class loader and verify it's a subclass of BackendConnection
    Class<?> uncastedBackendClass = null;
    try {
        uncastedBackendClass = Class.forName(backendType);
    } catch (ClassNotFoundException e) {
        throwInvalidConfiguration("Class '" + backendType + "' specified as 'type' was not found.");
    }
    try {
        _backendClass = uncastedBackendClass.asSubclass(Backend.class);
    } catch (ClassCastException e) {
        throwInvalidConfiguration("Class '" + backendType + "' is not a valid Backend implementation.");
    }
}

From source file:io.techcode.logbulk.pipeline.input.SyslogInput.java

License:Open Source License

@Override
protected void onStart() {
    // Setup mapping
    JsonObject map = config.getJsonObject(CONF_MAPPING, new JsonObject());
    mapping = Maps.newEnumMap(SyslogHeader.class);
    for (String entry : map.fieldNames()) {
        mapping.put(SyslogHeader.byName(entry), map.getString(entry));
    }/*from   www .  ja  v  a2s  . com*/
    skipStructuredData = config.getBoolean("skipStructuredData", false);
}

From source file:io.techcode.logbulk.pipeline.input.SyslogInput.java

License:Open Source License

@Override
protected void checkConfig(JsonObject config) {
    checkState(config.getString("dispatch") != null, "The dispatch is required");
    checkState(config.getInteger("port") != null, "The port is required");
}

From source file:io.techcode.logbulk.pipeline.output.SyslogOutput.java

License:Open Source License

@Override
public void onStart() {
    // Setup mapping
    JsonObject map = config.getJsonObject(CONF_MAPPING, new JsonObject());
    mapping = Maps.newEnumMap(SyslogHeader.class);
    for (String entry : map.fieldNames()) {
        mapping.put(SyslogHeader.byName(entry), map.getString(entry));
    }/*from  w w  w  .j  a  v a 2s .  co  m*/

    // Setup framing
    String framing = config.getString(CONF_FRAMING);
    if ("delimited".equals(framing)) {
        delimiter = config.getString(CONF_DELIMITER);
    }
}

From source file:io.techcode.logbulk.pipeline.output.SyslogOutput.java

License:Open Source License

@Override
protected void checkConfig(JsonObject config) {
    super.checkConfig(config);
    checkState(validFraming(config.getString(CONF_FRAMING)), "The framing is required");
    if ("delimited".equals(config.getString(CONF_FRAMING))) {
        checkState(!Strings.isNullOrEmpty(config.getString(CONF_DELIMITER)), "The delimiter is required");
    }/*from  ww  w .j  a  v  a2  s. c o m*/
}