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

The following examples show how to use io.vertx.core.json.JsonObject#mapTo() . 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: RpcUtil.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
static <T> T fromRpcRequestToJsonParam(final Class<T> type, final JsonRpcRequest request) {

    final Object object;
    final Object params = request.getParams();
    if (params instanceof List) {
      @SuppressWarnings("unchecked")
      final List<Object> paramList = (List<Object>) params;
      if (paramList.size() != 1) {
        throw new IllegalArgumentException(
            type.getSimpleName()
                + " json Rpc requires a single parameter, request contained "
                + paramList.size());
      }
      object = paramList.get(0);
    } else {
      object = params;
    }

    final JsonObject receivedParams = JsonObject.mapFrom(object);

    return receivedParams.mapTo(type);
  }
 
Example 2
Source File: TrustedCertificateAuthorityTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Decode "trusted-ca" section for a public key.
 */
@Test
public void testDecodeTrustedCAUsingPublicKey() {

    final Instant notBefore = certificate.getNotBefore().toInstant();
    final Instant notAfter = certificate.getNotAfter().toInstant();

    final JsonObject ca = new JsonObject()
            .put(RegistryManagementConstants.FIELD_PAYLOAD_SUBJECT_DN, certificate.getSubjectX500Principal().getName(X500Principal.RFC2253))
            .put(RegistryManagementConstants.FIELD_PAYLOAD_PUBLIC_KEY, certificate.getPublicKey().getEncoded())
            .put(RegistryManagementConstants.FIELD_PAYLOAD_KEY_ALGORITHM, certificate.getPublicKey().getAlgorithm())
            .put(RegistryManagementConstants.FIELD_SECRETS_NOT_BEFORE, DateTimeFormatter.ISO_INSTANT.format(notBefore))
            .put(RegistryManagementConstants.FIELD_SECRETS_NOT_AFTER, DateTimeFormatter.ISO_INSTANT.format(notAfter));

    final TrustedCertificateAuthority authority = ca.mapTo(TrustedCertificateAuthority.class);
    assertThat(authority.isValid()).isTrue();
    assertAuthority(authority);
}
 
Example 3
Source File: TenantStorePostgres.java    From okapi with Apache License 2.0 6 votes vote down vote up
private void updateModuleR(PostgresQuery q, String id,
                           SortedMap<String, Boolean> enabled,
                           Iterator<Row> it, Handler<ExtendedAsyncResult<Void>> fut) {

  if (!it.hasNext()) {
    fut.handle(new Success<>());
    q.close();
    return;
  }
  Row r = it.next();
  String sql = "UPDATE " + TABLE + " SET " + JSON_COLUMN + " = $2 WHERE " + ID_SELECT;
  JsonObject o = (JsonObject) r.getValue(0);
  Tenant t = o.mapTo(Tenant.class);
  t.setEnabled(enabled);
  JsonObject doc = JsonObject.mapFrom(t);
  q.query(sql, Tuple.of(id, doc), res -> {
    if (res.failed()) {
      fut.handle(new Failure<>(ErrorType.INTERNAL, res.cause()));
    } else {
      updateModuleR(q, id, enabled, it, fut);
    }
  });
}
 
Example 4
Source File: TenantTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Decode tenant with a "tracing" property set.
 */
@Test
public void testDecodeTraceSampling() {


    final JsonObject tracingConfigJson = new JsonObject()
            .put(RegistryManagementConstants.FIELD_TRACING_SAMPLING_MODE, TracingSamplingMode.ALL.getFieldValue())
            .put(RegistryManagementConstants.FIELD_TRACING_SAMPLING_MODE_PER_AUTH_ID, new JsonObject()
                    .put("authId1", TracingSamplingMode.ALL.getFieldValue())
                    .put("authId2", TracingSamplingMode.DEFAULT.getFieldValue()));

    final JsonObject tenantJson = new JsonObject();
    tenantJson.put(RegistryManagementConstants.FIELD_TRACING, tracingConfigJson);

    final var tenant = tenantJson.mapTo(Tenant.class);
    assertNotNull(tenant);
    final TenantTracingConfig tracingConfig = tenant.getTracing();
    assertNotNull(tracingConfig);
    assertEquals(TracingSamplingMode.ALL, tracingConfig.getSamplingMode());
    assertEquals(TracingSamplingMode.ALL, tracingConfig.getSamplingModePerAuthId().get("authId1"));
    assertEquals(TracingSamplingMode.DEFAULT, tracingConfig.getSamplingModePerAuthId().get("authId2"));
}
 
Example 5
Source File: CredentialsObjectTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the object can be successfully marshaled to JSON
 * and then unmarshaled back into an object.
 */
@Test
public void testMarshaling() {

    // GIVEN a credentials object with some additional custom data
    final CredentialsObject orig = CredentialsObject.fromClearTextPassword("4711", "my-device", "secret", null, null);
    orig.setProperty("client-id", "MQTT-client-4523653");
    orig.setEnabled(false);

    // WHEN marshaling the object to JSON
    final JsonObject json = JsonObject.mapFrom(orig);
    // and unmarshaling it back into an object
    final CredentialsObject unmarshaled = json.mapTo(CredentialsObject.class);

    // THEN all properties have the same value as in the original object
    assertThat(unmarshaled.getDeviceId()).isEqualTo("4711");
    assertThat(unmarshaled.getAuthId()).isEqualTo("my-device");
    assertThat(unmarshaled.getType()).isEqualTo(CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD);
    assertThat(unmarshaled.isEnabled()).isFalse();
    assertThat(unmarshaled.getProperty("client-id", String.class)).isEqualTo("MQTT-client-4523653");
}
 
Example 6
Source File: TrustedCertificateAuthorityTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the subject DN and key algorithm are
 * derived from a certificate instead of explicitly specified values.
 *
 * @throws CertificateEncodingException if the certificate cannot be encoded.
 */
@Test
public void testDecodeTrustedCAUsingCertAndPublicKey() throws CertificateEncodingException {

    final Instant notBefore = certificate.getNotBefore().toInstant().minus(1, ChronoUnit.DAYS);
    final Instant notAfter = certificate.getNotAfter().toInstant().plus(2, ChronoUnit.DAYS);

    final JsonObject ca = new JsonObject()
            .put(RegistryManagementConstants.FIELD_PAYLOAD_CERT, certificate.getEncoded())
            .put(RegistryManagementConstants.FIELD_PAYLOAD_PUBLIC_KEY, "NOTAKEY".getBytes())
            .put(RegistryManagementConstants.FIELD_PAYLOAD_SUBJECT_DN, "CN=not the right subject")
            .put(RegistryManagementConstants.FIELD_PAYLOAD_KEY_ALGORITHM, "unsupported")
            .put(RegistryManagementConstants.FIELD_SECRETS_NOT_BEFORE, DateTimeFormatter.ISO_INSTANT.format(notBefore))
            .put(RegistryManagementConstants.FIELD_SECRETS_NOT_AFTER, DateTimeFormatter.ISO_INSTANT.format(notAfter));

    final TrustedCertificateAuthority authority = ca.mapTo(TrustedCertificateAuthority.class);
    assertAuthority(authority);
}
 
Example 7
Source File: FileBasedTenantService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void addTenant(final JsonObject tenantToAdd) {

        Optional.ofNullable(tenantToAdd.getValue(TenantConstants.FIELD_PAYLOAD_TRUSTED_CA))
            .filter(JsonObject.class::isInstance)
            .map(JsonObject.class::cast)
            .ifPresent(trustedCas -> tenantToAdd.put(TenantConstants.FIELD_PAYLOAD_TRUSTED_CA, new JsonArray().add(trustedCas)));

        final String tenantId = Optional.ofNullable(tenantToAdd.remove(TenantConstants.FIELD_PAYLOAD_TENANT_ID))
            .filter(String.class::isInstance)
            .map(String.class::cast)
            .orElseThrow(() -> new IllegalArgumentException("tenant has no " + TenantConstants.FIELD_PAYLOAD_TENANT_ID + " property"));
        final Versioned<Tenant> tenant = new Versioned<>(tenantToAdd.mapTo(Tenant.class));
        LOG.debug("loading tenant [{}]", tenantId);
        tenants.put(tenantId, tenant);
    }
 
Example 8
Source File: JsonRpcRequestTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyParametersIsValid() {
  final JsonObject input = new JsonObject();
  input.put("jsonrpc", 2.0);
  input.put("method", "mine");
  input.put("params", emptyList());

  final JsonRpcRequest request = input.mapTo(JsonRpcRequest.class);
  assertThat(request.getParams()).isInstanceOf(List.class);
  @SuppressWarnings("unchecked")
  final List<Object> paramArray = (List<Object>) request.getParams();
  assertThat(paramArray.size()).isZero();
  assertThat(request.getVersion()).isEqualTo("2.0");
  assertThat(request.getMethod()).isEqualTo("mine");
}
 
Example 9
Source File: JsonRpcErrorResponseTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeErrorReportFromWeb3jProvider() {
  final JsonObject jsonObject =
      new JsonObject(
          "{\"jsonrpc\":\"2.0\",\"id\":77,\"error\":{\"code\":-32602,\"message\":\"Invalid params\"}}");
  final JsonRpcErrorResponse response = jsonObject.mapTo(JsonRpcErrorResponse.class);

  assertThat(response.getError().getCode()).isEqualTo(-32602);
}
 
Example 10
Source File: EthSendTransactionJsonParametersTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private <T> JsonRpcRequest wrapParametersInRequest(final T parameters) {
  final JsonObject input = new JsonObject();
  input.put("jsonrpc", 2.0);
  input.put("method", "mine");
  input.put("params", parameters);

  return input.mapTo(JsonRpcRequest.class);
}
 
Example 11
Source File: EeaSendTransactionJsonParametersTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private <T> JsonRpcRequest wrapParametersInRequest(final T parameters) {
  final JsonObject input = new JsonObject();
  input.put("jsonrpc", 2.0);
  input.put("method", "mine");
  input.put("params", parameters);

  return input.mapTo(JsonRpcRequest.class);
}
 
Example 12
Source File: WebSocketRequestHandlerTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void onInvalidJsonRpcParametersExceptionProcessingRequestShouldRespondInvalidParams(
    final TestContext context) {
  final Async async = context.async();

  final JsonObject requestJson = new JsonObject().put("id", 1).put("method", "eth_x");
  final JsonRpcRequestContext expectedRequest =
      new JsonRpcRequestContext(requestJson.mapTo(WebSocketRpcRequest.class));
  when(jsonRpcMethodMock.response(eq(expectedRequest)))
      .thenThrow(new InvalidJsonRpcParameters(""));
  final JsonRpcErrorResponse expectedResponse =
      new JsonRpcErrorResponse(1, JsonRpcError.INVALID_PARAMS);

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

  vertx
      .eventBus()
      .consumer(websocketId)
      .handler(
          msg -> {
            context.assertEquals(Json.encode(expectedResponse), msg.body());
            async.complete();
          })
      .completionHandler(v -> handler.handle(websocketId, requestJson.toString()));

  async.awaitSuccess(WebSocketRequestHandlerTest.VERTX_AWAIT_TIMEOUT_MILLIS);
}
 
Example 13
Source File: TrustedCertificateAuthorityTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Decode "trusted-ca" section for an X.509 certificate.
 *
 * @throws CertificateEncodingException if the certificate cannot be encoded.
 */
@Test
public void testDecodeTrustedCAUsingCert() throws CertificateEncodingException {

    final JsonObject ca = new JsonObject()
            .put(RegistryManagementConstants.FIELD_PAYLOAD_CERT, certificate.getEncoded());

    final TrustedCertificateAuthority authority = ca.mapTo(TrustedCertificateAuthority.class);
    assertThat(authority.isValid()).isTrue();
    assertAuthority(authority);
}
 
Example 14
Source File: TenantObjectTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a JSON string containing custom configuration
 * properties can be deserialized into a {@code TenantObject}.
 */
@Test
public void testDeserializationOfCustomAdapterConfigProperties() {

    final JsonObject defaults = new JsonObject().put("time-to-live", 60);
    final JsonObject deploymentValue = new JsonObject().put("maxInstances", 4);
    final JsonObject adapterConfig = new JsonObject()
            .put(TenantConstants.FIELD_ADAPTERS_TYPE, "custom")
            .put(TenantConstants.FIELD_ENABLED, true)
            .put(TenantConstants.FIELD_EXT, new JsonObject()
                    .put("deployment", deploymentValue));
    final JsonObject config = new JsonObject()
            .put(TenantConstants.FIELD_PAYLOAD_TENANT_ID, "my-tenant")
            .put(TenantConstants.FIELD_ENABLED, true)
            .put("plan", "gold")
            .put(TenantConstants.FIELD_ADAPTERS, new JsonArray().add(adapterConfig))
            .put(TenantConstants.FIELD_PAYLOAD_DEFAULTS, defaults);

    final TenantObject obj = config.mapTo(TenantObject.class);
    assertThat(obj).isNotNull();
    assertThat(obj.getProperty("plan", String.class)).isEqualTo("gold");

    final Adapter adapter = obj.getAdapter("custom");
    assertThat(adapter).isNotNull();
    assertThat(JsonObject.mapFrom(adapter.getExtensions().get("deployment"))).isEqualTo(deploymentValue);

    final JsonObject defaultProperties = obj.getDefaults();
    assertThat(defaultProperties.getInteger("time-to-live")).isEqualTo(60);
}
 
Example 15
Source File: CredentialsTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test encoding a generic secret.
 */
@Test
public void testEncodeGenericCredential() {
    final GenericCredential credential = new GenericCredential("custom-type", "foo");

    final JsonObject json = JsonObject.mapFrom(credential);
    assertThat(json).isNotNull();
    assertThat(json.getJsonArray(RegistryManagementConstants.FIELD_SECRETS)).isNull();

    assertThat(json.getString(RegistryManagementConstants.FIELD_TYPE)).isEqualTo("custom-type");
    final CommonCredential decodedCredential = json.mapTo(CommonCredential.class);
    assertThat(decodedCredential).isInstanceOf(GenericCredential.class);

}
 
Example 16
Source File: TenantTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Decode "trusted-ca" section for an X.509 certificate.
 *
 * @throws CertificateException if the self signed certificate cannot be encoded.
 */
@Test
public void testDecodeTrustedCAUsingCert() throws CertificateException {

    final JsonObject ca = new JsonObject()
            .put(RegistryManagementConstants.FIELD_PAYLOAD_CERT, certificate.getEncoded());
    final JsonObject tenantJson = new JsonObject()
            .put(RegistryManagementConstants.FIELD_PAYLOAD_TRUSTED_CA, new JsonArray().add(ca));

    final Tenant tenant = tenantJson.mapTo(Tenant.class);
    assertTrue(tenant.isValid());
}
 
Example 17
Source File: CredentialsTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test encoding a psk secret.
 */
@Test
public void testEncodePskCredential() {
    final PskCredential credential = new PskCredential("foo");
    credential.setSecrets(List.of(new PskSecret().setKey(new byte[] { 0x00, 0x01 })));

    final JsonObject json = JsonObject.mapFrom(credential);
    assertNotNull(json);
    assertEquals("psk", json.getString(RegistryManagementConstants.FIELD_TYPE));
    assertThat(json.getJsonArray(RegistryManagementConstants.FIELD_SECRETS)).hasSize(1);

    final CommonCredential decodedCredential = json.mapTo(CommonCredential.class);
    assertTrue(decodedCredential instanceof PskCredential);
}
 
Example 18
Source File: TenantTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Encode "resource-limits" section.
 */
@Test
public void testEncodeResourceLimitsDoesNotIncludeDefaultValues() {

    final ResourceLimits limits = new ResourceLimits();
    final JsonObject json = JsonObject.mapFrom(limits);
    assertFalse(json.containsKey(RegistryManagementConstants.FIELD_MAX_CONNECTIONS));
    final ResourceLimits deserializedLimits = json.mapTo(ResourceLimits.class);
    assertThat(deserializedLimits.getMaxConnections(), is(-1));
}
 
Example 19
Source File: SomeJsonPojoConverter.java    From vertx-jooq with MIT License 4 votes vote down vote up
@Override
public SomeJsonPojo from(JsonObject databaseObject) {
    return databaseObject == null?null:databaseObject.mapTo(SomeJsonPojo.class);
}
 
Example 20
Source File: ObjectExchangeTest.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Incoming("from-amqp")
public void consume(JsonObject p) {
    Price price = p.mapTo(Price.class);
    prices.add(price);
}