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

The following examples show how to use io.vertx.core.json.JsonObject#mapFrom() . 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: TransactionFactory.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
public <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 decoder.decodeValue(receivedParams.toBuffer(), type);
  }
 
Example 2
Source File: TenantTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Encode tenant with a "tracing" value set.
 */
@Test
public void testEncodeTraceSamplingModePerAuthId() {
    final var tenant = new Tenant();
    final TenantTracingConfig tracingConfig = new TenantTracingConfig();
    tracingConfig.setSamplingMode(TracingSamplingMode.ALL);
    tracingConfig.setSamplingModePerAuthId(
            Map.of("authId1", TracingSamplingMode.ALL, "authId2", TracingSamplingMode.DEFAULT));
    tenant.setTracing(tracingConfig);
    final var json = JsonObject.mapFrom(tenant);
    assertNotNull(json);
    final JsonObject tracingConfigJson = json.getJsonObject(RegistryManagementConstants.FIELD_TRACING);
    assertNotNull(tracingConfigJson);
    assertEquals(TracingSamplingMode.ALL.getFieldValue(), tracingConfigJson.getString(RegistryManagementConstants.FIELD_TRACING_SAMPLING_MODE));
    final JsonObject traceSamplingModePerAuthIdJson = tracingConfigJson.getJsonObject(RegistryManagementConstants.FIELD_TRACING_SAMPLING_MODE_PER_AUTH_ID);
    assertNotNull(traceSamplingModePerAuthIdJson);
    assertEquals(TracingSamplingMode.ALL.getFieldValue(), traceSamplingModePerAuthIdJson.getString("authId1"));
    assertEquals(TracingSamplingMode.DEFAULT.getFieldValue(), traceSamplingModePerAuthIdJson.getString("authId2"));
}
 
Example 3
Source File: JmxTransTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testServersDeserialization() {
    JmxTransServer server = new JmxTransServer();

    server.setHost("host");
    server.setPort(9999);
    server.setUsername("username");
    server.setPassword("password");
    server.setQueries(Collections.emptyList());

    JsonObject targetJson = JsonObject.mapFrom(server);

    assertThat(targetJson.getString("host"), is("host"));
    assertThat(targetJson.getInteger("port"), is(9999));
    assertThat(targetJson.getString("username"), is("username"));
    assertThat(targetJson.getString("password"), is("password"));
    assertThat(targetJson.getJsonArray("queries").getList().size(), is(0));
}
 
Example 4
Source File: CredentialsTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test encoding a x509 secret.
 */
@Test
public void testEncodeX509Credential() {
    final X509CertificateCredential credential = new X509CertificateCredential("CN=foo, O=bar");

    final JsonObject json = JsonObject.mapFrom(credential);
    assertNotNull(json);
    assertNull(json.getJsonArray(RegistryManagementConstants.FIELD_SECRETS));

    assertEquals("x509-cert", json.getString(RegistryManagementConstants.FIELD_TYPE));
    assertEquals("CN=foo,O=bar", json.getString(RegistryManagementConstants.FIELD_AUTH_ID));
}
 
Example 5
Source File: DeviceTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Encode device with "enabled=true".
 */
@Test
public void testEncodeEnabled() {
    final var device = new Device();
    device.setEnabled(true);
    final var json = JsonObject.mapFrom(device);
    assertThat(json).isNotNull();
    assertThat(json.getBoolean("enabled")).isTrue();
    assertThat(json.getJsonObject("ext")).isNull();
}
 
Example 6
Source File: MongoDbBasedTenantService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<OperationResult<Id>> processCreateTenant(final String tenantId, final Tenant tenantObj,
        final Span span) {

    final TenantDto newTenantDto = new TenantDto(tenantId, tenantObj,
            new Versioned<>(tenantObj).getVersion());

    // the tenantId is either the device ID provided by the client
    // or a newly created random ID
    TracingHelper.TAG_DEVICE_ID.set(span, tenantId);

    final JsonObject newTenantDtoJson = JsonObject.mapFrom(newTenantDto);
    final Promise<String> createTenantPromise = Promise.promise();
    mongoClient.insert(config.getCollectionName(), newTenantDtoJson, createTenantPromise);
    return createTenantPromise.future()
            .compose(tenantObjectIdResult -> {
                span.log("successfully created tenant");
                return Future.succeededFuture(OperationResult.ok(
                        HttpURLConnection.HTTP_CREATED,
                        Id.of(tenantId),
                        Optional.empty(),
                        Optional.of(newTenantDto.getVersion())));
            })
            .recover(error -> {
                if (MongoDbDeviceRegistryUtils.isDuplicateKeyError(error)) {
                    LOG.debug(
                            "tenant [{}] already exists or an existing tenant uses a certificate authority with the same Subject DN",
                            tenantId, error);
                    TracingHelper.logError(span,
                            "tenant with the given identifier already exists or an existing tenant uses a certificate authority with the same Subject DN",
                            error);
                    return Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_CONFLICT));
                } else {
                    LOG.error("error adding tenant [{}]", tenantId, error);
                    TracingHelper.logError(span, "error adding Tenant", error);
                    return Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_INTERNAL_ERROR));
                }
            });
}
 
Example 7
Source File: JmxTransTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueriesDeserialization() {
    JmxTransOutputWriter outputWriter = new JmxTransOutputWriter();

    outputWriter.setAtClass("class");
    outputWriter.setHost("host");
    outputWriter.setPort(9999);
    outputWriter.setFlushDelayInSeconds(1);
    outputWriter.setTypeNames(Collections.singletonList("SingleType"));

    JmxTransQueries queries = new JmxTransQueries();

    queries.setObj("object");
    queries.setAttr(Collections.singletonList("attribute"));

    queries.setOutputWriters(Collections.singletonList(outputWriter));

    JsonObject targetJson = JsonObject.mapFrom(queries);
    JsonObject outputWriterJson = targetJson.getJsonArray("outputWriters").getJsonObject(0);

    assertThat(targetJson.getString("obj"), is("object"));
    assertThat(targetJson.getJsonArray("attr").size(), is(1));
    assertThat(targetJson.getJsonArray("attr").getString(0), is("attribute"));

    assertThat(outputWriterJson.getString("host"), is("host"));
    assertThat(outputWriterJson.getString("@class"), is("class"));
    assertThat(outputWriterJson.getInteger("port"), is(9999));
    assertThat(outputWriterJson.getInteger("flushDelayInSeconds"), is(1));
    assertThat(outputWriterJson.getJsonArray("typeNames").size(), is(1));
    assertThat(outputWriterJson.getJsonArray("typeNames").getList().get(0), is("SingleType"));
}
 
Example 8
Source File: SecretsTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test encoding a generic credential.
 */
@Test
public void testEncodeGeneric() {

    final GenericSecret secret = new GenericSecret();
    addCommonProperties(secret);
    secret.setAdditionalProperties(Map.of("foo", "bar"));

    final JsonObject json = JsonObject.mapFrom(secret);
    assertCommonProperties(json);
    assertThat(json.getString("foo"), is("bar"));
}
 
Example 9
Source File: TenantServiceImpl.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private Set<X500Principal> anchors(final IoTProject project) {

        if (project != null && project.getStatus() == null
                || project.getStatus().getAccepted() == null
                || project.getStatus().getAccepted().getConfiguration() == null) {

            // no configuration yet
            return Collections.emptySet();

        }

        final JsonObject config = JsonObject.mapFrom(project.getStatus().getAccepted().getConfiguration());
        final JsonArray trustAnchors = config.getJsonArray(TenantConstants.FIELD_PAYLOAD_TRUSTED_CA);
        if (trustAnchors == null) {
            return Collections.emptySet();
        }

        final Set<X500Principal> result = new HashSet<>();

        for (Object value : trustAnchors) {
            if (!(value instanceof JsonObject)) {
                continue;
            }
            final JsonObject trustAnchor = (JsonObject) value;
            if (!trustAnchor.getBoolean(TenantConstants.FIELD_ENABLED, true)) {
                continue;
            }
            final String subjectDn = trustAnchor.getString(TenantConstants.FIELD_PAYLOAD_SUBJECT_DN);
            if (Strings.isNullOrEmpty(subjectDn)) {
                continue;
            }

            result.add(new X500Principal(subjectDn));
        }

        return result;
    }
 
Example 10
Source File: TenantManagementIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a request to register a tenant that contains unsupported properties
 * fails with a 400 status.
 *
 * @param context The Vert.x test context.
 */
@Test
public void testAddTenantFailsForUnknownProperties(final VertxTestContext context) {

    final JsonObject requestBody = JsonObject.mapFrom(new Tenant());
    requestBody.put("unexpected", "property");

    helper.registry.addTenant(
            tenantId,
            requestBody,
            "application/json",
            HttpURLConnection.HTTP_BAD_REQUEST)
        .onComplete(context.completing());
}
 
Example 11
Source File: OrionNode.java    From orion with Apache License 2.0 5 votes vote down vote up
private <T> JsonObject sendRequestToOrion(final T serialisableObject) throws IOException {
  final JsonObject payload = JsonObject.mapFrom(serialisableObject);
  final RequestBody requestBody =
      RequestBody.create(MediaType.parse(HttpContentType.JSON.toString()), payload.encode());

  final Request request = new Request.Builder().url(clientUrl() + "/receive").post(requestBody).build();
  final Response response = httpClient.newCall(request).execute();

  return new JsonObject(response.body().string());
}
 
Example 12
Source File: CredentialsManagementIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verify that a json payload to add credentials that does not contain a {@link CredentialsConstants#FIELD_AUTH_ID}
 * is not accepted and responded with {@link HttpURLConnection#HTTP_BAD_REQUEST}
 * and a non empty error response message.
 *
 * @param context The vert.x test context.
 */
@Test
public void testAddCredentialsFailsForMissingAuthId(final VertxTestContext context) {

    final JsonObject credentials = JsonObject.mapFrom(hashedPasswordCredential);
    credentials.remove(CredentialsConstants.FIELD_AUTH_ID);

    testAddCredentialsWithErroneousPayload(
            context,
            new JsonArray().add(credentials),
            HttpURLConnection.HTTP_BAD_REQUEST);
}
 
Example 13
Source File: DeviceManagementIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a request to register a device that contains unsupported properties
 * fails with a 400 status.
 *
 * @param ctx The vert.x test context
 */
@Test
public void testAddDeviceFailsForUnknownProperties(final VertxTestContext ctx) {

    final JsonObject requestBody = JsonObject.mapFrom(new Device());
    requestBody.put("unexpected", "property");

    registry.registerDevice(
            tenantId,
            deviceId,
            requestBody,
            "application/json",
            HttpURLConnection.HTTP_BAD_REQUEST)
        .onComplete(ctx.completing());
}
 
Example 14
Source File: HttpVerticle.java    From reactive-refarch-cloudformation with Apache License 2.0 5 votes vote down vote up
private void handleTrackingEvent(final RoutingContext routingContext) {

        String userAgent = routingContext.request().getHeader("User-Agent");
        String eventID = routingContext.request().getParam("eventID");

        UUID uuid = UUID.randomUUID();
        TrackingMessage trackingMessage = new TrackingMessage();
        trackingMessage.setMessageId(uuid.toString());
        trackingMessage.setProgramId(eventID);

        JsonObject message = JsonObject.mapFrom(trackingMessage);

        if (null == eventID) {
            sendError(400, routingContext);
        } else {
            eb.send(Constants.CACHE_EVENTBUS_ADDRESS, message, res -> {
                if (res.succeeded()) {
                    JsonObject result = (JsonObject)res.result().body();
                    if (result.isEmpty()) {
                        sendResponse(routingContext, 404, Json.encode("ProgramId not found"));
                    } else {

                        TrackingMessage tmpMsg = Json.decodeValue(result.encode(), TrackingMessage.class);
                        tmpMsg.setUserAgent(userAgent);

                        String enrichedData = Json.encode(tmpMsg);

                        eb.send(Constants.KINESIS_EVENTBUS_ADDRESS, enrichedData);
                        sendResponse(routingContext, 200, enrichedData);
                    }
                } else {
                    LOGGER.error(res.cause());
                    sendResponse(routingContext, 500, res.cause().getMessage());
                }
            });
        }
    }
 
Example 15
Source File: GossipManager.java    From jgossip with Apache License 2.0 4 votes vote down vote up
public Buffer encodeAckMessage(AckMessage ackMessage) {
    Buffer buffer = Buffer.buffer();
    JsonObject ackJson = JsonObject.mapFrom(ackMessage);
    buffer.appendString(GossipMessageFactory.getInstance().makeMessage(MessageType.ACK_MESSAGE, ackJson.encode(), getCluster(), getSelf().ipAndPort()).encode());
    return buffer;
}
 
Example 16
Source File: TenantTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Encode with absent "enabled" flag.
 */
@Test
public void testEncodeDefault() {
    final var json = JsonObject.mapFrom(new Tenant());
    assertThat(json, is(emptyIterable()));
}
 
Example 17
Source File: GossipManager.java    From jgossip with Apache License 2.0 4 votes vote down vote up
private Buffer encodeShutdownMessage() {
    Buffer buffer = Buffer.buffer();
    JsonObject self = JsonObject.mapFrom(getSelf());
    buffer.appendString(GossipMessageFactory.getInstance().makeMessage(MessageType.SHUTDOWN, self.encode(), getCluster(), getSelf().ipAndPort()).encode());
    return buffer;
}
 
Example 18
Source File: User.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
public User(io.gravitee.am.model.User user) {
    this.user = user;
    this.principal = JsonObject.mapFrom(user);
}
 
Example 19
Source File: SomeJsonPojoConverter.java    From vertx-jooq with MIT License 4 votes vote down vote up
@Override
public JsonObject to(SomeJsonPojo userObject) {
    return userObject==null?null:JsonObject.mapFrom(userObject);
}
 
Example 20
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Updates configuration information for a tenant.
 *
 * @param tenantId The tenant to update information for.
 * @param requestPayload The payload to set, as specified by the Tenant management API.
 * @param expectedStatusCode The status code indicating a successful outcome.
 * @return A future indicating the outcome of the operation. The future will succeed if the response contained the
 *         expected status code. Otherwise the future will fail with a {@link org.eclipse.hono.client.ServiceInvocationException}.
 */
public Future<MultiMap> updateTenant(final String tenantId, final Tenant requestPayload,
        final int expectedStatusCode) {

    final String uri = tenantInstanceUri(tenantId);
    final JsonObject payload = JsonObject.mapFrom(requestPayload);
    return httpClient.update(uri, payload, status -> status == expectedStatusCode);
}