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

The following examples show how to use io.vertx.core.json.JsonObject#toBuffer() . 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: RabbitMQServiceTest.java    From vertx-rabbitmq-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicPublishJson(TestContext ctx) throws Exception {
  String q = setupQueue(ctx, null);
  JsonObject body = new JsonObject().put("foo", randomAlphaString(5)).put("bar", randomInt());
  Buffer message = body.toBuffer();
  AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
    .contentType("application/json")
    .build();
  client.basicPublish("", q, props, message, ctx.asyncAssertSuccess(v -> {
    client.basicGet(q, true, ctx.asyncAssertSuccess(msg -> {
      ctx.assertNotNull(msg);
      JsonObject b = msg.body().toJsonObject();
      ctx.assertNotNull(b);
      ctx.assertFalse(body == b);
      ctx.assertEquals(body, b);
    }));
  }));
}
 
Example 2
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 3
Source File: SigfoxProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Buffer convertToResponsePayload(final Command command) {
    final JsonObject payload = new JsonObject();

    payload.put(command.getDeviceId(),
            new JsonObject()
                    .put(DOWNLINK_DATA_FIELD,
                            BaseEncoding
                                    .base16()
                                    .encode(command.getPayload().getBytes())
                                    .toLowerCase()));

    return payload.toBuffer();
}
 
Example 4
Source File: MessageSendTester.java    From enmasse with Apache License 2.0 5 votes vote down vote up
/**
 * Fill up the message with extra payload to get an exact payload size (in bytes).
 * <p>
 * If the payload size if greater than zero, it will always requires {@link #FIXED_JSON_EXTRA_SIZE}
 * of bytes remaining for an empty object and {@link #FIXED_JSON_EXTRA_SIZE} plus one for an object
 * which already contains a field.
 *
 * @param payload The payload to modify.
 * @param payloadSize The target payload size. If this is zero or less, this operation is a no-op.
 * @throws IllegalArgumentException if the target payload size is lower than the already provided
 *         payload.
 */
static Buffer fillWithPayload(final JsonObject payload, final int payloadSize) {

    final Buffer buffer = payload.toBuffer();

    if (payloadSize <= 0) {
        return buffer;
    }

    // if the object is empty, there will be no extra comma
    final int extraComma = payload.isEmpty() ? 0 : 1;
    final int actualSize = buffer.length();
    final int fixed = FIXED_JSON_EXTRA_SIZE + extraComma;

    if (actualSize + fixed > payloadSize) {
        // we are already "too big"
        throw new IllegalArgumentException(String.format("Provided payload size already exceeds maximum (actual: %d + %d, target: %d)",
                actualSize, fixed, payloadSize));
    }

    final int diff = payloadSize - actualSize - fixed;
    final char[] fill = new char[diff];
    Arrays.fill(fill, 'a');
    payload.put("extra", String.valueOf(fill));

    return payload.toBuffer();
}
 
Example 5
Source File: GraphQLRequest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Buffer getJsonBody() {
  JsonObject json = new JsonObject();
  if (graphQLQuery != null) {
    json.put("query", graphQLQuery);
  }
  if (operationName != null) {
    json.put("operationName", operationName);
  }
  if (!variables.isEmpty()) {
    json.put("variables", variables);
  }
  return json.isEmpty() ? null : json.toBuffer();
}
 
Example 6
Source File: KafkaConnectApi.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Future<Map<String, Object>> createOrUpdatePutRequest(
        String host, int port,
        String connectorName, JsonObject configJson) {
    Promise<Map<String, Object>> result = Promise.promise();
    HttpClientOptions options = new HttpClientOptions().setLogActivity(true);
    Buffer data = configJson.toBuffer();
    String path = "/connectors/" + connectorName + "/config";
    log.debug("Making PUT request to {} with body {}", path, configJson);
    vertx.createHttpClient(options)
            .put(port, host, path, response -> {
                response.exceptionHandler(error -> {
                    result.fail(error);
                });
                if (response.statusCode() == 200 || response.statusCode() == 201) {
                    response.bodyHandler(buffer -> {
                        ObjectMapper mapper = new ObjectMapper();
                        try {
                            Map t = mapper.readValue(buffer.getBytes(), Map.class);
                            log.debug("Got {} response to PUT request to {}: {}", response.statusCode(), path, t);
                            result.complete(t);
                        } catch (IOException e) {
                            result.fail(new ConnectRestException(response, "Could not deserialize response: " + e));
                        }
                    });
                } else {
                    // TODO Handle 409 (Conflict) indicating a rebalance in progress
                    log.debug("Got {} response to PUT request to {}", response.statusCode(), path);
                    response.bodyHandler(buffer -> {
                        JsonObject x = buffer.toJsonObject();
                        result.fail(new ConnectRestException(response, x.getString("message")));
                    });
                }
            })
            .exceptionHandler(result::fail)
            .setFollowRedirects(true)
            .putHeader("Accept", "application/json")
            .putHeader("Content-Type", "application/json")
            .putHeader("Content-Length", String.valueOf(data.length()))
            .write(data)
            .end();
    return result.future();
}
 
Example 7
Source File: JsonObjectHelper.java    From vertx-config with Apache License 2.0 2 votes vote down vote up
/**
 * Deprecated. {@link JsonObject} now has a {@link JsonObject#toBuffer()} method.
 *
 * @deprecated use {@link JsonObject#toBuffer()} instead
 */
@Deprecated
public static Buffer toBuffer(JsonObject json) {
  return json.toBuffer();
}