io.vertx.core.json.Json Java Examples

The following examples show how to use io.vertx.core.json.Json. 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: VertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void customizeDownstreamMessage(final Message downstreamMessage, final MqttContext ctx) {

    final Object additionalProperties = ctx.get(MAPPER_DATA);
    if (additionalProperties instanceof Map) {
        ((Map<Object, Object>) additionalProperties).entrySet().stream()
            .filter(entry -> entry.getKey() instanceof String)
            .forEach(entry -> {
                final String key = (String) entry.getKey();
                final Object value = entry.getValue();
                if (value instanceof String) {
                    // prevent quotes around strings
                    MessageHelper.addProperty(downstreamMessage, key, value);
                } else {
                    MessageHelper.addProperty(downstreamMessage, key, Json.encode(value));
                }
            });
    }
}
 
Example #2
Source File: JDBCSpaceConfigClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Override
public void getSpace(Marker marker, String spaceId, Handler<AsyncResult<Space>> handler) {
  SQLQuery query = new SQLQuery(String.format("SELECT config FROM %s WHERE id = ?", SPACE_TABLE), spaceId);
  client.queryWithParams(query.text(), new JsonArray(query.parameters()), out -> {
    if (out.succeeded()) {
      Optional<String> config = out.result().getRows().stream().map(r -> r.getString("config")).findFirst();
      if (config.isPresent()) {
        Space space = Json.decodeValue(config.get(), Space.class);
        handler.handle(Future.succeededFuture(space));
      } else {
        handler.handle(Future.succeededFuture(null));
      }
    } else {
      handler.handle(Future.failedFuture(out.cause()));
    }
  });
}
 
Example #3
Source File: PetApiHandler.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void addPet(RoutingContext routingContext) {
    logger.info("addPet()");
    HttpServerResponse response = routingContext.response();

    Single.defer( () -> {

        String jsonString = routingContext.getBodyAsString();
        Pet pet = jsonString == null ? null : Json.decodeValue(jsonString, new TypeReference<Pet>(){});
        logger.info("Parameter pet is {}", pet);
        return apiImpl.addPet(pet);
    })
    .subscribe(
        apiResponse -> {
            response.setStatusCode(apiResponse.getStatusCode())
                    .end(Json.encodePrettily(apiResponse.getData()));
        }, error -> {
            if (error instanceof ApiException) {
                ApiException apiException = (ApiException) error;
                response.setStatusCode(apiException.getStatusCode()).end(apiException.getMessage());
            } else {
                response.setStatusCode(500).end(error.getMessage());
            }
        }).dispose();
}
 
Example #4
Source File: WebSocketRequestHandlerTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void jsonDecodeFailureShouldRespondInvalidRequest(final TestContext context) {
  final Async async = context.async();

  final JsonRpcErrorResponse expectedResponse =
      new JsonRpcErrorResponse(null, JsonRpcError.INVALID_REQUEST);

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

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

  async.awaitSuccess(VERTX_AWAIT_TIMEOUT_MILLIS);
}
 
Example #5
Source File: ValidationHandlerTest.java    From vertx-starter with Apache License 2.0 6 votes vote down vote up
private void doTest(Vertx vertx, VertxTestContext testContext, ValidationHandler validator, MultiMap params, String extension, Handler<HttpResponse<Buffer>> handler) {
  Router router = Router.router(vertx);
  router.route().handler(validator).handler(rc -> {
    VertxProject vertProject = rc.get(WebVerticle.VERTX_PROJECT_KEY);
    rc.response().end(Json.encodePrettily(vertProject));
  });

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

      WebClientOptions options = new WebClientOptions().setDefaultPort(server.actualPort());
      WebClient webClient = WebClient.create(vertx, options);

      HttpRequest<Buffer> request = webClient.get("/starter" + extension);
      request.queryParams().addAll(params);

      request.send(testContext.succeeding(handler));
    }));
}
 
Example #6
Source File: TestServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void getSchemasForNew() {
  String microserviceId = "msId";

  new MockUp<RestClientUtil>() {
    @Mock
    void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
      Holder<GetSchemasResponse> holder = Deencapsulation.getField(responseHandler, "arg$4");
      GetSchemasResponse schemasResp = Json.decodeValue(
          "{\"schemas\":[{\"schemaId\":\"metricsEndpoint\",\"summary\":\"c1188d709631a9038874f9efc6eb894f\"},{\"schemaId\":\"comment\",\"summary\":\"bfa81d625cfbd3a57f38745323e16824\"},"
              + "{\"schemaId\":\"healthEndpoint\",\"summary\":\"96a0aaaaa454cfa0c716e70c0017fe27\"}]}",
          GetSchemasResponse.class);
      holder.statusCode = 200;
      holder.value = schemasResp;
    }
  };
  Holder<List<GetSchemaResponse>> schemasHolder = oClient.getSchemas(microserviceId);
  List<GetSchemaResponse> schemas = schemasHolder.getValue();
  Assert.assertEquals(200, schemasHolder.getStatusCode());
  Assert.assertEquals(3, schemas.size());
  Assert.assertEquals("bfa81d625cfbd3a57f38745323e16824", schemas.get(1).getSummary());
}
 
Example #7
Source File: MqttSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private Buffer convert(Object payload) {
    if (payload instanceof JsonObject) {
        return new Buffer(((JsonObject) payload).toBuffer());
    }
    if (payload instanceof JsonArray) {
        return new Buffer(((JsonArray) payload).toBuffer());
    }
    if (payload instanceof String || payload.getClass().isPrimitive()) {
        return new Buffer(io.vertx.core.buffer.Buffer.buffer(payload.toString()));
    }
    if (payload instanceof byte[]) {
        return new Buffer(io.vertx.core.buffer.Buffer.buffer((byte[]) payload));
    }
    if (payload instanceof Buffer) {
        return (Buffer) payload;
    }
    if (payload instanceof io.vertx.core.buffer.Buffer) {
        return new Buffer((io.vertx.core.buffer.Buffer) payload);
    }
    // Convert to Json
    return new Buffer(Json.encodeToBuffer(payload));
}
 
Example #8
Source File: BeanTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testModuleDescriptorBadMethod() {
  int fail = 0;

  final String docModuleDescriptor = "{" + LS
    + "  \"id\" : \"sample-module-1\"," + LS
    + "  \"provides\" : [ {" + LS
    + "    \"id\" : \"sample\"," + LS
    + "    \"version\" : \"1.0\"," + LS
    + "    \"handlers\" : [ {" + LS
    + "      \"methods\" : [ \"GET\", \"NOST\" ]," + LS
    + "      \"pathPattern\" : \"/users/{id}\"" + LS
    + "    } ]" + LS
    + "  } ]" + LS
    + "}";

  try {
    final ModuleDescriptor md = Json.decodeValue(docModuleDescriptor,
      ModuleDescriptor.class);
    String pretty = Json.encodePrettily(md);
  } catch (DecodeException ex) {
    fail = 400;
  }
  assertEquals(400, fail);
}
 
Example #9
Source File: CreateUserEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInvokeSCIMCreateUserEndpoint_valid_password() throws Exception {
    router.route("/Users").handler(usersEndpoint::create);
    when(passwordValidator.validate(anyString())).thenReturn(true);
    when(userService.create(any(), any())).thenReturn(Single.just(getUser()));

    testRequest(
            HttpMethod.POST,
            "/Users",
            req -> {
                req.setChunked(true);
                req.write(Json.encode(getUser()));
            },
            201,
            "Created", null);
}
 
Example #10
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyStringIdField() throws Exception {
  final String id = "";
  final RequestBody body =
      RequestBody.create(
          JSON,
          "{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(id)
              + ",\"method\":\"web3_clientVersion\"}");

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    // An empty string is still a string, so should be a valid id
    assertThat(resp.code()).isEqualTo(200);
    // Check general format of result
    final JsonObject json = new JsonObject(resp.body().string());
    testHelper.assertValidJsonRpcResult(json, id);
    // Check result
    final String result = json.getString("result");
    assertThat(result).isEqualTo(CLIENT_VERSION);
  }
}
 
Example #11
Source File: DynamoSpaceConfigClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Override
public void getSpace(Marker marker, String spaceId, Handler<AsyncResult<Space>> handler) {
  try {
    logger.info(marker, "Getting space with ID: {}", spaceId);
    final Item item = spaces.getItem("id", spaceId);

    if (item == null) {
      logger.info(marker, "Getting space with ID: {} returned null", spaceId);
      handler.handle(Future.succeededFuture(null));
      return;
    }

    final Space space = Json.decodeValue(item.toJSON(), Space.class);
    if (space != null) {
      logger.info(marker, "Space ID: {} with title: \"{}\" has been decoded", spaceId, space.getTitle());
    } else {
      logger.info(marker, "Space ID: {} has been decoded to null", spaceId);
    }
    handler.handle(Future.succeededFuture(space));
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure during getting a space from DynamoDB", e);
    handler.handle(Future.failedFuture(e));
  }
}
 
Example #12
Source File: UpdateUserEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturn400WhenInvalidUserException() throws Exception {
    router.route("/Users").handler(userEndpoint::update);
    when(passwordValidator.validate(anyString())).thenReturn(true);
    when(userService.update(any(), any(), anyString())).thenReturn(Single.error(new InvalidUserException("Invalid user infos")));

    testRequest(
            HttpMethod.PUT,
            "/Users",
            req -> {
                req.setChunked(true);
                req.write(Json.encode(getUser()));
            },
            400,
            "Bad Request",
            "{\n" +
                    "  \"status\" : \"400\",\n" +
                    "  \"scimType\" : \"invalidValue\",\n" +
                    "  \"detail\" : \"Invalid user infos\",\n" +
                    "  \"schemas\" : [ \"urn:ietf:params:scim:api:messages:2.0:Error\" ]\n" +
                    "}");
}
 
Example #13
Source File: App.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void dbHandler(final RoutingContext ctx) {
  dbBuilder.transactAsync(dbs ->
    dbs.get().toSelect("SELECT id, randomnumber from WORLD where id = ?")
        .argInteger(randomWorld())
        .queryFirstOrNull(row -> new World(row.getIntegerOrZero(), row.getIntegerOrZero()))
  , call -> {
    if (call.succeeded()) {
      if (call.result() == null) {
        ctx.fail(404);
      } else {
        ctx.response()
            .putHeader(HttpHeaders.SERVER, SERVER)
            .putHeader(HttpHeaders.DATE, date)
            .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
            .end(Json.encode(call.result()));
      }
    } else {
      ctx.fail(call.cause());
    }
  });
}
 
Example #14
Source File: UserApiHandler.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private void logoutUser(RoutingContext routingContext) {
    logger.info("logoutUser()");
    HttpServerResponse response = routingContext.response();

    Single.defer( () -> {

        return apiImpl.logoutUser();
    })
    .subscribe(
        apiResponse -> {
            response.setStatusCode(apiResponse.getStatusCode())
                    .end(Json.encodePrettily(apiResponse.getData()));
        }, error -> {
            if (error instanceof ApiException) {
                ApiException apiException = (ApiException) error;
                response.setStatusCode(apiException.getStatusCode()).end(apiException.getMessage());
            } else {
                response.setStatusCode(500).end(error.getMessage());
            }
        }).dispose();
}
 
Example #15
Source File: RxPetStoreTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 2000)
public void testGetOrderById(TestContext context) {
    Async async = context.async();
    httpClient.getNow(TEST_PORT, TEST_HOST, "/v2/store/order/1", response -> {
        response.bodyHandler(body -> {
            JsonObject jsonObject = new JsonObject(body.toString());
            try {
                Order resultOrder = Json.mapper.readValue(jsonObject.encode(), Order.class);
                context.assertEquals(orderDog, resultOrder);
            } catch (Exception e) {
                context.fail(e);
            }
            async.complete();
        });
        response.exceptionHandler(err -> {
            context.fail(err);
        });
    });
}
 
Example #16
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void getBlockByHashWithInvalidHashParameterThatIsTooShort() throws Exception {
  final String id = "123";
  final String blockHashString = "0xe670";
  final RequestBody body =
      RequestBody.create(
          JSON,
          "{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(id)
              + ",\"method\":\"eth_getBlockByHash\", \"params\": [\""
              + blockHashString
              + "\",true]}");

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    assertThat(resp.code()).isEqualTo(400);
    // Check general format of result
    final JsonObject json = new JsonObject(resp.body().string());
    final JsonRpcError expectedError = JsonRpcError.INVALID_PARAMS;
    testHelper.assertValidJsonRpcError(
        json, id, expectedError.getCode(), expectedError.getMessage());
  }
}
 
Example #17
Source File: CreateUserEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturn409WhenUsernameAlreadyExists() throws Exception {
    router.route("/Users").handler(usersEndpoint::create);
    when(passwordValidator.validate(anyString())).thenReturn(true);
    when(userService.create(any(), any())).thenReturn(Single.error(new UniquenessException("Username already exists")));

    testRequest(
            HttpMethod.POST,
            "/Users",
            req -> {
                req.setChunked(true);
                req.write(Json.encode(getUser()));
            },
            409,
            "Conflict",
            "{\n" +
                    "  \"status\" : \"409\",\n" +
                    "  \"scimType\" : \"uniqueness\",\n" +
                    "  \"detail\" : \"Username already exists\",\n" +
                    "  \"schemas\" : [ \"urn:ietf:params:scim:api:messages:2.0:Error\" ]\n" +
                    "}");
}
 
Example #18
Source File: TestSpringMVCObjectParamTypeRestOnly.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullFieldAndDefaultValue_rpc() {
  LinkedHashMap<Object, Object> request = new LinkedHashMap<>();
  request.put("s1", "sss1");
  request.put("i1", 111);
  TestNullFieldAndDefaultValueParam response =
      consumers.getIntf().testNullFieldAndDefaultValue(request);
  TestNullFieldAndDefaultValueParam expectedResponse =
      new TestNullFieldAndDefaultValueParam("sss1", 111, null, 0, "defaultS3", 2333);
  expectedResponse.setRawRequest(Json.encode(expectedResponse));
  Assert.assertEquals(expectedResponse, response);

  request.put("s2", "sss2");
  request.put("i2", 1234);
  request.put("s3", "sss3");
  request.put("i3", 3333);
  response = consumers.getIntf().testNullFieldAndDefaultValue(request);
  expectedResponse = new TestNullFieldAndDefaultValueParam("sss1", 111, "sss2", 1234, "sss3", 3333);
  expectedResponse.setRawRequest(Json.encode(expectedResponse));
  Assert.assertEquals(expectedResponse, response);
}
 
Example #19
Source File: BeanTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeploymentDescriptor1() {
  int fail = 0;
  final String docSampleDeployment = "{" + LS
    + "  \"srvcId\" : \"sample-module-1\"," + LS
    + "  \"descriptor\" : {" + LS
    + "    \"exec\" : "
    + "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"," + LS
    + "    \"env\" : [ {" + LS
    + "      \"name\" : \"helloGreeting\"," + LS
    + "      \"value\" : \"hej\"" + LS
    + "    } ]" + LS
    + "  }" + LS
    + "}";

  try {
    final DeploymentDescriptor md = Json.decodeValue(docSampleDeployment,
      DeploymentDescriptor.class);
    String pretty = Json.encodePrettily(md);
    assertEquals(docSampleDeployment, pretty);
  } catch (DecodeException ex) {
    ex.printStackTrace();
    fail = 400;
  }
  assertEquals(0, fail);
}
 
Example #20
Source File: TestSpringMVCObjectParamTypeRestOnly.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullFieldAndDefaultValue_rt() {
  LinkedHashMap<Object, Object> request = new LinkedHashMap<>();
  request.put("s1", "sss1");
  request.put("i1", 111);
  TestNullFieldAndDefaultValueParam response = consumers.getSCBRestTemplate()
      .postForObject("/testNullFieldAndDefaultValue", request, TestNullFieldAndDefaultValueParam.class);
  TestNullFieldAndDefaultValueParam expectedResponse =
      new TestNullFieldAndDefaultValueParam("sss1", 111, null, 0, "defaultS3", 2333);
  expectedResponse.setRawRequest(Json.encode(expectedResponse));
  Assert.assertEquals(expectedResponse, response);

  request.put("s2", "sss2");
  request.put("i2", 1234);
  request.put("s3", "sss3");
  request.put("i3", 3333);
  ResponseEntity<TestNullFieldAndDefaultValueParam> responseEntity = consumers.getSCBRestTemplate()
      .postForEntity("/testNullFieldAndDefaultValue", request, TestNullFieldAndDefaultValueParam.class);
  expectedResponse = new TestNullFieldAndDefaultValueParam("sss1", 111, "sss2", 1234, "sss3", 3333);
  expectedResponse.setRawRequest(Json.encode(expectedResponse));
  Assert.assertEquals(expectedResponse, responseEntity.getBody());
  Assert.assertEquals(200, responseEntity.getStatusCodeValue());
}
 
Example #21
Source File: DiscoveryManager.java    From okapi with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a service to the discovery, and optionally deploys it too.
 * <p>
 *   1: We have LaunchDescriptor and NodeId: Deploy on that node.
 *   2: NodeId, but no LaunchDescriptor: Fetch the module, use its LaunchDescriptor, and deploy.
 *   3: No nodeId: Do not deploy at all, just record the existence (URL and instId) of the module.
 * </p>
 */
private void addAndDeploy0(DeploymentDescriptor dd,
                           Handler<ExtendedAsyncResult<DeploymentDescriptor>> fut) {

  String tmp = Json.encodePrettily(dd);
  logger.info("addAndDeploy: {}", tmp);
  final String modId = dd.getSrvcId();
  if (modId == null) {
    fut.handle(new Failure<>(ErrorType.USER, messages.getMessage("10800")));
    return;
  }
  moduleManager.get(modId, gres -> {
    if (gres.failed()) {
      if (gres.getType() == ErrorType.NOT_FOUND) {
        fut.handle(new Failure<>(ErrorType.NOT_FOUND, messages.getMessage("10801", modId)));
      } else {
        fut.handle(new Failure<>(gres.getType(), gres.cause()));
      }
    } else {
      addAndDeploy1(dd, gres.result(), fut);
    }
  });
}
 
Example #22
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void ethSyncingResultIsPresent() throws Exception {
  final SyncStatus testResult =
      new DefaultSyncStatus(1L, 8L, 7L, Optional.empty(), Optional.empty());
  when(synchronizer.getSyncStatus()).thenReturn(Optional.of(testResult));
  final String id = "999";
  final RequestBody body =
      RequestBody.create(
          JSON,
          "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"eth_syncing\"}");

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    final String respBody = resp.body().string();
    final JsonObject json = new JsonObject(respBody);
    final JsonObject result = json.getJsonObject("result");
    final long startingBlock = Long.decode(result.getString("startingBlock"));
    assertThat(startingBlock).isEqualTo(1L);
    final long currentBlock = Long.decode(result.getString("currentBlock"));
    assertThat(currentBlock).isEqualTo(8L);
    final long highestBlock = Long.decode(result.getString("highestBlock"));
    assertThat(highestBlock).isEqualTo(7L);
  }
}
 
Example #23
Source File: VerticleHelper.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
public <T> Handler<AsyncResult<ResourceResponse<T>>> getAsyncResultHandler(Message<JsonObject> message, String serviceName, boolean withJsonEncode, TypeReference<T> type) {
    return result -> {
        if (result.succeeded()) {
            DeliveryOptions deliveryOptions = new DeliveryOptions();
            deliveryOptions.setHeaders(result.result().getHeaders());
            if(withJsonEncode) {
                message.reply(Json.encode(result.result().getResponse()), deliveryOptions);
            } else {
                message.reply(result.result().getResponse(), deliveryOptions);
            }
        } else {
            Throwable cause = result.cause();
            manageError(message, cause, serviceName);
        }
    };
}
 
Example #24
Source File: Auth.java    From okapi with Apache License 2.0 5 votes vote down vote up
public void login(RoutingContext ctx) {
  final String json = ctx.getBodyAsString();
  if (json.length() == 0) {
    logger.debug("test-auth: accept OK in login");
    HttpResponse.responseText(ctx, 202).end("Auth accept in /authn/login");
    return;
  }
  LoginParameters p;
  try {
    p = Json.decodeValue(json, LoginParameters.class);
  } catch (DecodeException ex) {
    HttpResponse.responseText(ctx, 400).end("Error in decoding parameters: " + ex);
    return;
  }

  // Simple password validation: "peter" has a password "peter-password", etc.
  String u = p.getUsername();
  String correctpw = u + "-password";
  if (!p.getPassword().equals(correctpw)) {
    logger.warn("test-auth: Bad passwd for '{}'. Got '{}' expected '{}",
        u, p.getPassword(), correctpw);
    HttpResponse.responseText(ctx, 401).end("Wrong username or password");
    return;
  }
  String tok;
  tok = token(p.getTenant(), p.getUsername());
  logger.info("test-auth: Ok login for {}: {}", u, tok);
  HttpResponse.responseJson(ctx, 200).putHeader(XOkapiHeaders.TOKEN, tok).end(json);
}
 
Example #25
Source File: BodyParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void testOkAddBodyRequired(TestContext context) {
    Async async = context.async();
    BodyType bodyReq = new BodyType(1L, "body 1");
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/body/required");
    req.handler(response -> {
        context.assertEquals(response.statusCode(), 200);
        response.bodyHandler(body -> {
            context.assertEquals(Json.encode(bodyReq), body.toString());
            async.complete();
        });

    }).end(Json.encode(bodyReq));
}
 
Example #26
Source File: HttpJsonMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Override
public KafkaProducerRecord<byte[], byte[]> toKafkaRecord(String kafkaTopic, Integer partition, Buffer message) {

    Integer partitionFromBody = null;
    byte[] key = null;
    byte[] value = null;

    JsonObject json = message.toJsonObject();

    if (!json.isEmpty()) {
        if (json.containsKey("key")) {
            key = Json.encodeToBuffer(json.getValue("key")).getBytes();
        }
        if (json.containsKey("value")) {
            value = Json.encodeToBuffer(json.getValue("value")).getBytes();
        }
        if (json.containsKey("partition")) {
            partitionFromBody = json.getInteger("partition");
        }
        if (partition != null && partitionFromBody != null) {
            throw new IllegalStateException("Partition specified in body and in request path");
        }
        if (partition != null) {
            partitionFromBody = partition;
        }
    }

    KafkaProducerRecord<byte[], byte[]> record = KafkaProducerRecord.create(kafkaTopic, key, value, partitionFromBody);

    return record;
}
 
Example #27
Source File: RxPetStoreTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testUUID(TestContext context) {
    Async async = context.async();
    httpClient.getNow(TEST_PORT, TEST_HOST, "/v2/uuid/5f2f7ba4-3d97-44d7-8e9d-4d7141bab11c", response -> {
        response.bodyHandler(body -> {
            context.assertEquals("5f2f7ba4-3d97-44d7-8e9d-4d7141bab11c", Json.decodeValue(body.toString(), Map.class).get("uuid"));
            async.complete();
        });
    });
}
 
Example #28
Source File: DeviceManagementServiceImpl.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Override
protected Future<OperationResult<Id>> processUpdateDevice(final DeviceKey key, final Device device, final Optional<String> resourceVersion, final Span span) {

    final CompletableFuture<OperationResult<Id>> future = this.managementCache

            .getWithMetadataAsync(deviceKey(key))
            .thenCompose(currentValue -> {

                if (currentValue == null) {
                    return completedFuture(OperationResult.empty(HTTP_NOT_FOUND));
                }

                if (!currentValue.getValue().isVersionMatch(resourceVersion)) {
                    return failedFuture(new ServiceInvocationException(HTTP_PRECON_FAILED, "Version mismatch"));
                }

                final DeviceInformation newValue = currentValue.getValue().newVersion();
                newValue.setRegistrationInformation(Json.encode(device));

                return this.managementCache

                        .replaceWithVersionAsync(deviceKey(key), newValue, currentValue.getVersion())
                        .thenApply(putResult -> {
                            if (putResult == null) {
                                return OperationResult.empty(HTTP_PRECON_FAILED);
                            }

                            return ok(
                                    HTTP_NO_CONTENT,
                                    Id.of(key.getDeviceId()),
                                    Optional.empty(),
                                    Optional.ofNullable(newValue.getVersion()));
                        });

            });

    return MoreFutures.map(future);
}
 
Example #29
Source File: DynamicClientRegistrationTemplateEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    LOGGER.debug("Dynamic client registration TEMPLATE endpoint");

    this.clientSyncService.findTemplates()
            .subscribe(
                    templates -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(DynamicClientRegistrationTemplate.from(templates)))
                    , error -> context.fail(error)
            );
}
 
Example #30
Source File: JsonRpcHttpServiceRpcApisTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void requestWithNetMethodShouldSucceedWhenDefaultApisEnabled() throws Exception {
  service = createJsonRpcHttpServiceWithRpcApis(configuration);
  final String id = "123";
  final RequestBody body =
      RequestBody.create(
          JSON,
          "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"net_version\"}");

  try (final Response resp = client.newCall(buildRequest(body)).execute()) {
    assertThat(resp.code()).isEqualTo(200);
  }
}