List of usage examples for io.vertx.core.json JsonObject JsonObject
public JsonObject()
From source file:de.notizwerk.Producer.java
License:Open Source License
private void generateAndSend(Long id) { if (!sendingActive) { vertx.setTimer(SEND_DELAY_IN_MSEC, this::generateAndSend); return;/*ww w . j av a 2s.c o m*/ } long start = System.currentTimeMillis(); long msgsToSend = Math.max(Math.floorDiv(msgPerSec * SEND_DELAY_IN_MSEC, 1000), 1); int m = 0; while (m < msgsToSend) { JsonObject msg = new JsonObject().put("ts", System.currentTimeMillis()).put("message", "messsage " + m); this.generatedMessages++; generatedMessagesInTick++; m++; vertx.eventBus().send("consumer", msg, new DeliveryOptions().setSendTimeout(10000), reply -> { if (reply.succeeded()) { if ("ok".equalsIgnoreCase(reply.result().body().toString())) { this.sentMessages++; } else { this.undeliveredMessages++; file.write(Buffer.buffer("failed message :" + msg.getLong("ts") + ". " + reply.cause().getMessage() + String.format("%n"))); } } else { this.undeliveredMessages++; file.write(Buffer.buffer("failed message :" + msg.getLong("ts") + ". " + reply.cause().getMessage() + String.format("%n"))); } }); } ; long diff = System.currentTimeMillis() - start; long delay = Math.max(SEND_DELAY_IN_MSEC - diff, 10); vertx.setTimer(delay, this::generateAndSend); }
From source file:de.notizwerk.Producer.java
License:Open Source License
private void report(Long id) { long messageRate = Math.floorDiv(generatedMessagesInTick * 1000, REPORT_DELAY_IN_MSEC); generatedMessagesInTick = 0;/*from ww w . j ava 2 s . co m*/ JsonObject stats = new JsonObject().put("name", name).put("id", name).put("throttle", msgPerSec) .put("timestamp", AppStarter.TIME_FORMATTER.format(ZonedDateTime.now())) .put("generatedMessages", generatedMessages).put("sentMessages", sentMessages) .put("undeliveredMessages", undeliveredMessages).put("messageRate", messageRate); file.write(Buffer.buffer(stats.encode() + String.format("%n"))); vertx.eventBus().publish("producer.stats", stats); }
From source file:de.notizwerk.Producer.java
License:Open Source License
private void generateAndSendToConsumer(Long id) { if (!sendingActive || consumer.isEmpty()) { vertx.setTimer(SEND_DELAY_IN_MSEC, this::generateAndSendToConsumer); return;//from ww w. j av a2s . c om } consumer.removeIf(c -> c.online == false); if (consumer.isEmpty()) { vertx.setTimer(SEND_DELAY_IN_MSEC, this::generateAndSendToConsumer); return; } long start = System.currentTimeMillis(); long msgsToSend = Math.max(Math.floorDiv(msgPerSec * SEND_DELAY_IN_MSEC, 1000), 1); int m = 0; while (m < msgsToSend) { for (Consumer consumer : consumer) { if (consumer.online) { JsonObject msg = new JsonObject().put("ts", System.currentTimeMillis()).put("message", "messsage " + m); this.generatedMessages++; generatedMessagesInTick++; m++; vertx.eventBus().send("consumer", msg, new DeliveryOptions().setSendTimeout(10000), reply -> { if (reply.succeeded()) { if ("ok".equalsIgnoreCase(reply.result().body().toString())) { this.sentMessages++; consumer.online = true; } else { this.undeliveredMessages++; file.write(Buffer.buffer("failed message :" + msg.getLong("ts") + ". " + reply.result().body() + String.format("%n"))); } } else { this.undeliveredMessages++; file.write(Buffer.buffer("failed message :" + msg.getLong("ts") + ". " + reply.cause().getMessage() + String.format("%n"))); consumer.online = false; } }); if (m >= msgsToSend) break; } } ; } ; long diff = System.currentTimeMillis() - start; long delay = Math.max(SEND_DELAY_IN_MSEC - diff, 10); vertx.setTimer(delay, this::generateAndSendToConsumer); }
From source file:de.openflorian.alarm.AlarmFaxEventMessageCodec.java
License:Open Source License
@Override public void encodeToWire(Buffer buffer, AlarmFaxEvent event) { JsonObject jsonToEncode = new JsonObject(); jsonToEncode.put(JSON_PROPERTY_FILENAME, event.getResultFile().getAbsolutePath()); // Encode object to string String jsonToStr = jsonToEncode.encode(); // Length of JSON: is NOT characters count int length = jsonToStr.getBytes().length; // Write data into given buffer buffer.appendInt(length);// www . j ava 2 s. com buffer.appendString(jsonToStr); }
From source file:demo.Main.java
License:Apache License
public static void main(String[] args) { Vertx vertx = Vertx.vertx();// w w w . j a v a2 s . c om vertx.deployVerticle(SimpleVerticle.class.getName(), new DeploymentOptions().setConfig(new JsonObject().put("message", "bonjour"))); }
From source file:docoverride.json.Examples.java
License:Open Source License
public void example1() { JsonObject object = new JsonObject(); object.put("foo", "bar").put("num", 123).put("mybool", true); }
From source file:doug.iotdemo.server.web.WebServer.java
License:Open Source License
private void handleFetch(RoutingContext context) { ScanRequest scanRequest = new ScanRequest().withTableName(sensorTableName); db.scanAsync(scanRequest, new AsyncHandler<ScanRequest, ScanResult>() { @Override//from ww w . j ava2 s . c o m public void onSuccess(ScanRequest request, ScanResult result) { JsonObject states = new JsonObject(); for (Map<String, AttributeValue> item : result.getItems()) { AttributeValue stateValue = item.get("state"); if (stateValue != null) { JsonObject sensorObj = new JsonObject(); sensorObj.put("state", Integer.valueOf(stateValue.getN())); if (item.get("time") != null) { long time = Long.parseLong(item.get("time").getN()); long count = Long.parseLong(item.get("count").getN()); long thresh = time / count; sensorObj.put("thresh", thresh); } states.put(item.get("sensor").getS(), sensorObj); } } context.response().end(states.encode()); } @Override public void onError(Exception exception) { StringWriter msg = new StringWriter(); exception.printStackTrace(new PrintWriter(msg)); context.response().setStatusCode(500).end(msg.toString()); } }); }
From source file:doug.iotdemo.server.web.WebServer.java
License:Open Source License
private void handlePut(RoutingContext context) { JsonObject msg = new JsonObject(); msg.put("sensor", context.request().getParam("sensor")); msg.put("state", Integer.valueOf(context.request().getParam("state"))); MqttMessage message = new MqttMessage(msg.toString().getBytes(StandardCharsets.UTF_8)); try {// ww w . ja v a2s. c om if (!mqtt.isConnected()) { mqtt.connect(this, new IMqttActionListener() { @Override public void onSuccess(IMqttToken arg0) { try { publishMessage(message, context); } catch (MqttException e) { throw new RuntimeException(e); } } @Override public void onFailure(IMqttToken arg0, Throwable t) { StringWriter msg = new StringWriter(); t.printStackTrace(new PrintWriter(msg)); context.response().setStatusCode(500).end(msg.toString()); } }); } else { publishMessage(message, context); } } catch (MqttException e) { throw new RuntimeException(e); } }
From source file:enmasse.kafka.bridge.converter.JsonMessageConverter.java
License:Apache License
@Override public ProducerRecord<String, byte[]> toKafkaRecord(String kafkaTopic, Message message) { Object partition = null, key = null; byte[] value = null; // root JSON/*from w w w . jav a2 s .c o m*/ JsonObject json = new JsonObject(); // make JSON with AMQP properties JsonObject jsonProperties = new JsonObject(); if (message.getMessageId() != null) jsonProperties.put(JsonMessageConverter.MESSAGE_ID, message.getMessageId()); if (message.getAddress() != null) jsonProperties.put(JsonMessageConverter.TO, message.getAddress()); if (message.getSubject() != null) jsonProperties.put(JsonMessageConverter.SUBJECT, message.getSubject()); if (message.getReplyTo() != null) jsonProperties.put(JsonMessageConverter.REPLY_TO, message.getReplyTo()); if (message.getCorrelationId() != null) jsonProperties.put(JsonMessageConverter.CORRELATION_ID, message.getCorrelationId()); if (!jsonProperties.isEmpty()) json.put(JsonMessageConverter.PROPERTIES, jsonProperties); // make JSON with AMQP application properties ApplicationProperties applicationProperties = message.getApplicationProperties(); if (applicationProperties != null) { JsonObject jsonApplicationProperties = new JsonObject(); Map<String, Object> applicationPropertiesMap = (Map<String, Object>) applicationProperties.getValue(); for (Entry<String, Object> entry : applicationPropertiesMap.entrySet()) { jsonApplicationProperties.put(entry.getKey(), entry.getValue()); } json.put(JsonMessageConverter.APPLICATION_PROPERTIES, jsonApplicationProperties); } // get partition and key from AMQP message annotations // NOTE : they are not mandatory MessageAnnotations messageAnnotations = message.getMessageAnnotations(); if (messageAnnotations != null) { partition = messageAnnotations.getValue().get(Symbol.getSymbol(Bridge.AMQP_PARTITION_ANNOTATION)); key = messageAnnotations.getValue().get(Symbol.getSymbol(Bridge.AMQP_KEY_ANNOTATION)); if (partition != null && !(partition instanceof Integer)) throw new IllegalArgumentException("The partition annotation must be an Integer"); if (key != null && !(key instanceof String)) throw new IllegalArgumentException("The key annotation must be a String"); // make JSON with AMQP message annotations JsonObject jsonMessageAnnotations = new JsonObject(); Map<Symbol, Object> messageAnnotationsMap = (Map<Symbol, Object>) messageAnnotations.getValue(); for (Entry<Symbol, Object> entry : messageAnnotationsMap.entrySet()) { jsonMessageAnnotations.put(entry.getKey().toString(), entry.getValue()); } json.put(JsonMessageConverter.MESSAGE_ANNOTATIONS, jsonMessageAnnotations); } // get topic and body from AMQP message String topic = (message.getAddress() == null) ? kafkaTopic : message.getAddress().replace('/', '.'); Section body = message.getBody(); // check body null if (body != null) { JsonObject jsonBody = new JsonObject(); // section is AMQP value if (body instanceof AmqpValue) { jsonBody.put(JsonMessageConverter.SECTION_TYPE, JsonMessageConverter.SECTION_AMQP_VALUE_TYPE); Object amqpValue = ((AmqpValue) body).getValue(); // encoded as String if (amqpValue instanceof String) { String content = (String) ((AmqpValue) body).getValue(); jsonBody.put(JsonMessageConverter.SECTION, content); // encoded as a List } else if (amqpValue instanceof List) { List<?> list = (List<?>) ((AmqpValue) body).getValue(); JsonArray jsonArray = new JsonArray(list); jsonBody.put(JsonMessageConverter.SECTION, jsonArray); // encoded as an array } else if (amqpValue instanceof Object[]) { Object[] array = (Object[]) ((AmqpValue) body).getValue(); JsonArray jsonArray = new JsonArray(Arrays.asList(array)); jsonBody.put(JsonMessageConverter.SECTION, jsonArray); // encoded as a Map } else if (amqpValue instanceof Map) { Map<?, ?> map = (Map<?, ?>) ((AmqpValue) body).getValue(); value = map.toString().getBytes(); JsonObject jsonMap = new JsonObject((Map<String, Object>) map); jsonBody.put(JsonMessageConverter.SECTION, jsonMap); } // section is Data (binary) } else if (body instanceof Data) { Binary binary = (Binary) ((Data) body).getValue(); value = binary.getArray(); jsonBody.put(JsonMessageConverter.SECTION_TYPE, JsonMessageConverter.SECTION_DATA_TYPE); // put the section bytes as Base64 encoded string jsonBody.put(JsonMessageConverter.SECTION, Base64.getEncoder().encode(value)); } // put the body into the JSON root json.put(JsonMessageConverter.BODY, jsonBody); } // build the record for the KafkaProducer and then send it return new ProducerRecord<>(topic, (Integer) partition, (String) key, json.toString().getBytes()); }
From source file:eu.rethink.mn.component.AllocationManager.java
License:Apache License
@Override public void handle(PipeContext ctx) { final PipeMessage msg = ctx.getMessage(); final JsonObject body = msg.getBody(); if (msg.getType().equals("create")) { //process JSON msg requesting a number of available addresses final JsonObject msgBodyValue = body.getJsonObject("value"); final String scheme = body.getString("scheme"); int number = msgBodyValue.getInteger("number", 5); final List<String> allocated = allocate(ctx, scheme, number); final PipeMessage reply = new PipeMessage(); reply.setId(msg.getId());/* w ww. j a va 2 s . co m*/ reply.setFrom(name); reply.setTo(msg.getFrom()); reply.setReplyCode(ReplyCode.OK); final JsonObject value = new JsonObject(); value.put("allocated", new JsonArray(allocated)); reply.getBody().put("value", value); ctx.reply(reply); } else if (msg.getType().equals("delete")) { //process JSON msg releasing an address final String resource = body.getString("resource"); final JsonArray childrenResourcesList = body.getJsonArray("childrenResources"); if (resource != null) { deallocate(ctx, resource); } else { for (Object childrenResource : childrenResourcesList) { deallocate(ctx, childrenResource.toString()); } } ctx.replyOK(name); } }