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

The following examples show how to use io.vertx.core.json.JsonArray#getJsonObject() . 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: MapBasedDeviceConnectionServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Asserts the the given result JSON of the <em>getCommandHandlingAdapterInstances</em> method contains an
 * "adapter-instances" entry with the given device id and adapter instance id.
 */
private void assertGetInstancesResultMapping(final JsonObject resultJson, final String deviceId,
        final String adapterInstanceId) {
    assertNotNull(resultJson);
    final JsonArray adapterInstancesJson = resultJson
            .getJsonArray(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES);
    assertNotNull(adapterInstancesJson);
    boolean entryFound = false;
    for (int i = 0; i < adapterInstancesJson.size(); i++) {
        final JsonObject entry = adapterInstancesJson.getJsonObject(i);
        if (deviceId.equals(entry.getString(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID))) {
            entryFound = true;
            assertEquals(adapterInstanceId, entry.getString(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID));
        }
    }
    assertTrue(entryFound);
}
 
Example 2
Source File: JsonArrayMapConverter.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<? extends Map<FieldName, ?>> convertPmml(Schema schema, JsonArray jsonArray, TransformProcess transformProcess) {
    if (transformProcess != null) {
        return doTransformProcessConvertPmml(schema, jsonArray, transformProcess);
    }


    List<FieldName> fieldNames = getNameRepresentationFor(schema);


    List<Map<FieldName, Object>> ret = new ArrayList<>(jsonArray.size());

    for (int i = 0; i < jsonArray.size(); i++) {
        JsonObject jsonObject = jsonArray.getJsonObject(i);
        Map<FieldName, Object> record = new LinkedHashMap();
        for (int j = 0; j < schema.numColumns(); j++) {
            record.put(fieldNames.get(j), jsonObject.getValue(schema.getName(j)));

        }

        ret.add(record);
    }

    return ret;
}
 
Example 3
Source File: TestPythonJsonInput.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testInferenceResult(TestContext context) {
    this.context = context;

    RequestSpecification requestSpecification = given();
    requestSpecification.port(port);
    JsonObject inputJson = new JsonObject();
    inputJson.put("first", 2);
    requestSpecification.body(inputJson.encode().getBytes());
    requestSpecification.header("Content-Type", "application/json");
    String responseBody = requestSpecification.when()
            .expect().statusCode(200)
            .body(not(isEmptyOrNullString()))
            .post("/raw/json").then()
            .extract()
            .body().asString();
    JsonArray outputJsonArray = new JsonArray(responseBody);
    JsonObject result = outputJsonArray.getJsonObject(0);
    assertTrue(result.containsKey("second"));
    assertEquals(4, result.getInteger("second"), 1e-1);
}
 
Example 4
Source File: UserConverter.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
public static User decode(JsonObject json) throws IllegalArgumentException {
  Objects.requireNonNull(json);

  JsonObject principal = json.getJsonObject(FIELD_PRINCIPAL);
  User user = User.create(principal);
  // authorizations
  JsonObject jsonAuthorizations = json.getJsonObject(FIELD_AUTHORIZATIONS);
  for (String fieldName: jsonAuthorizations.fieldNames()) {
    JsonArray jsonAuthorizationByProvider = jsonAuthorizations.getJsonArray(fieldName);
    for (int i=0; i<jsonAuthorizationByProvider.size(); i++) {
      JsonObject jsonAuthorization = jsonAuthorizationByProvider.getJsonObject(i);
      user.authorizations().add(fieldName, AuthorizationConverter.decode(jsonAuthorization));
    }
  }
  return user;
}
 
Example 5
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private static void manageHttpService(Record record, JsonObject service) {
  JsonObject spec = service.getJsonObject("spec");
  JsonArray ports = spec.getJsonArray("ports");

  if (ports != null && !ports.isEmpty()) {
    if (ports.size() > 1) {
      LOGGER.warn("More than one port has been found for " + record.getName() + " - taking the first" +
        " one to extract the HTTP endpoint location");
    }

    JsonObject port = ports.getJsonObject(0);
    Integer p = port.getInteger("port");

    record.setType(HttpEndpoint.TYPE);

    HttpLocation location = new HttpLocation(port.copy());

    if (isExternalService(service)) {
      location.setHost(spec.getString("externalName"));
    } else {
      location.setHost(spec.getString("clusterIP"));
    }

    if (isTrue(record.getMetadata().getString("ssl")) || p != null && p == 443) {
      location.setSsl(true);
    }
    record.setLocation(location.toJson());
  } else {
    throw new IllegalStateException("Cannot extract the HTTP URL from the service " + record + " - no port");
  }
}
 
Example 6
Source File: SpringConfigServerStore.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
private void parseFromStandard(JsonObject body, Handler<AsyncResult<Buffer>> handler) {
  JsonArray sources = body.getJsonArray("propertySources");
  if (sources == null) {
    handler.handle(Future.failedFuture("Invalid configuration server response, property sources missing"));
  } else {
    JsonObject configuration = new JsonObject();
    for (int i = sources.size() - 1; i >= 0; i--) {
      JsonObject source = sources.getJsonObject(i);
      JsonObject content = source.getJsonObject("source");
      configuration = configuration.mergeIn(content, true);
    }
    handler.handle(Future.succeededFuture(Buffer.buffer(configuration.encode())));
  }
}
 
Example 7
Source File: KafkaBridgeUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static void checkSendResponse(JsonObject response, int messageCount) {
    JsonArray offsets = response.getJsonArray("offsets");
    assertThat(offsets.size(), is(messageCount));
    for (int i = 0; i < messageCount; i++) {
        JsonObject metadata = offsets.getJsonObject(i);
        assertThat(metadata.getInteger("partition"), is(0));
        assertThat(metadata.getInteger("offset"), is(i));
        LOGGER.debug("offset size: {}, partition: {}, offset size: {}", offsets.size(), metadata.getInteger("partition"), metadata.getLong("offset"));
    }
}
 
Example 8
Source File: JsonArrayMapConverter.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Pair<Map<Integer, Integer>, List<? extends Map<FieldName, ?>>> convertPmmlWithErrors(Schema schema, JsonArray jsonArray, TransformProcess transformProcess, DataPipelineErrorHandler dataPipelineErrorHandler) {
    if (transformProcess != null) {
        return doTransformProcessConvertPmmlWithErrors(schema, jsonArray, transformProcess, dataPipelineErrorHandler);
    }


    List<FieldName> fieldNames = getNameRepresentationFor(schema);


    List<Map<FieldName, Object>> ret = new ArrayList<>(jsonArray.size());
    Map<Integer, Integer> mapping = new LinkedHashMap<>();
    int numSucceeded = 0;
    for (int i = 0; i < jsonArray.size(); i++) {
        try {
            JsonObject jsonObject = jsonArray.getJsonObject(i);
            if (jsonObject.size() != schema.numColumns()) {
                throw new IllegalArgumentException("Found illegal item at row " + i);
            }
            Map<FieldName, Object> record = new LinkedHashMap();
            for (int j = 0; j < schema.numColumns(); j++) {
                record.put(fieldNames.get(j), jsonObject.getValue(schema.getName(j)));
            }

            mapping.put(numSucceeded, i);
            numSucceeded++;
            ret.add(record);
        } catch (Exception e) {
            dataPipelineErrorHandler.onError(e, jsonArray.getJsonObject(i), i);
        }
    }


    return Pair.of(mapping, ret);
}
 
Example 9
Source File: ArcEndpointTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBeans() {
    String debugPath = RestAssured.get("/console-path").asString();
    JsonArray beans = new JsonArray(RestAssured.get(debugPath + "/arc/beans").asString());
    JsonArray observers = new JsonArray(RestAssured.get(debugPath + "/arc/observers").asString());
    JsonObject fooBean = null;
    JsonObject fooObserver = null;
    for (int i = 0; i < beans.size(); i++) {
        JsonObject bean = beans.getJsonObject(i);
        if (bean.getString("beanClass").equals(Foo.class.getName())) {
            fooBean = bean;
        }
    }
    assertNotNull(fooBean);
    assertEquals(ApplicationScoped.class.getName(), fooBean.getString("scope"));
    assertEquals("CLASS", fooBean.getString("kind"));
    assertEquals("foo", fooBean.getString("name"));
    String beanId = fooBean.getString("id");
    assertNotNull(beanId);

    for (int i = 0; i < observers.size(); i++) {
        JsonObject observer = observers.getJsonObject(i);
        if (beanId.equals(observer.getString("declaringBean"))
                && StartupEvent.class.getName().equals(observer.getString("observedType"))) {
            fooObserver = observer;
            assertEquals(2500, fooObserver.getInteger("priority"));
        }
    }
    assertNotNull(fooObserver);
}
 
Example 10
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private static void handleOverrides() throws IOException {
  String overrides = null;
  if(overrideFileExists){
    overrides = IOUtils.toString(ResourceMethodExtensionPlugin.class.getClassLoader().getResourceAsStream(
      "overrides/raml_overrides.json"), "UTF-8");
    if(overrides == null){
      log.info("No overrides/raml_overrides.json file found, continuing...");
      overrideFileExists = false;
      return;
    }
  }
  else{
    return;
  }
  if(overrideMap.isEmpty()){
    try {
      JsonObject jobj = new JsonObject(overrides);
      JsonArray jar = jobj.getJsonArray("overrides");
      int size = jar.size();
      for (int i = 0; i < size; i++) {
        JsonObject overrideEntry = jar.getJsonObject(i);
        String type = overrideEntry.getString("type");
        String url = overrideEntry.getString("url");
        overrideMap.put(url, type, overrideEntry);
      }
    } catch (Exception e1) {
      log.error(e1.getMessage(), e1);
    }
  }
}
 
Example 11
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private static void manageUnknownService(Record record, JsonObject service, String type) {
  JsonObject spec = service.getJsonObject("spec");
  JsonArray ports = spec.getJsonArray("ports");
  if (ports != null && !ports.isEmpty()) {
    if (ports.size() > 1) {
      LOGGER.warn("More than one ports has been found for " + record.getName() + " - taking the " +
        "first one to build the record location");
    }
    JsonObject port = ports.getJsonObject(0);
    JsonObject location = port.copy();

    if (isExternalService(service)) {
      location.put("host", spec.getString("externalName"));
    } else {
      //Number or name of the port to access on the pods targeted by the service.
      Object targetPort = port.getValue("targetPort");
      if (targetPort instanceof Integer) {
        location.put("internal-port", (Integer) targetPort);
      }
      location.put("host", spec.getString("clusterIP"));
    }

    record.setLocation(location).setType(type);
  } else {
    throw new IllegalStateException("Cannot extract the location from the service " + record + " - no port");
  }
}
 
Example 12
Source File: CacheBasedDeviceConnectionInfoTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Asserts the the given result JSON of the <em>getCommandHandlingAdapterInstances</em> method contains
 * an "adapter-instances" entry with the given device id and adapter instance id.
 */
private void assertGetInstancesResultMapping(final JsonObject resultJson, final String deviceId, final String adapterInstanceId) {
    assertNotNull(resultJson);
    final JsonArray adapterInstancesJson = resultJson.getJsonArray(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES);
    assertNotNull(adapterInstancesJson);
    boolean entryFound = false;
    for (int i = 0; i < adapterInstancesJson.size(); i++) {
        final JsonObject entry = adapterInstancesJson.getJsonObject(i);
        if (deviceId.equals(entry.getString(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID))) {
            entryFound = true;
            assertEquals(adapterInstanceId, entry.getString(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID));
        }
    }
    assertTrue(entryFound);
}
 
Example 13
Source File: OrAuthorizationConverter.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static OrAuthorization decode(JsonObject json) throws IllegalArgumentException {
  Objects.requireNonNull(json);

  if (TYPE_AND_AUTHORIZATION.equals(json.getString(FIELD_TYPE))) {
    OrAuthorization result = OrAuthorization.create();
    JsonArray authorizations = json.getJsonArray(FIELD_AUTHORIZATIONS);
    for (int i = 0; i < authorizations.size(); i++) {
      JsonObject authorization = authorizations.getJsonObject(i);
      result.addAuthorization(AuthorizationConverter.decode(authorization));
    }
    return result;
  }
  return null;
}
 
Example 14
Source File: WxApiClient.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 获取素材
 * @param mediaType 素材类型
 * @param offset 开始位置
 * @param count 获取数量
 * @return
 */
public static Material syncBatchMaterial(MediaType mediaType, Integer offset, Integer count, Account mpAccount){
	String accessToken = getAccessToken(mpAccount);
	String url = WxApi.getBatchMaterialUrl(accessToken);
	JsonObject bodyObj = new JsonObject();
	bodyObj.put("type", mediaType.toString());
	bodyObj.put("offset", offset);
	bodyObj.put("count", count);
	String body = bodyObj.toString();
	try {
		JsonObject jsonObj = WxApi.httpsRequest(url, "POST", body);
		if (jsonObj.containsKey("errcode")) {//获取素材失败
			System.out.println(ErrCode.errMsg(jsonObj.getInteger("errcode")));
			return null;
		}else{
			Material material = new Material();
			material.setTotalCount(jsonObj.getInteger("total_count"));
			material.setItemCount(jsonObj.getInteger("item_count"));
			JsonArray arr = jsonObj.getJsonArray("item");
			if(arr != null && arr.size() > 0){
				List<MaterialItem> itemList = new ArrayList<MaterialItem>();
				for(int i = 0; i < arr.size(); i++){
					JsonObject item = arr.getJsonObject(i);
					MaterialItem materialItem = new MaterialItem();
					materialItem.setMediaId(item.getString("media_id"));
					materialItem.setUpdateTime(item.getLong("update_time")*1000L);
					if(item.containsKey("content")){//mediaType=news (图文消息)
						JsonArray articles = item.getJsonObject("content").getJsonArray("news_item");
						List<MaterialArticle> newsItems = new ArrayList<MaterialArticle>();
						for(int j = 0; j < articles.size(); j++){
							JsonObject article = articles.getJsonObject(j);
							MaterialArticle ma = new MaterialArticle();
							ma.setTitle(article.getString("title"));
							ma.setThumb_media_id(article.getString("thumb_media_id"));
							ma.setShow_cover_pic(article.getString("show_cover_pic"));
							ma.setAuthor(article.getString("author"));
							ma.setContent_source_url(article.getString("content_source_url"));
							ma.setContent(article.getString("content"));
							ma.setUrl(article.getString("url"));
							newsItems.add(ma);
						}
						materialItem.setNewsItems(newsItems);
					}else{
						materialItem.setName(item.getString("name"));
						materialItem.setUrl(item.getString("url"));
					}
					itemList.add(materialItem);
				}
				material.setItems(itemList);
			}
			return material;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 15
Source File: AccountDBVerticle.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
private void updateAlipayPay(Handler replyMsg, JsonArray params) {
    JsonObject acc = params.getJsonObject(0);
    accDao.updateZfbPay(acc, replyMsg);
}
 
Example 16
Source File: AccountDBVerticle.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
private void updateWechatPay(Handler replyMsg, JsonArray params) {
    JsonObject acc = params.getJsonObject(0);
    accDao.updateWxPay(acc, replyMsg);
}
 
Example 17
Source File: AccountDBVerticle.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
private void updateNormalInfo(Handler replyMsg, JsonArray params) {
    JsonObject acc = params.getJsonObject(0);
    accDao.updateBase(acc, replyMsg);
}
 
Example 18
Source File: OrderDBVerticle.java    From AlipayWechatPlatform with GNU General Public License v3.0 4 votes vote down vote up
private void insertOrder(Handler replyMsg, JsonArray params) {
    JsonObject orderInsert = params.getJsonObject(0);
    orderDao.insert(orderInsert, replyMsg);
}
 
Example 19
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void batchRequest() throws Exception {
  final int clientVersionRequestId = 2;
  final int brokenRequestId = 3;
  final int netVersionRequestId = 4;
  final RequestBody body =
      RequestBody.create(
          JSON,
          "[{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(clientVersionRequestId)
              + ",\"method\":\"web3_clientVersion\"},"
              + "{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(brokenRequestId)
              + ",\"method\":\"bla\"},"
              + "{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(netVersionRequestId)
              + ",\"method\":\"net_version\"}]");

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    assertThat(resp.code()).isEqualTo(200);
    // Check general format of result
    final JsonArray json = new JsonArray(resp.body().string());
    final int requestCount = 3;
    assertThat(json.size()).isEqualTo(requestCount);
    final Map<Integer, JsonObject> responses = new HashMap<>();
    for (int i = 0; i < requestCount; ++i) {
      final JsonObject response = json.getJsonObject(i);
      responses.put(response.getInteger("id"), response);
    }

    // Check result web3_clientVersion
    final JsonObject jsonClientVersion = responses.get(clientVersionRequestId);
    testHelper.assertValidJsonRpcResult(jsonClientVersion, clientVersionRequestId);
    assertThat(jsonClientVersion.getString("result")).isEqualTo(CLIENT_VERSION);

    // Check result unknown method
    final JsonObject jsonError = responses.get(brokenRequestId);
    final JsonRpcError expectedError = JsonRpcError.METHOD_NOT_FOUND;
    testHelper.assertValidJsonRpcError(
        jsonError, brokenRequestId, expectedError.getCode(), expectedError.getMessage());

    // Check result net_version
    final JsonObject jsonNetVersion = responses.get(netVersionRequestId);
    testHelper.assertValidJsonRpcResult(jsonNetVersion, netVersionRequestId);
    assertThat(jsonNetVersion.getString("result")).isEqualTo(String.valueOf(CHAIN_ID));
  }
}
 
Example 20
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void batchRequestContainingInvalidRequest() throws Exception {
  final int clientVersionRequestId = 2;
  final int invalidId = 3;
  final int netVersionRequestId = 4;
  final String[] reqs = new String[3];
  reqs[0] =
      "{\"jsonrpc\":\"2.0\",\"id\":"
          + Json.encode(clientVersionRequestId)
          + ",\"method\":\"web3_clientVersion\"}";
  reqs[1] = "5";
  reqs[2] =
      "{\"jsonrpc\":\"2.0\",\"id\":"
          + Json.encode(netVersionRequestId)
          + ",\"method\":\"net_version\"}";
  final String batchRequest = "[" + String.join(", ", reqs) + "]";
  final RequestBody body = RequestBody.create(JSON, batchRequest);

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    assertThat(resp.code()).isEqualTo(200);
    // Check general format of result
    final String jsonStr = resp.body().string();
    final JsonArray json = new JsonArray(jsonStr);
    final int requestCount = 3;
    assertThat(json.size()).isEqualTo(requestCount);

    // Organize results for inspection
    final Map<Integer, JsonObject> responses = new HashMap<>();
    for (int i = 0; i < requestCount; ++i) {
      final JsonObject response = json.getJsonObject(i);
      Integer identifier = response.getInteger("id");
      if (identifier == null) {
        identifier = invalidId;
      }
      responses.put(identifier, response);
    }

    // Check result web3_clientVersion
    final JsonObject jsonClientVersion = responses.get(clientVersionRequestId);
    testHelper.assertValidJsonRpcResult(jsonClientVersion, clientVersionRequestId);
    assertThat(jsonClientVersion.getString("result")).isEqualTo(CLIENT_VERSION);

    // Check invalid request
    final JsonObject jsonError = responses.get(invalidId);
    final JsonRpcError expectedError = JsonRpcError.INVALID_REQUEST;
    testHelper.assertValidJsonRpcError(
        jsonError, null, expectedError.getCode(), expectedError.getMessage());

    // Check result net_version
    final JsonObject jsonNetVersion = responses.get(netVersionRequestId);
    testHelper.assertValidJsonRpcResult(jsonNetVersion, netVersionRequestId);
    assertThat(jsonNetVersion.getString("result")).isEqualTo(String.valueOf(CHAIN_ID));
  }
}