Java Code Examples for io.vertx.core.json.JsonArray#add()

The following examples show how to use io.vertx.core.json.JsonArray#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StoreCRUDServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
  return res -> {
    if (res.failed()) {
      if (res.cause() instanceof ServiceException) {
        msg.reply(res.cause());
      } else {
        msg.reply(new ServiceException(-1, res.cause().getMessage()));
      }
    } else {
      JsonArray arr = new JsonArray();
      for (Character chr: res.result()) {
        arr.add((int) chr);
      }
      msg.reply(arr);
    }
  };
}
 
Example 2
Source File: ProducerTest.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@Test
void sendToBothPartitionTest(VertxTestContext context) {
    String kafkaTopic = "sendToBothPartitionTest";
    kafkaCluster.createTopic(kafkaTopic, 3, 1);

    String value = "Hi, This is kafka bridge";
    int partition = 1;

    JsonArray records = new JsonArray();
    JsonObject json = new JsonObject();
    json.put("value", value);
    json.put("partition", 2);
    records.add(json);

    JsonObject root = new JsonObject();
    root.put("records", records);

    producerService()
        .sendRecordsToPartitionRequest(kafkaTopic, partition, root, BridgeContentType.KAFKA_JSON_JSON)
        .sendJsonObject(root, verifyBadRequest(context, "Validation error on: body.records[0] - " +
                "$.records[0].partition: is not defined in the schema and the schema does not allow additional properties"));
}
 
Example 3
Source File: PortfolioServiceVertxProxyHandler.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
  return res -> {
    if (res.failed()) {
      if (res.cause() instanceof ServiceException) {
        msg.reply(res.cause());
      } else {
        msg.reply(new ServiceException(-1, res.cause().getMessage()));
      }
    } else {
      JsonArray arr = new JsonArray();
      for (Character chr: res.result()) {
        arr.add((int) chr);
      }
      msg.reply(arr);
    }
  };
}
 
Example 4
Source File: CounterServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
  return res -> {
    if (res.failed()) {
      if (res.cause() instanceof ServiceException) {
        msg.reply(res.cause());
      } else {
        msg.reply(new ServiceException(-1, res.cause().getMessage()));
      }
    } else {
      JsonArray arr = new JsonArray();
      for (Character chr: res.result()) {
        arr.add((int) chr);
      }
      msg.reply(arr);
    }
  };
}
 
Example 5
Source File: PortfolioServiceVertxProxyHandler.java    From microtrader with MIT License 6 votes vote down vote up
private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
  return res -> {
    if (res.failed()) {
      if (res.cause() instanceof ServiceException) {
        msg.reply(res.cause());
      } else {
        msg.reply(new ServiceException(-1, res.cause().getMessage()));
      }
    } else {
      JsonArray arr = new JsonArray();
      for (Character chr: res.result()) {
        arr.add((int) chr);
      }
      msg.reply(arr);
    }
  };
}
 
Example 6
Source File: StoreCRUDServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
private Handler<AsyncResult<Set<Character>>> createSetCharHandler(Message msg) {
  return res -> {
    if (res.failed()) {
      if (res.cause() instanceof ServiceException) {
        msg.reply(res.cause());
      } else {
        msg.reply(new ServiceException(-1, res.cause().getMessage()));
      }
    } else {
      JsonArray arr = new JsonArray();
      for (Character chr: res.result()) {
        arr.add((int) chr);
      }
      msg.reply(arr);
    }
  };
}
 
Example 7
Source File: ConsumerSubscriptionTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void subscriptionConsumerDoesNotExistBecauseAnotherGroup(VertxTestContext context) throws InterruptedException, ExecutionException, TimeoutException {
    String topic = "subscriptionConsumerDoesNotExistBecauseAnotherGroup";
    kafkaCluster.createTopic(topic, 1, 1);
    String name = "my-kafka-consumer-does-not-exists-because-another-group";
    String groupId = "my-group";
    String anotherGroupId = "anotherGroupId";

    JsonArray topics = new JsonArray();
    topics.add(topic);

    JsonObject topicsRoot = new JsonObject();
    topicsRoot.put("topics", topics);

    JsonObject json = new JsonObject();
    json.put("name", name);
    json.put("format", "json");

    // create consumer
    consumerService()
            .createConsumer(context, groupId, json);

    CompletableFuture<Boolean> subscribe = new CompletableFuture<>();
    consumerService()
            .subscribeConsumerRequest(anotherGroupId, name, topicsRoot)
            .sendJsonObject(topicsRoot, ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    HttpBridgeError error = HttpBridgeError.fromJson(response.body());
                    assertThat(response.statusCode(), is(HttpResponseStatus.NOT_FOUND.code()));
                    assertThat(error.getCode(), is(HttpResponseStatus.NOT_FOUND.code()));
                    assertThat(error.getMessage(), is("The specified consumer instance was not found."));
                });
                subscribe.complete(true);
            });
    subscribe.get(TEST_TIMEOUT, TimeUnit.SECONDS);
    context.completeNow();
}
 
Example 8
Source File: MapBasedDeviceConnectionService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private JsonObject getResultJson(final Map<String, String> deviceToAdapterInstanceMap) {
    final JsonObject jsonObject = new JsonObject();
    final JsonArray adapterInstancesArray = new JsonArray(new ArrayList<>(deviceToAdapterInstanceMap.size()));
    for (final Map.Entry<String, String> resultEntry : deviceToAdapterInstanceMap.entrySet()) {
        final JsonObject entryJson = new JsonObject();
        entryJson.put(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID, resultEntry.getKey());
        entryJson.put(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID, resultEntry.getValue());
        adapterInstancesArray.add(entryJson);
    }
    jsonObject.put(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES, adapterInstancesArray);
    return jsonObject;
}
 
Example 9
Source File: AccountDao.java    From AlipayWechatPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 更新微信支付配置
 */
public void updateWxPay(JsonObject acc, Handler<Integer> callback) {
    Integer id = acc.getInteger(ID);
    if(id == null){
        throw new IllegalArgumentException("Account ID cannot be null!!!");
    }
    StringBuilder sql = new StringBuilder("update awp_account set ");
    JsonArray params = new JsonArray();
    boolean moreThanOne = false;
    String mchid = acc.getString(MCHID);
    if (mchid != null && !mchid.equals("")) {
        sql.append("mchId=?");
        params.add(mchid);
        moreThanOne = true;
    }
    String mchkey = acc.getString(MCHKEY);
    if (mchkey != null && !mchkey.equals("")) {
        if (moreThanOne) sql.append(",");
        sql.append("mchKey=?");
        params.add(mchkey);
        moreThanOne = true;
    }
    Integer wxpayon = acc.getInteger(WXPAYON);
    if (wxpayon != null) {
        if (moreThanOne) sql.append(",");
        sql.append("wxPayOn=?");
        params.add(wxpayon);
    }
    sql.append(" where id=?");
    params.add(id);
    update(sql.toString(), params, callback);
}
 
Example 10
Source File: StUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static JsonArray expectedServiceDiscoveryInfo(int port, String protocol, String auth) {
    JsonObject jsonObject = new JsonObject();
    jsonObject.put("port", port);
    jsonObject.put("tls", port == 9093);
    jsonObject.put("protocol", protocol);
    jsonObject.put("auth", auth);

    JsonArray jsonArray = new JsonArray();
    jsonArray.add(jsonObject);

    return jsonArray;
}
 
Example 11
Source File: AmqpSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testSourceWithListContent() {
    String topic = UUID.randomUUID().toString();
    Map<String, Object> config = getConfig(topic);
    provider = new AmqpConnector();
    provider.setup(executionHolder);

    List<Message<JsonArray>> messages = new ArrayList<>();
    PublisherBuilder<? extends Message<?>> builder = provider.getPublisherBuilder(new MapBasedConfig(config));
    AtomicBoolean opened = new AtomicBoolean();

    builder.to(createSubscriber(messages, opened)).run();
    await().until(opened::get);

    await().until(() -> provider.isReady(config.get(CHANNEL_NAME_ATTRIBUTE).toString()));

    JsonArray list = new JsonArray();
    String id = UUID.randomUUID().toString();
    list.add("ola");
    list.add(id);
    usage.produce(topic, 1, () -> AmqpMessage.create().withJsonArrayAsBody(list).build());

    await().atMost(2, TimeUnit.MINUTES).until(() -> !messages.isEmpty());
    JsonArray result = messages.get(0).getPayload();
    assertThat(result)
            .containsExactly("ola", id);
}
 
Example 12
Source File: MemMapArrayResultRangeJsonVerticleTest.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testArrayResultJson(TestContext context) {
    HttpClient httpClient = vertx.createHttpClient();
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(0);
    Async async = context.async();

    HttpClientRequest req = httpClient.post(port, "localhost", "/array/json")
            .handler(handler -> {
                handler.bodyHandler(body -> {
                    byte[] npyArray = body.getBytes();
                    System.out.println("Found numpy array bytes with length " + npyArray.length);
                    System.out.println("Contents: " + new String(npyArray));
                    context.assertEquals(Double.parseDouble(new String(npyArray)), 1.0);
                    async.complete();
                });

                handler.exceptionHandler(exception -> {
                    if (exception.getCause() != null)
                        context.fail(exception.getCause());
                    async.complete();
                });

            }).putHeader("Content-Type", "application/json")
            .putHeader("Content-Length", String.valueOf(jsonArray.toBuffer().length()))
            .write(jsonArray.encode());

    async.await();
}
 
Example 13
Source File: DATAVerticle.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 删除一个应用程序,接收应用程序的字符串名字
 * 
 * @param msg
 */
public void delApplication(Message<String> msg) {
	if (msg.body() == null) {
		msg.fail(411, "the application name is null");
	} else {
		String isql = MessageFormat.format("delete from {0} where {1} = ?", APITN, API_APPIC);
		JsonArray iparams = new JsonArray();
		iparams.add(msg.body());
		jdbcClient.updateWithParams(isql, iparams, ires -> {
			if (ires.succeeded()) {
				String sql = MessageFormat.format("delete from {0} where {1} = ?", APPTN, APPIC);
				JsonArray params = new JsonArray();
				params.add(msg.body());
				jdbcClient.updateWithParams(sql, params, res -> {
					if (res.succeeded()) {
						int result = res.result().getUpdated();
						msg.reply(result);
					} else {
						msg.fail(500, res.cause().toString());
						LOG.error("执行删除应用程序-->失败:" + ires.cause().toString());
					}
				});
			} else {
				msg.fail(500, ires.cause().toString());
				LOG.error("执行删除应用程序-->失败:" + ires.cause().toString());
			}
		});

	}
}
 
Example 14
Source File: MemMapArrayResultRangeVerticleTest.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testArrayResultRange(TestContext context) {
    HttpClient httpClient = vertx.createHttpClient();
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(0);
    Async async = context.async();

    httpClient.post(port, "localhost", "/array/range/0/2/numpy")
            .handler(handler -> {
                handler.bodyHandler(body -> {
                    byte[] npyArray = body.getBytes();
                    System.out.println("Found numpy array bytes with length " + npyArray.length);
                    System.out.println("Contents: " + new String(npyArray));
                    INDArray arrFromNumpy = Nd4j.createNpyFromByteArray(npyArray);
                    INDArray assertion = Nd4j.create(new float[]{1, 2}).reshape(2);
                    context.assertEquals(assertion, arrFromNumpy);
                    System.out.println(arrFromNumpy);
                    async.complete();
                });

                handler.exceptionHandler(exception -> {
                    if (exception.getCause() != null)
                        context.fail(exception.getCause());
                });
            }).putHeader("Content-Type", "application/json")
            .putHeader("Content-Length", String.valueOf(0))
            .write("");

    async.await();
}
 
Example 15
Source File: MyRX2Verticle.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
private synchronized JsonArray getBindings(ServiceDiscovery discovery) {
  JsonArray array = new JsonArray();
  for (ServiceReference ref : discovery.bindings()) {
    array.add(ref.toString());
  }
  return array;
}
 
Example 16
Source File: SeekTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
@Disabled // This test was disabled because of known issue described in https://github.com/strimzi/strimzi-kafka-bridge/issues/320
void seekToNotExistingPartitionInSubscribedTopic(VertxTestContext context) throws InterruptedException, ExecutionException, TimeoutException {
    String topic = "seekToNotExistingPartitionInSubscribedTopic";
    kafkaCluster.createTopic(topic, 1, 1);

    // create consumer
    consumerService()
        .createConsumer(context, groupId, jsonConsumer)
        .subscribeTopic(context, groupId, name, new JsonObject().put("topic", topic).put("partition", 0));

    int notExistingPartition = 2;
    JsonArray notExistingPartitionJSON = new JsonArray();
    notExistingPartitionJSON.add(new JsonObject().put("topic", topic).put("partition", notExistingPartition));

    JsonObject partitionsJSON = new JsonObject();
    partitionsJSON.put("partitions", notExistingPartitionJSON);

    seekService().positionsBeginningRequest(groupId, name, partitionsJSON)
        .sendJsonObject(partitionsJSON, ar -> {
            context.verify(() -> {
                assertThat(ar.succeeded(), is(true));
                HttpResponse<JsonObject> response = ar.result();
                HttpBridgeError error = HttpBridgeError.fromJson(response.body());
                assertThat(response.statusCode(), is(HttpResponseStatus.NOT_FOUND.code()));
                assertThat(error.getCode(), is(HttpResponseStatus.NOT_FOUND.code()));
                assertThat(error.getMessage(), is("No current assignment for partition " + topic + "-" + notExistingPartition));
                context.completeNow();
            });
        });
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
}
 
Example 17
Source File: PostgresClientIT.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
@Test
public void saveBatchJsonNullEntity(TestContext context) {
  JsonArray array = new JsonArray();
  array.add((String) null);
  createFoo(context).saveBatch(FOO, array, context.asyncAssertFailure());
}
 
Example 18
Source File: ProducerTest.java    From strimzi-kafka-bridge with Apache License 2.0 4 votes vote down vote up
@Test
void sendSimpleMessage(VertxTestContext context) {
    String topic = "sendSimpleMessage";
    kafkaCluster.createTopic(topic, 1, 1);

    String value = "message-value";

    JsonArray records = new JsonArray();
    JsonObject json = new JsonObject();
    json.put("value", value);
    records.add(json);

    JsonObject root = new JsonObject();
    root.put("records", records);

    producerService()
        .sendRecordsRequest(topic, root, BridgeContentType.KAFKA_JSON_JSON)
        .sendJsonObject(root, verifyOK(context));

    Properties config = kafkaCluster.getConsumerProperties();

    KafkaConsumer<String, String> consumer = KafkaConsumer.create(vertx, config,
            new StringDeserializer(), new KafkaJsonDeserializer<>(String.class));
    consumer.handler(record -> {
        context.verify(() -> {
            assertThat(record.value(), is(value));
            assertThat(record.topic(), is(topic));
            assertThat(record.partition(), is(0));
            assertThat(record.offset(), is(0L));
            assertThat(record.key(), nullValue());
        });
        LOGGER.info("Message consumed topic={} partition={} offset={}, key={}, value={}",
                record.topic(), record.partition(), record.offset(), record.key(), record.value());
        consumer.close();
        context.completeNow();
    });

    consumer.subscribe(topic, done -> {
        if (!done.succeeded()) {
            context.failNow(done.cause());
        }
    });
}
 
Example 19
Source File: StUtils.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public static JsonArray expectedServiceDiscoveryInfo(String plainAuth, String tlsAuth) {
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(expectedServiceDiscoveryInfo(9092, "kafka", plainAuth).getValue(0));
    jsonArray.add(expectedServiceDiscoveryInfo(9093, "kafka", tlsAuth).getValue(0));
    return jsonArray;
}
 
Example 20
Source File: JsArray.java    From vertx-codetrans with Apache License 2.0 4 votes vote down vote up
@CodeTranslate
public void addObject() throws Exception {
  JsonArray arr = new JsonArray();
  arr.add(new JsonObject().put("foo", "foo_value"));
  JsonTest.o = JsonConverter.toJsonArray(arr);
}