Java Code Examples for io.vertx.core.json.Json#encode()

The following examples show how to use io.vertx.core.json.Json#encode() . 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: JsonRpcHttpServiceTlsClientAuthTest.java    From besu with Apache License 2.0 6 votes vote down vote up
private void netVersionSuccessful(
    final Supplier<OkHttpClient> okHttpClientSupplier, final String baseUrl) throws Exception {
  final String id = "123";
  final String json =
      "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"net_version\"}";

  final OkHttpClient httpClient = okHttpClientSupplier.get();
  try (final Response response = httpClient.newCall(buildPostRequest(json, baseUrl)).execute()) {

    assertThat(response.code()).isEqualTo(200);
    // Check general format of result
    final ResponseBody body = response.body();
    assertThat(body).isNotNull();
    final JsonObject jsonObject = new JsonObject(body.string());
    testHelper.assertValidJsonRpcResult(jsonObject, id);
    // Check result
    final String result = jsonObject.getString("result");
    assertThat(result).isEqualTo(String.valueOf(CHAIN_ID));
  } catch (final Exception e) {
    e.printStackTrace();
    throw e;
  }
}
 
Example 2
Source File: AbstractDeviceManagementStore.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public Future<UpdateResult> createDevice(final DeviceKey key, final Device device, final SpanContext spanContext) {

        final String json = Json.encode(device);

        final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "create device", getClass().getSimpleName())
                .withTag("tenant_instance_id", key.getTenantId())
                .withTag("device_id", key.getDeviceId())
                .withTag("data", json)
                .start();

        var expanded = this.createStatement.expand(params -> {
            params.put("tenant_id", key.getTenantId());
            params.put("device_id", key.getDeviceId());
            params.put("version", UUID.randomUUID().toString());
            params.put("data", json);
        });

        log.debug("createDevice - statement: {}", expanded);
        var f = expanded.trace(this.tracer, span).update(this.client)
                .recover(SQL::translateException);

        return MoreFutures
                .whenComplete(f, span::finish);
    }
 
Example 3
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static void binaryEncodeJSON(Object value, ByteBuf buff) {
  String s;
  if (value == Tuple.JSON_NULL) {
    s = "null";
  } else {
    s = Json.encode(value);
  }
  buff.writeCharSequence(s, StandardCharsets.UTF_8);
}
 
Example 4
Source File: EeaSendRawTransaction.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public String request() {
  final Request<?, ? extends Response<?>> sendRawTransactionRequest =
      eeaJsonRpc.eeaSendRawTransaction(
          "0xf90110a0e04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f28609184e72a0008276c094d46e8dd67c5d32be8058bb8eb970870f0724456780a9d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f07244567536a00b528cefb87342b2097318cd493d13b4c9bd55bf35bf1b3cf2ef96ee14cee563a06423107befab5530c42a2d7d2590b96c04ee361c868c138b054d7886966121a6aa307837353737393139616535646634393431313830656163323131393635663237356364636533313464ebaa3078643436653864643637633564333262653830353862623865623937303837306630373234343536378a72657374726963746564");
  sendRawTransactionRequest.setId(77);
  return Json.encode(sendRawTransactionRequest);
}
 
Example 5
Source File: EeaSendRawTransaction.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public String request(final String value) {
  final Request<?, ? extends Response<?>> sendRawTransactionRequest =
      eeaJsonRpc.eeaSendRawTransaction(value);
  sendRawTransactionRequest.setId(77);

  return Json.encode(sendRawTransactionRequest);
}
 
Example 6
Source File: UpdateSection.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Return the object o set by setValue(o) encoded as a JSON string. Return null if o is null
 * or if o is neither a JsonObject nor a String nor a primitive type.
 * @return the JSON string
 */
public String getValue() {
  if (value == null) {
    return null;
  }
  if (value instanceof JsonObject) {
    return ((JsonObject) value).encode();
  }
  if (value instanceof String || value.getClass().isPrimitive() || Primitives.isWrapperType(value.getClass())) {
    return Json.encode(value);
  }
  return null;
}
 
Example 7
Source File: SendRawTransaction.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public String request() {
  final Request<?, ? extends Response<?>> sendRawTransactionRequest =
      jsonRpc.ethSendRawTransaction(
          "0xf8b2a0e04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f28609184e72a0008276c094d46e8dd67c5d32be8058bb8eb970870f07244567849184e72aa9d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f07244567535a0f04e0e7b41adea417596550611138a3ec9a452abb6648d734107c53476e76a27a05b826d9e9b4e0dd0e7b8939c102a2079d71cfc27cd6b7bebe5a006d5ad17d780");
  sendRawTransactionRequest.setId(77);

  return Json.encode(sendRawTransactionRequest);
}
 
Example 8
Source File: SendRawTransaction.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public String request(final String value) {
  final Request<?, ? extends Response<?>> sendRawTransactionRequest =
      jsonRpc.ethSendRawTransaction(value);
  sendRawTransactionRequest.setId(77);

  return Json.encode(sendRawTransactionRequest);
}
 
Example 9
Source File: PostgresTable.java    From okapi with Apache License 2.0 5 votes vote down vote up
void insert(T dd, Handler<ExtendedAsyncResult<Void>> fut) {
  PostgresQuery q = pg.getQuery();
  final String sql = "INSERT INTO " + table + "(" + jsonColumn + ") VALUES ($1::JSONB)";
  String s = Json.encode(dd);
  JsonObject doc = new JsonObject(s);
  q.query(sql, Tuple.of(doc), res -> {
    if (res.failed()) {
      fut.handle(new Failure<>(res.getType(), res.cause()));
      return;
    }
    q.close();
    fut.handle(new Success<>());
  });
}
 
Example 10
Source File: TransactionCountResponder.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
protected String generateTransactionCountResponse(final JsonRpcRequestId id) {
  final JsonRpcSuccessResponse response =
      new JsonRpcSuccessResponse(id.getValue(), "0x" + nonce.toString());
  LOG.debug("Responding with Nonce of {}", nonce.toString());

  return Json.encode(response);
}
 
Example 11
Source File: ProxyIntegrationTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
void requestReturningErrorIsProxied() {
  final String ethProtocolVersionRequest = Json.encode(jsonRpc().ethProtocolVersion());

  setUpEthNodeResponse(
      request.ethNode(ethProtocolVersionRequest),
      response.ethNode("Not Found", HttpResponseStatus.NOT_FOUND));

  sendPostRequestAndVerifyResponse(
      request.ethSigner(ethProtocolVersionRequest),
      response.ethSigner("Not Found", HttpResponseStatus.NOT_FOUND));

  verifyEthNodeReceived(ethProtocolVersionRequest);
}
 
Example 12
Source File: SendRawTransaction.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
public String response(final String value) {
  final Response<String> sendRawTransactionResponse = new EthSendTransaction();
  sendRawTransactionResponse.setResult(value);
  return Json.encode(sendRawTransactionResponse);
}
 
Example 13
Source File: ResultFormatObj.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
public String toJsonStr() {
	return Json.encode(this);
}
 
Example 14
Source File: VxApi.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Override
public String body() {
    return Json.encode(api);
}
 
Example 15
Source File: CredentialsRegistryClient.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public void setCredentials(final String tenantId, final String deviceId, int expectedStatusCode, final List<CommonCredential> credentials) throws Exception {
    var requestPath = String.format("/%s/%s/%s", CREDENTIALS_PATH, tenantId, deviceId);
    fixInstants(credentials);
    var body = Json.encode(credentials.toArray(CommonCredential[]::new)); // jackson needs an array
    execute(HttpMethod.PUT, requestPath, body, expectedStatusCode, "Error setting credentials to device");
}
 
Example 16
Source File: TableManagementStore.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Future<Boolean> setCredentials(final DeviceKey key, final List<CommonCredential> credentials, final Optional<String> resourceVersion,
        final SpanContext spanContext) {

    final String json = Json.encode(credentials.toArray(CommonCredential[]::new));

    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "set credentials", getClass().getSimpleName())
            .withTag("tenant_instance_id", key.getTenantId())
            .withTag("device_id", key.getDeviceId())
            .withTag("data", json)
            .start();

    resourceVersion.ifPresent(version -> span.setTag("version", version));

    final String nextVersion = UUID.randomUUID().toString();

    final Promise<SQLConnection> promise = Promise.promise();
    this.client.getConnection(promise);

    return promise.future()

            // disable autocommit, which is enabled by default
            .flatMap(connection -> SQL.setAutoCommit(this.tracer, span.context(), connection, false))

            // read the device "for update", locking the entry
            .flatMap(connection -> readDeviceForUpdate(connection, key, resourceVersion, span)

                    // check if we got back a result, if not this will abort early
                    .flatMap(TableManagementStore::extractVersionForUpdate)

                    // take the version and start processing on
                    .flatMap(version -> this.deleteAllCredentialsStatement

                            // delete the existing entries
                            .expand(map -> {
                                map.put("tenant_id", key.getTenantId());
                                map.put("device_id", key.getDeviceId());
                            })
                            .trace(this.tracer, span).update(connection)

                            // then create new entries
                            .flatMap(x -> CompositeFuture.all(credentials.stream()
                                    .map(JsonObject::mapFrom)
                                    .filter(c -> c.containsKey("type") && c.containsKey("auth-id"))
                                    .map(c -> this.insertCredentialEntryStatement
                                            .expand(map -> {
                                                map.put("tenant_id", key.getTenantId());
                                                map.put("device_id", key.getDeviceId());
                                                map.put("type", c.getString("type"));
                                                map.put("auth_id", c.getString("auth-id"));
                                                map.put("data", c.toString());
                                            })
                                            .trace(this.tracer, span).update(connection))
                                    .collect(Collectors.toList())).map(x))

                            // update the version, this will release the lock
                            .flatMap(x -> this.updateDeviceVersionStatement
                                    .expand(map -> {
                                        map.put("tenant_id", key.getTenantId());
                                        map.put("device_id", key.getDeviceId());
                                        map.put("expected_version", version);
                                        map.put("next_version", nextVersion);
                                    })
                                    .trace(this.tracer, span).update(connection)

                                    // check the update outcome
                                    .flatMap(updateResult -> checkUpdateOutcome(updateResult)))

                    )

                    // commit or rollback ... return original result
                    .flatMap(x -> SQL.commit(this.tracer, span.context(), connection).map(true))
                    .recover(x -> SQL.rollback(this.tracer, span.context(), connection).flatMap(y -> Future.<Boolean>failedFuture(x)))

                    // close the connection
                    .onComplete(x -> connection.close()))

            // when not found, then return "false"
            .recover(err -> recoverNotFound(span, err, () -> false))

            .onComplete(x -> span.finish());

}
 
Example 17
Source File: InstanceCacheChecker.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
protected InstanceCacheResult check(MicroserviceVersions microserviceVersions) {
  InstanceCacheResult instanceCacheResult = new InstanceCacheResult();
  instanceCacheResult.setAppId(microserviceVersions.getAppId());
  instanceCacheResult.setMicroserviceName(microserviceVersions.getMicroserviceName());
  instanceCacheResult.setPulledInstances(microserviceVersions.getPulledInstances());

  MicroserviceInstances microserviceInstances = RegistryUtils
      .findServiceInstances(microserviceVersions.getAppId(),
          microserviceVersions.getMicroserviceName(),
          DefinitionConst.VERSION_RULE_ALL,
          null);
  if (microserviceInstances == null) {
    instanceCacheResult.setStatus(Status.UNKNOWN);
    instanceCacheResult.setDetail("failed to find instances from service center");
    return instanceCacheResult;
  }
  if (microserviceInstances.isMicroserviceNotExist()) {
    // no problem, will be deleted from MicroserviceManager in next pull
    instanceCacheResult.setStatus(Status.UNKNOWN);
    instanceCacheResult.setDetail("microservice is not exist anymore, will be deleted from memory in next pull");
    return instanceCacheResult;
  }

  if (!Objects.equals(microserviceInstances.getRevision(), microserviceVersions.getRevision())) {
    // maybe not pull, wait for next pull we get the same revision
    instanceCacheResult.setStatus(Status.UNKNOWN);
    instanceCacheResult.setDetail(String.format(
        "revision is different, will be synchronized in next pull. local revision=%s, remote revision=%s",
        microserviceVersions.getRevision(), microserviceInstances.getRevision()));
    // better to change revision and more likely to find the correct instances in next pull.
    microserviceVersions.setRevision(null);
    return instanceCacheResult;
  }

  // compare all instances
  List<MicroserviceInstance> remoteInstances = microserviceInstances.getInstancesResponse().getInstances();
  remoteInstances.sort(Comparator.comparing(MicroserviceInstance::getInstanceId));
  String local = Json.encode(microserviceVersions.getPulledInstances());
  String remote = Json.encode(remoteInstances);
  if (local.equals(remote)) {
    instanceCacheResult.setStatus(Status.NORMAL);
    return instanceCacheResult;
  }

  LOGGER.error("instance cache not match. appId={}, microservice={}.\n"
          + "local cache: {}\n"
          + "remote cache: {}",
      microserviceVersions.getAppId(),
      microserviceVersions.getMicroserviceName(),
      local,
      remote);
  instanceCacheResult.setStatus(Status.ABNORMAL);
  instanceCacheResult.setDetail("instance cache not match");

  // auto fix, will do a full pull request when invoke MicroserviceVersions.pullInstances
  microserviceVersions.setRevision(null);

  return instanceCacheResult;
}
 
Example 18
Source File: PersonCodec.java    From vertx-camel-bridge with Apache License 2.0 4 votes vote down vote up
@Override
public void encodeToWire(Buffer buffer, Person person) {
  String encoded = Json.encode(person);
  buffer.appendInt(encoded.length());
  buffer.appendString(encoded);
}
 
Example 19
Source File: EthRequestFactory.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
public EthSignerRequest ethSigner(final Request<?, ?> request) {
  return new EthSignerRequest(NO_HEADERS, Json.encode(request));
}
 
Example 20
Source File: SpringMVCObjectRestSchemaRestOnly.java    From servicecomb-java-chassis with Apache License 2.0 3 votes vote down vote up
/**
 * Request body doesn't carry a certain fields, and will not overwrite the default field value of
 * provider param definition.
 * <p/>
 * There are two test cases:
 * <ul>
 *   <li>consumer invoke provider directly</li>
 *   <li>consumer invoke provider via EdgeService</li>
 * </ul>
 *
 */
@PostMapping("testNullFieldAndDefaultValue")
public TestNullFieldAndDefaultValueParam testNullFieldAndDefaultValue(
    @RequestBody TestNullFieldAndDefaultValueParam request) {
  String jsonRequest = Json.encode(request);
  request.setRawRequest(jsonRequest);
  LOGGER.info("return testNullFieldAndDefaultValue response: {}", request);
  LOGGER.info("raw json is {}", Json.encode(request));
  return request;
}