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

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

Introduction

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

Prototype

public Object getValue(String key) 

Source Link

Document

Get the value with the specified key, as an Object with types respecting the limitations of JSON.

Usage

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 ww  w . j  a  v a  2 s .  c  o 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.silverware.microservices.providers.cdi.internal.RestInterface.java

License:Apache License

@SuppressWarnings("checkstyle:JavadocMethod")
public void callMethod(final RoutingContext routingContext) {
    final String microserviceName = routingContext.request().getParam("microservice");
    final String methodName = routingContext.request().getParam("method");
    final Bean bean = gatewayRegistry.get(microserviceName);

    routingContext.request().bodyHandler(buffer -> {
        final JsonObject mainJsonObject = new JsonObject(buffer.toString());

        try {//from   w w  w . j  ava  2 s  .  com
            final Class<?> beanClass = bean.getBeanClass();
            List<Method> methods = Arrays.asList(beanClass.getDeclaredMethods()).stream()
                    .filter(method -> method.getName().equals(methodName)
                            && method.getParameterCount() == mainJsonObject.size())
                    .collect(Collectors.toList());

            if (methods.size() == 0) {
                throw new IllegalStateException(
                        String.format("No such method %s with compatible parameters.", methodName));
            }

            if (methods.size() > 1) {
                throw new IllegalStateException("Overridden methods are not supported yet.");
            }

            final Method m = methods.get(0);

            final Parameter[] methodParams = m.getParameters();
            final Object[] paramValues = new Object[methodParams.length];
            final ConvertUtilsBean convert = new ConvertUtilsBean();
            for (int i = 0; i < methodParams.length; i++) {
                final Parameter methodParameter = methodParams[i];
                final String paramName = getParamName(methodParameter, m, beanClass);
                final Object jsonObject = mainJsonObject.getValue(paramName);
                paramValues[i] = convert.convert(jsonObject, methodParameter.getType());
            }

            @SuppressWarnings("unchecked")
            Set<Object> services = context.lookupLocalMicroservice(
                    new MicroserviceMetaData(microserviceName, beanClass, bean.getQualifiers()));
            JsonObject response = new JsonObject();
            try {
                Object result = m.invoke(services.iterator().next(), paramValues);
                response.put("result", Json.encodePrettily(result));
                response.put("resultPlain", JsonWriter.objectToJson(result));
            } catch (Exception e) {
                response.put("exception", e.toString());
                response.put("stackTrace", stackTraceAsString(e));
                log.warn("Could not call method: ", e);
            }

            routingContext.response().end(response.encodePrettily());
        } catch (Exception e) {
            log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e);
            routingContext.response().setStatusCode(503).end("Resource not available.");
        }
    });
}

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

License:Open Source License

/**
 * Populate header based on data./*from   w ww  .j a va  2  s. c o  m*/
 *
 * @param buf    buffer to write in.
 * @param header header to populate.
 * @param data   data involved.
 */
private void populate(Buffer buf, SyslogHeader header, JsonObject data) {
    String key = mapping.get(header);
    if (mapping.containsKey(header) && data.containsKey(key)) {
        buf.appendString(String.valueOf(data.getValue(key)));
        buf.appendString(" ");
    } else {
        buf.appendString("- ");
    }
}

From source file:me.escoffier.vertx.healthchecks.StatusConverter.java

License:Apache License

public static void fromJson(JsonObject json, Status obj) {
    if (json.getValue("data") instanceof JsonObject) {
        obj.setData(((JsonObject) json.getValue("data")).copy());
    }//from   w w w.  ja v  a2  s  .  c  o m
    if (json.getValue("ok") instanceof Boolean) {
        obj.setOk((Boolean) json.getValue("ok"));
    }
    if (json.getValue("procedureInError") instanceof Boolean) {
        obj.setProcedureInError((Boolean) json.getValue("procedureInError"));
    }
}

From source file:me.yoryor.app.vtodo.entity.TodoConverter.java

License:Apache License

public static void fromJson(JsonObject json, Todo obj) {
    if (json.getValue("completed") instanceof Boolean) {
        obj.setCompleted((Boolean) json.getValue("completed"));
    }//  w  w w. j a va 2 s  . c o  m
    if (json.getValue("id") instanceof String) {
        obj.setId((String) json.getValue("id"));
    }
    if (json.getValue("order") instanceof Number) {
        obj.setOrder(((Number) json.getValue("order")).intValue());
    }
    if (json.getValue("title") instanceof String) {
        obj.setTitle((String) json.getValue("title"));
    }
    if (json.getValue("url") instanceof String) {
        obj.setUrl((String) json.getValue("url"));
    }
}

From source file:microservicerx.dht.DhtMap.java

public Observable<Map.Entry<K, T>> rangeQuery(K from, K to) {
    final String address = this.prefix + ".data." + UUID.randomUUID().toString();

    BehaviorSubject<Map.Entry<K, T>> result = BehaviorSubject.create();
    AtomicLong countResponsed = new AtomicLong(0);
    AtomicReference<Runnable> checkComplete = new AtomicReference<>();

    MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer(address, (Message<JsonObject> msg) -> {
        JsonObject o = msg.body();
        result.onNext(new AbstractMap.SimpleEntry<>((K) o.getValue("k"), (T) o.getValue("v")));
        countResponsed.decrementAndGet();
        checkComplete.get().run();/*from w w w .  j av  a  2 s. c  o m*/
    });

    checkComplete.set(() -> {
        if (countResponsed.get() == 0) {
            consumer.unregister();
            result.onCompleted();
        }
    });

    this.<DhtMap<K, T>, Long>traverse(from, to, 0l, (a, b) -> Long.sum(a, b), (pair, cb) -> {
        DhtMap<K, T> node = pair.node();
        Observable.from(node.getValues().entrySet()).filter(e -> DHT.isResponsible(from, to, e.getKey()))
                .doOnNext(entry -> {
                    node.getVertx().eventBus().publish(address,
                            new JsonObject().put("k", entry.getKey()).put("v", entry.getValue()));
                }).countLong().subscribe(l -> {
                    cb.accept(l);
                }, e -> {
                    e.printStackTrace();
                });
    }).subscribe(l -> {
        long count = countResponsed.accumulateAndGet(l, (a, b) -> a + b);
        checkComplete.get().run();
    }, e -> {
        e.printStackTrace();
    });

    return result;
}

From source file:name.bpdp.vertx.blazegraph.BlazegraphServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
        throw new IllegalStateException("action not specified");
    }/*w  w w.j av  a  2 s .  c  o m*/
    accessed();
    switch (action) {

    case "save": {
        service.save((java.lang.String) json.getValue("collection"));
        break;
    }
    default: {
        throw new IllegalStateException("Invalid action: " + action);
    }
    }
}

From source file:name.bpdp.vertx.changeme.ChangemeServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
        throw new IllegalStateException("action not specified");
    }//  w  w w . ja  v a 2 s. c  o  m
    accessed();
    switch (action) {

    case "method1": {
        service.method1((java.lang.String) json.getValue("method1Arg"), createHandler(msg));
        break;
    }
    default: {
        throw new IllegalStateException("Invalid action: " + action);
    }
    }
}

From source file:org.eclipse.hono.service.credentials.BaseCredentialsService.java

License:Open Source License

private boolean containsValidSecretValue(final JsonObject credentials) {

    final Object obj = credentials.getValue(FIELD_SECRETS);

    if (JsonArray.class.isInstance(obj)) {

        JsonArray secrets = (JsonArray) obj;
        if (secrets.isEmpty()) {

            log.debug("credentials request contains empty {} object in payload - not supported", FIELD_SECRETS);
            return false;

        } else {//from ww w.j  ava  2  s .c om

            for (int i = 0; i < secrets.size(); i++) {
                JsonObject currentSecret = secrets.getJsonObject(i);
                if (!containsValidTimestampIfPresentForField(currentSecret, FIELD_SECRETS_NOT_BEFORE)
                        || !containsValidTimestampIfPresentForField(currentSecret, FIELD_SECRETS_NOT_AFTER)) {
                    log.debug("credentials request did contain invalid timestamp values in payload");
                    return false;
                }
            }

            return true;
        }

    } else {

        log.debug("credentials request does not contain a {} array in payload - not supported", FIELD_SECRETS);
        return false;

    }
}

From source file:org.eclipse.hono.service.credentials.BaseCredentialsService.java

License:Open Source License

private boolean containsStringValueForField(final JsonObject payload, final String field) {

    final Object value = payload.getValue(field);
    if (StringUtils.isEmpty(value)) {
        log.debug("credentials request did not contain string typed field {} in payload - not supported",
                field);//from  w  w  w .j  a v  a2s.c o  m
        return false;
    }

    return true;
}