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

The following examples show how to use io.vertx.core.json.JsonObject#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: JsonRpcHttpServiceRpcApisTest.java    From besu with Apache License 2.0 6 votes vote down vote up
private void assertNetService(
    final boolean[] servicesStates, final JsonObject jsonBody, final String serviceName) {

  final boolean isAssertTrue = servicesStates[netServices.indexOf(serviceName)];

  final JsonObject result = jsonBody.getJsonObject("result");
  final JsonObject serviceElement = result.getJsonObject(serviceName);
  if (isAssertTrue) {
    assertThat(
            serviceElement != null
                && serviceElement.containsKey("host")
                && serviceElement.containsKey("port"))
        .isTrue();
  } else {
    assertThat(
            serviceElement != null
                && serviceElement.containsKey("host")
                && serviceElement.containsKey("port"))
        .isFalse();
  }
}
 
Example 2
Source File: CoordinateParser.java    From vertx-consul-client with Apache License 2.0 6 votes vote down vote up
static Coordinate parse(JsonObject json) {
  Coordinate coordinate = new Coordinate()
    .setNode(json.getString(NODE_KEY));
  JsonObject coord = json.getJsonObject(COORD_KEY);
  if (coord != null) {
    coordinate
      .setAdj(coord.getFloat(ADJ_KEY, 0f))
      .setErr(coord.getFloat(ERR_KEY, 0f))
      .setHeight(coord.getFloat(HEIGHT_KEY, 0f));
    JsonArray arr = coord.getJsonArray(VEC_KEY);
    coordinate.setVec(arr == null ? null : arr.stream()
      .map(o -> o instanceof Number ? ((Number) o).floatValue() : 0f)
      .collect(Collectors.toList()));
  }
  return coordinate;
}
 
Example 3
Source File: MonitoringClient.java    From enmasse with Apache License 2.0 6 votes vote down vote up
private JsonObject getRule(String name) throws Exception {
    JsonObject rules = client.getRules();
    if (rules.getString("status", "").equals("success")) {
        JsonObject data = rules.getJsonObject("data", new JsonObject());
        for (Object obj : data.getJsonArray("groups", new JsonArray())) {
            JsonObject group = (JsonObject) obj;
            for (Object ruleObj : group.getJsonArray("rules", new JsonArray())) {
                JsonObject rule = (JsonObject) ruleObj;
                if (rule.getString("name").equals(name)) {
                    return rule;
                }
            }
        }
    }
    return null;
}
 
Example 4
Source File: KafkaUserQuotasOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the quotas from existing JSON
 *
 * @param userConfig JSON string with existing userConfig configuration as byte[]
 *
 * @return  Returns the updated JSON without the quotas
 */
protected JsonObject removeQuotasFromJsonUser(byte[] userConfig)   {
    JsonObject json = new JsonObject(new String(userConfig, StandardCharsets.UTF_8));

    validateJsonVersion(json);
    JsonObject config = json.getJsonObject("config");
    if (config == null) {
        json.put("config", new JsonObject());
    } else {
        if (config.getString("producer_byte_rate") != null) {
            config.remove("producer_byte_rate");
        }
        if (config.getString("consumer_byte_rate") != null) {
            config.remove("consumer_byte_rate");
        }
        if (config.getString("request_percentage") != null) {
            config.remove("request_percentage");
        }
    }
    return json;
}
 
Example 5
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void getBlockByNumberForPending() throws Exception {
  final String id = "123";
  final RequestBody body =
      RequestBody.create(
          JSON,
          "{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(id)
              + ",\"method\":\"eth_getBlockByNumber\", \"params\": [\"pending\",true]}");

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    assertThat(resp.code()).isEqualTo(200);
    // Check general format of result
    final String respBody = resp.body().string();
    final JsonObject json = new JsonObject(respBody);
    testHelper.assertValidJsonRpcResult(json, id);
    // Check result
    final JsonObject result = json.getJsonObject("result");
    assertThat(result).isNull();
  }
}
 
Example 6
Source File: GetResult.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
public GetResult(JsonObject jsonObject) {
    this.index = jsonObject.getString(JSON_FIELD_INDEX);
    this.type = jsonObject.getString(JSON_FIELD_TYPE);
    this.id = jsonObject.getString(JSON_FIELD_ID);
    this.version = jsonObject.getLong(JSON_FIELD_VERSION);
    this.exists = jsonObject.getBoolean(JSON_FIELD_EXISTS);
    this.source = jsonObject.getJsonObject(JSON_FIELD_SOURCE);

    final JsonObject jsonFields = jsonObject.getJsonObject(JSON_FIELD_FIELDS);
    if (jsonFields != null) {
        for (String fieldName : jsonFields.fieldNames()) {
            final List<Object> fieldValues = new LinkedList<>();
            jsonFields.getJsonArray(fieldName).stream().forEach(e -> fieldValues.add(e));
            this.fields.put(fieldName, fieldValues);
        }
    }
}
 
Example 7
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 8
Source File: PipelineExecutioner.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
/**
 * Perform json inference using the given {@link JsonObject}
 *  containing 2 objects: a schema and values
 *  and if a {@link RoutingContext} is provided, it will also
 *  write the result as a response
 * @param jsonBody the input
 * @param ctx the context
 */
public Record[] doJsonInference(JsonObject jsonBody,RoutingContext ctx) {
    JsonObject schema = jsonBody.getJsonObject("schema");
    JsonObject values = jsonBody.getJsonObject("values");
    Preconditions.checkState(schema.fieldNames().equals(values.fieldNames()),"Schema and Values must be the same field names!");
    Record[] pipelineInput = new Record[schema.fieldNames().size()];
    int count = 0;
    for(String key : schema.fieldNames()) {
        JsonObject schemaJson = schema.getJsonObject(key);
        JsonObject recordAsJson = values.getJsonObject(key);
        Record record = JsonSerdeUtils.createRecordFromJson(recordAsJson, schemaJson);
        pipelineInput[count] = record;
        count++;
    }


    Preconditions.checkNotNull(pipeline,"Pipeline must not be null!");
    Record[] records = pipeline.doPipeline(pipelineInput);
    JsonObject writeJson = JsonSerdeUtils.convertRecords(records,outputNames());
    if(ctx != null) {
        ctx.response().putHeader("Content-Type", "application/json");
        Buffer buffer = writeJson.toBuffer();
        ctx.response().putHeader("Content-Length", String.valueOf(buffer.length()));
        ctx.response().end(buffer);
    }

    return records;
}
 
Example 9
Source File: KubeAuthApi.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Override
public io.enmasse.api.auth.SubjectAccessReview performSubjectAccessReviewPath(TokenReview tokenReview, String path, String verb) {
    if (client.isAdaptable(OkHttpClient.class)) {
        JsonObject body = new JsonObject();

        body.put("kind", "SubjectAccessReview");
        body.put("apiVersion", "authorization.k8s.io/v1");

        JsonObject spec = new JsonObject();

        JsonObject nonResourceAttributes = new JsonObject();
        nonResourceAttributes.put("path", path);
        nonResourceAttributes.put("verb", verb);

        spec.put("nonResourceAttributes", nonResourceAttributes);

        putCommonSpecAttributes(spec, tokenReview);

        body.put("spec", spec);
        log.debug("Subject access review request: {}", body);
        JsonObject responseBody = doRawHttpRequest("/apis/authorization.k8s.io/v1/subjectaccessreviews", "POST", body, false);

        log.debug("Subject access review response: {}", responseBody);
        JsonObject status = responseBody.getJsonObject("status");
        boolean allowed = false;
        if (status != null) {
            Boolean allowedMaybe = status.getBoolean("allowed");
            allowed = allowedMaybe == null ? false : allowedMaybe;
        }
        return new io.enmasse.api.auth.SubjectAccessReview(tokenReview.getUserName(), allowed);
    } else {
        return new SubjectAccessReview(tokenReview.getUserName(), false);
    }
}
 
Example 10
Source File: GenesisFileModule.java    From besu with Apache License 2.0 5 votes vote down vote up
private static GenesisFileModule createGenesisModule(final String genesisConfig) {
  // duplicating work from JsonGenesisConfigOptions, but in a refactoring this goes away.
  final JsonObject genesis = new JsonObject(genesisConfig);
  final JsonObject config = genesis.getJsonObject("config");
  if (config.containsKey("ethash")) {
    return new MainnetGenesisFileModule(genesisConfig);
  } else if (config.containsKey("ibft")) {
    return new IBFTGenesisFileModule(genesisConfig);
  } else if (config.containsKey("clique")) {
    return new CliqueGenesisFileModule(genesisConfig);
  } else {
    // default is mainnet
    return new MainnetGenesisFileModule(genesisConfig);
  }
}
 
Example 11
Source File: GetResponse.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
public GetResponse(JsonObject json) {
    super(json);

    final JsonObject jsonResult = json.getJsonObject(JSON_FIELD_RESULT);
    if (jsonResult != null) {
        this.result = new GetResult(jsonResult);
    }
}
 
Example 12
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void getBlockByNumberForEarliest() throws Exception {
  // Setup mocks to return a block
  final BlockDataGenerator gen = new BlockDataGenerator();
  final Block block = gen.genesisBlock();
  final BlockWithMetadata<TransactionWithMetadata, Hash> blockWithMetadata =
      blockWithMetadata(block);
  when(blockchainQueries.blockByNumber(eq(BlockHeader.GENESIS_BLOCK_NUMBER)))
      .thenReturn(Optional.of(blockWithMetadata));

  final String id = "123";
  final RequestBody body =
      RequestBody.create(
          JSON,
          "{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(id)
              + ",\"method\":\"eth_getBlockByNumber\", \"params\": [\"earliest\",true]}");

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    assertThat(resp.code()).isEqualTo(200);
    // Check general format of result
    final String respBody = resp.body().string();
    final JsonObject json = new JsonObject(respBody);
    testHelper.assertValidJsonRpcResult(json, id);
    // Check result
    final JsonObject result = json.getJsonObject("result");
    verifyBlockResult(block, blockWithMetadata.getTotalDifficulty(), result, false);
  }
}
 
Example 13
Source File: BulkOperation.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
/**
 * Json constructor
 * 
 * @param json
 *          the json object
 */
public BulkOperation(JsonObject json) {
  String typeValue = json.getString("type");
  if (typeValue != null)
    this.type = BulkOperationType.valueOf(typeValue.toUpperCase());
  filter = json.getJsonObject("filter");
  document = json.getJsonObject("document");
  upsert = json.getBoolean("upsert");
  multi = json.getBoolean("multi");
}
 
Example 14
Source File: MetadataHandlerTest.java    From vertx-starter with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnStarterMetadata(Vertx vertx, VertxTestContext testContext) throws IOException {
  JsonObject starterData = Util.loadStarterData();

  JsonObject defaults = starterData.getJsonObject("defaults");
  JsonArray versions = starterData.getJsonArray("versions");
  JsonArray stack = starterData.getJsonArray("stack");

  Router router = Router.router(vertx);
  router.route().handler(new MetadataHandler(defaults, versions, stack));

  vertx.createHttpServer(new HttpServerOptions().setPort(0))
    .requestHandler(router)
    .listen(testContext.succeeding(server -> {

      WebClient webClient = WebClient.create(vertx, new WebClientOptions().setDefaultPort(server.actualPort()));
      webClient.get("/")
        .send(testContext.succeeding(response -> testContext.verify(() -> {

          assertThat(response.statusCode()).withFailMessage(response.bodyAsString()).isEqualTo(200);

          JsonObject metadata = response.bodyAsJsonObject();
          assertThat(metadata.getJsonObject("defaults")).isEqualTo(defaults);
          assertThat(metadata.getJsonArray("versions")).isEqualTo(versions);
          assertThat(metadata.getJsonArray("stack")).isEqualTo(stack);
          assertThat(metadata.getJsonArray("buildTools")).contains("maven", "gradle");
          assertThat(metadata.getJsonArray("languages")).contains("java", "kotlin");
          assertThat(metadata.getJsonArray("jdkVersions")).contains("1.8", "11", "13");
          assertThat(metadata.getJsonArray("vertxDependencies")).isEqualTo(stack);
          assertThat(metadata.getJsonArray("vertxVersions")).isEqualTo(versions.stream()
            .map(JsonObject.class::cast)
            .map(obj -> obj.getString("number"))
            .collect(JsonArray::new, JsonArray::add, JsonArray::addAll));

          testContext.completeNow();

        })));
    }));
}
 
Example 15
Source File: TestData.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
boolean checkLinkUrls(List<String> expected, JsonObject body) {
  if (body.containsKey("errors")) {
    return false;
  }
  JsonObject data = body.getJsonObject("data");
  List<String> urls = data.getJsonArray("allLinks").stream()
    .map(JsonObject.class::cast)
    .map(json -> json.getString("url"))
    .collect(toList());
  return expected.equals(urls);
}
 
Example 16
Source File: RPCChannel.java    From kyoko with MIT License 4 votes vote down vote up
public Message(JsonObject payload) {
    this(payload.getLong("id"), payload.getJsonObject("payload"));
}
 
Example 17
Source File: TestSetChainParams.java    From besu with Apache License 2.0 4 votes vote down vote up
private static String modifyGenesisFile(final String initialGenesis) {
  final JsonObject chainParamsJson = new JsonObject(initialGenesis);
  final JsonObject config = new JsonObject();
  chainParamsJson.put("config", config);
  final JsonObject params = chainParamsJson.getJsonObject("params");
  final JsonObject genesis = chainParamsJson.getJsonObject("genesis");

  // Whether sealEngine is NoProof, Ethash, or NoReward the genesis file is the same
  final JsonObject ethash = new JsonObject();
  config.put("ethash", ethash);

  maybeMoveToNumber(params, "homesteadForkBlock", config, "homesteadBlock");
  maybeMoveToNumber(params, "EIP150ForkBlock", config, "eip150Block");
  maybeMoveToNumber(params, "EIP158ForkBlock", config, "eip158Block");
  maybeMoveToNumber(params, "byzantiumForkBlock", config, "byzantiumBlock");
  maybeMoveToNumber(params, "constantinopleForkBlock", config, "constantinopleBlock");
  maybeMoveToNumber(params, "constantinopleFixForkBlock", config, "constantinopleFixBlock");
  maybeMoveToNumber(params, "istanbulForkBlock", config, "istanbulBlock");
  maybeMoveToNumber(params, "muirGlacierForkBlock", config, "muirGlacierBlock");
  maybeMoveToNumber(params, "berlinForkBlock", config, "berlinBlock");
  maybeMoveToNumber(params, "chainID", config, "chainId", 1);
  maybeMove(genesis, "author", chainParamsJson, "coinbase");
  maybeMove(genesis, "difficulty", chainParamsJson, "difficulty");
  maybeMove(genesis, "extraData", chainParamsJson, "extraData");
  maybeMove(genesis, "gasLimit", chainParamsJson, "gasLimit");
  maybeMove(genesis, "mixHash", chainParamsJson, "mixHash");
  maybeMove(genesis, "nonce", chainParamsJson, "nonce");
  maybeMove(genesis, "timestamp", chainParamsJson, "timestamp");
  maybeMove(chainParamsJson, "accounts", chainParamsJson, "alloc");

  // strip out precompiles with zero balance
  final JsonObject alloc = chainParamsJson.getJsonObject("alloc");
  final Iterator<String> fieldNamesIter = alloc.fieldNames().iterator();
  while (fieldNamesIter.hasNext()) {
    final String address = fieldNamesIter.next();
    final JsonObject account = alloc.getJsonObject(address);
    if (account.containsKey("precompiled") && !account.containsKey("balance")) {
      fieldNamesIter.remove();
    }
  }

  return chainParamsJson.encodePrettily();
}
 
Example 18
Source File: MetricsExamples.java    From vertx-dropwizard-metrics with Apache License 2.0 4 votes vote down vote up
public void naming1(Vertx vertx, MetricsService metricsService) {
  JsonObject metrics = metricsService.getMetricsSnapshot(vertx);
  metrics.getJsonObject("vertx.eventbus.handlers");
}
 
Example 19
Source File: SchemaTypeUtils.java    From konduit-serving with Apache License 2.0 4 votes vote down vote up
/**
 * Create a {@link Schema} from a {@link JsonObject}
 *  schema descriptor. The schema descriptor contains a json object of keys
 *  of type {@link ColumnType} values in the form of:
 *  name : {@link ColumnType} value
 *
 * There are 2 exceptions to this rule.
 * {@link ColumnType#NDArray} and {@link ColumnType#Categorical}
 * both are json objects.
 * {@link ColumnType#NDArray} has the form:
 * {name : shape: [], serialization type: "json" | "b64"}
 * {@link ColumnType#Categorical} has the form:
 * {categories: []}
 * {@link ColumnType#Time} has the form:
 * {timeZoneId: timeZoneId}
 *
 *
 * @param schemaDescriptor a {@link JsonObject} with the form
 *                         described above
 * @return the equivalent {@link Schema} derived from the given descriptor
 */
public static Schema schemaFromDynamicSchemaDefinition(JsonObject schemaDescriptor) {
    Schema.Builder schemaBuilder = new Builder();
    for(String key : schemaDescriptor.fieldNames()) {
        JsonObject fieldInfo = schemaDescriptor.getJsonObject(key);
        JsonObject fieldInfoObject = fieldInfo.getJsonObject("fieldInfo");
        if(fieldInfoObject == null) {
            throw new IllegalArgumentException("Unable to find object fieldInfo!");
        }

        if(!fieldInfoObject.containsKey("type")) {
            throw new IllegalArgumentException("Illegal field info. Missing key type for identifying type of field");
        }
        //convert image to bytes and let user pre process accordingly
        String type = fieldInfoObject.getString("type");
        if(type.equals("Image")) {
            type = "Bytes";
        }
        switch(ColumnType.valueOf(type)) {
            case Boolean:
                schemaBuilder.addColumnBoolean(key);
                break;
            case Double:
                schemaBuilder.addColumnDouble(key);
                break;
            case Float:
                schemaBuilder.addColumnFloat(key);
                break;
            case Long:
                schemaBuilder.addColumnLong(key);
                break;
            case String:
                schemaBuilder.addColumnString(key);
                break;
            case Integer:
                schemaBuilder.addColumnInteger(key);
                break;
            case NDArray:
                JsonArray shapeArr = fieldInfoObject.getJsonArray("shape");
                long[] shape = new long[shapeArr.size()];
                for(int i = 0; i < shape.length; i++) {
                    shape[i] = shapeArr.getLong(i);
                }
                schemaBuilder.addColumnNDArray(key,shape);
                break;
            case Categorical:
                JsonArray jsonArray = fieldInfoObject.getJsonArray("categories");
                String[] categories = new String[jsonArray.size()];
                for(int i = 0; i < categories.length; i++) {
                    categories[i] = jsonArray.getString(i);
                }
                schemaBuilder.addColumnCategorical(key,categories);
                break;
            case Bytes:
                ColumnMetaData columnMetaData = new BinaryMetaData(key);
                schemaBuilder.addColumn(columnMetaData);
                break;
            case Time:
                TimeZone zoneById = TimeZone.getTimeZone(fieldInfoObject.getString("timeZoneId"));
                schemaBuilder.addColumnTime(key,zoneById);
                break;

        }
    }

    return schemaBuilder.build();
}
 
Example 20
Source File: AndroidSafetynetAttestation.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
@Override
public void verify(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject ctapMakeCredResp, AuthenticatorData authr) throws AttestationException {

  try {
    JsonObject attStmt = ctapMakeCredResp.getJsonObject("attStmt");

    JsonObject token = JWT.parse(ub64dec.decode(attStmt.getString("response")));

    /* ----- Verify payload ----- */
    byte[] clientDataHashBuf = hash(clientDataJSON);

    Buffer nonceBase = Buffer.buffer()
      .appendBytes(authr.getRaw())
      .appendBytes(clientDataHashBuf);

    if (!MessageDigest.isEqual(hash(nonceBase.getBytes()), b64dec.decode(token.getJsonObject("payload").getString("nonce")))) {
      throw new AttestationException("JWS nonce does not contains expected nonce!");
    }

    if (!token.getJsonObject("payload").getBoolean("ctsProfileMatch")) {
      throw new AttestationException("JWS ctsProfileMatch is false!");
    }
    /* ----- Verify payload ENDS ----- */

    /* ----- Verify header ----- */
    JsonArray x5c = token.getJsonObject("header").getJsonArray("x5c");

    if (x5c == null || x5c.size() == 0) {
      throw new AttestationException("Invalid certificate chain");
    }

    // push the root certificate
    x5c.add(ANDROID_SAFETYNET_ROOT);

    List<X509Certificate> certChain = new ArrayList<>();

    for (int i = 0; i < x5c.size(); i++) {
      final X509Certificate c = (X509Certificate) x509.generateCertificate(new ByteArrayInputStream(b64dec.decode(x5c.getString(i))));
      // verify the certificate chain
      c.checkValidity();
      certChain.add(c);
    }

    if (!ATTEST_ANDROID_COM.equals(certChain.get(0).getSubjectX500Principal())) {
      throw new AttestationException("The common name is not set to 'attest.android.com'!");
    }

    validateCertificatePath(certChain);
    /* ----- Verify header ENDS ----- */

    /* ----- Verify signature ----- */
    if (!verifySignature(ub64dec.decode(token.getString("signature")), token.getString("signatureBase").getBytes(), certChain.get(0))) {
      throw new AttestationException("Failed to verify the signature!");
    }
    /* ----- Verify signature ENDS ----- */

  } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
    throw new AttestationException(e);
  }
}