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

The following examples show how to use io.vertx.core.json.Json#decodeValue() . 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: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
private void pullModules(String body,
                         Handler<ExtendedAsyncResult<String>> fut) {

  try {
    final PullDescriptor pmd = Json.decodeValue(body, PullDescriptor.class);
    pullManager.pull(pmd, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      fut.handle(new Success<>(Json.encodePrettily(res.result())));
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(ErrorType.USER, ex));
  }
}
 
Example 2
Source File: UserInfoEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * Handle claims request previously made during the authorization request
 * @param claimsValue claims request parameter
 * @param userClaims user full claims list
 * @param requestedClaims requested claims
 * @return true if userinfo claims have been found
 */
private boolean processClaimsRequest(String claimsValue, final Map<String, Object> userClaims, Map<String, Object> requestedClaims) {
    try {
        ClaimsRequest claimsRequest = Json.decodeValue(claimsValue, ClaimsRequest.class);
        if (claimsRequest != null && claimsRequest.getUserInfoClaims() != null) {
            claimsRequest.getUserInfoClaims().forEach((key, value) -> {
                if (userClaims.containsKey(key)) {
                    requestedClaims.putIfAbsent(key, userClaims.get(key));
                }
            });
            return true;
        }
    } catch (Exception e) {
        // Any members used that are not understood MUST be ignored.
    }
    return false;
}
 
Example 3
Source File: BeanTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeploymentDescriptor2() {
  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
    + "    } ]" + 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 4
Source File: TestServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void getAggregatedMicroservice() {
  String microserviceId = "msId";
  new MockUp<RestClientUtil>() {
    @Mock
    void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
      Holder<GetServiceResponse> holder = Deencapsulation.getField(responseHandler, "arg$4");
      holder.value = Json
          .decodeValue(
              "{\"service\":{\"serviceId\":\"serviceId\",\"framework\":null"
                  + ",\"registerBy\":null,\"environment\":null,\"appId\":\"appId\",\"serviceName\":null,"
                  + "\"alias\":null,\"version\":null,\"description\":null,\"level\":null,\"schemas\":[],"
                  + "\"paths\":[],\"status\":\"UP\",\"properties\":{},\"intance\":null}}",
              GetServiceResponse.class);
      RequestParam requestParam = requestContext.getParams();
      Assert.assertEquals("global=true", requestParam.getQueryParams());
    }
  };
  Microservice aggregatedMicroservice = oClient.getAggregatedMicroservice(microserviceId);
  Assert.assertEquals("serviceId", aggregatedMicroservice.getServiceId());
  Assert.assertEquals("appId", aggregatedMicroservice.getAppId());
}
 
Example 5
Source File: TestServiceRegistryClientImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void getSchemas() {
  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(
          "{\"schema\":[{\"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> schemaResponses = schemasHolder.getValue();
  Assert.assertEquals(200, schemasHolder.getStatusCode());
  Assert.assertEquals(3, schemaResponses.size());
  Assert.assertEquals("bfa81d625cfbd3a57f38745323e16824", schemaResponses.get(1).getSummary());
}
 
Example 6
Source File: Space.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
public Map<String,Object> asMap() {
  try {
    //noinspection unchecked
    return Json.decodeValue(Json.mapper.writerWithView(Static.class).writeValueAsString(this), Map.class);
  } catch (Exception e) {
    return Collections.emptyMap();
  }
}
 
Example 7
Source File: CredentialsTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test to ensure we can decode what we encoded.
 */
@Test
public void testEncodeDecode1() {

    final String authId = "abcd-=.";
    final Instant notAfter = Instant.parse("1992-09-11T11:38:00.123456Z");

    // create credentials to encode

    final PasswordSecret secret = new PasswordSecret();
    secret.setPasswordHash("setec astronomy");
    secret.setSalt("abc");
    secret.setNotAfter(notAfter);

    final PasswordCredential cred = new PasswordCredential(authId);
    cred.setSecrets(Arrays.asList(secret));

    // encode

    final String encode = Json.encode(new CommonCredential[] { cred });

    // now decode

    final CommonCredential[] decode = Json.decodeValue(encode, CommonCredential[].class);

    // and assert
    assertThat(decode[0]).isInstanceOf(PasswordCredential.class);

    final PasswordCredential decodeCredential = (PasswordCredential) decode[0];

    assertThat(decodeCredential.getAuthId()).isEqualTo(authId);
    assertThat(decodeCredential.getSecrets()).hasSize(1);
    final PasswordSecret decodeSecret = decodeCredential.getSecrets().get(0);
    assertThat(decodeSecret.getNotAfter()).isEqualTo(Instant.parse("1992-09-11T11:38:00Z"));
}
 
Example 8
Source File: CarsResource.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
public void create(RoutingContext routingContext) {
    Car car = Json.decodeValue(routingContext.getBodyAsString(), Car.class);
    carRepository.save(car);
    HttpServerResponse response = routingContext.response();
    response.putHeader("Location", routingContext.request().absoluteURI() + "/" + car.getId())
            .setStatusCode(201)
            .end();
}
 
Example 9
Source File: XyzHubActionMatrixTest.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Test
public void testCase16() {
  String rights = "{'readFeatures': [{'color': 'blue'}, {'tags': 'mapcreator'}, {'tags': 'OSM'}]}".replace('\'', '"');
  String filter = "{'readFeatures': [{'color': 'blue'}, {'tags': ['mapcreator', 'delta']}]}".replace('\'', '"');

  ActionMatrix rightsMatrix = Json.decodeValue(rights, ActionMatrix.class);
  ActionMatrix filterMatrix = Json.decodeValue(filter, ActionMatrix.class);
  assertTrue(rightsMatrix.matches(filterMatrix));
}
 
Example 10
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 11
Source File: XyzHubActionMatrixTest.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Test
public void testCase9() {
  String rights = "{'readFeatures': [{'owner': 'abc'}]}".replace('\'', '"');
  String filter = "{'readFeatures': [{'owner': 'abc'}]}".replace('\'', '"');

  ActionMatrix rightsMatrix = Json.decodeValue(rights, ActionMatrix.class);
  ActionMatrix filterMatrix = Json.decodeValue(filter, ActionMatrix.class);
  assertTrue(rightsMatrix.matches(filterMatrix));
  assertTrue(filterMatrix.matches(rightsMatrix));
}
 
Example 12
Source File: EthSubscribeIntegrationTest.java    From besu with Apache License 2.0 5 votes vote down vote up
private WebSocketRpcRequest createEthSubscribeRequestBody(final String connectionId) {
  return Json.decodeValue(
      "{\"id\": 1, \"method\": \"eth_subscribe\", \"params\": [\"syncing\"], \"connectionId\": \""
          + connectionId
          + "\"}",
      WebSocketRpcRequest.class);
}
 
Example 13
Source File: DFDataProcessor.java    From df_data_service with Apache License 2.0 5 votes vote down vote up
/**
 * Update one model information
 */
private void updateOneModel(RoutingContext routingContext) {
    final String id = routingContext.request().getParam("id");
    final DFModelPOPJ dfModel = Json.decodeValue(routingContext.getBodyAsString(),DFModelPOPJ.class);

    if (id == null) {
        routingContext.response()
                .setStatusCode(ConstantApp.STATUS_CODE_BAD_REQUEST)
                .end(DFAPIMessage.getResponseMessage(9000));
        LOG.error(DFAPIMessage.logResponseMessage(9000, id));
    } else {
        mongo.updateCollection(COLLECTION_MODEL, new JsonObject().put("_id", id), // Select a unique document
                // The update syntax: {$set, the json object containing the fields to update}
                new JsonObject().put("$set", dfModel.toJson()), v -> {
                    if (v.failed()) {
                        routingContext.response()
                                .setStatusCode(ConstantApp.STATUS_CODE_NOT_FOUND)
                                .end(DFAPIMessage.getResponseMessage(9003));
                        LOG.error(DFAPIMessage.logResponseMessage(9003, id));
                    } else {
                        HelpFunc.responseCorsHandleAddOn(routingContext.response())
                                .end(DFAPIMessage.getResponseMessage(1001));
                        LOG.info(DFAPIMessage.logResponseMessage(1001, id));
                    }
                }
        );
    }
}
 
Example 14
Source File: DtmHandlerInterceptor.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  //get header then fill to DTMContext for business use it
  DTMContext dtmContext = DTMContext.getDTMContext();
  String dtmHeader = request.getHeader(DtmConstants.DTM_CONTEXT);
  if (StringUtils.isNotEmpty(dtmHeader)) {
    DtmContextDTO dtmContextDTO = Json.decodeValue(dtmHeader, DtmContextDTO.class);
    LOGGER.debug("dtm info, provider dtmContextDTO:" + dtmContextDTO);
    transform(dtmContext, dtmContextDTO);
  }
  return true;
}
 
Example 15
Source File: DeviceTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Decode device with "enabled=true".
 */
@Test
public void testDecodeEnabled() {
    final var device = Json.decodeValue("{\"enabled\": true}", Device.class);
    assertThat(device).isNotNull();
    assertThat(device.isEnabled());
}
 
Example 16
Source File: TransactionCountResponder.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
private static JsonRpcRequestId getRequestId(final String jsonBody) {
  final JsonRpcRequest jsonRpcRequest = Json.decodeValue(jsonBody, JsonRpcRequest.class);
  return jsonRpcRequest.getId();
}
 
Example 17
Source File: JsonMessageCodec.java    From festival with Apache License 2.0 4 votes vote down vote up
@Override
public Object decodeFromWire(int pos, Buffer buffer) {
    return Json.decodeValue(buffer);
}
 
Example 18
Source File: EthUnsubscribeTest.java    From besu with Apache License 2.0 4 votes vote down vote up
private JsonRpcRequestContext createJsonRpcRequest() {
  return new JsonRpcRequestContext(
      Json.decodeValue(
          "{\"id\": 1, \"method\": \"eth_unsubscribe\", \"params\": [\"0x0\"]}",
          JsonRpcRequest.class));
}
 
Example 19
Source File: DemoRamlRestTest.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
@Test
public void getBookWithRoutingContext(TestContext context)  throws Exception {
  Buffer buf = Buffer.buffer("{\"module_to\":\"raml-module-builder-1.0.0\"}");
  NetClient cli = vertx.createNetClient();
  postData(context, "http://localhost:" + port + "/_/tenant", buf,
    201, HttpMethod.POST, "application/json", TENANT, false);

  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test?query=nullpointer%3Dtrue", 500);
  context.assertEquals("java.lang.NullPointerException", buf.toString());

  Books books;
  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test", 200);
  books = Json.decodeValue(buf, Books.class);
  context.assertEquals(0, books.getTotalRecords());
  context.assertEquals(0, books.getResultInfo().getDiagnostics().size());
  context.assertEquals(0, books.getResultInfo().getTotalRecords());
  context.assertEquals(0, books.getBooks().size());

  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test?query=title%3Dwater", 200);
  books = Json.decodeValue(buf, Books.class);
  context.assertEquals(0, books.getTotalRecords());

  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test?query=a%3D", 400);
  context.assertTrue(buf.toString().contains("expected index or term, got EOF"));

  Data d = new Data();
  d.setAuthor("a");
  d.setGenre("g");
  d.setDescription("description1");
  d.setTitle("title");
  d.setDatetime(new Datetime());
  d.setLink("link");

  Book b = new Book();
  b.setData(d);
  b.setStatus(0);
  b.setSuccess(true);

  ObjectMapper om = new ObjectMapper();
  String book = om.writerWithDefaultPrettyPrinter().writeValueAsString(b);

  postData(context, "http://localhost:" + port + "/rmbtests/test", Buffer.buffer(book), 201,
    HttpMethod.POST, "application/json", TENANT, false);

  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test", 200);
  books = Json.decodeValue(buf, Books.class);
  context.assertEquals(1, books.getTotalRecords());
  context.assertEquals(0, books.getResultInfo().getDiagnostics().size());
  context.assertEquals(1, books.getResultInfo().getTotalRecords());
  context.assertEquals(1, books.getBooks().size());

  d.setDescription("description2");
  book = om.writerWithDefaultPrettyPrinter().writeValueAsString(b);
  postData(context, "http://localhost:" + port + "/rmbtests/test", Buffer.buffer(book), 201,
    HttpMethod.POST, "application/json", TENANT, false);

  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test", 200);
  books = Json.decodeValue(buf, Books.class);
  context.assertEquals(2, books.getTotalRecords());
  context.assertEquals(0, books.getResultInfo().getDiagnostics().size());
  context.assertEquals(2, books.getResultInfo().getTotalRecords());
  context.assertEquals(2, books.getBooks().size());

  // need at least one record in result before we can trigger this error
  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test?query=badclass%3Dtrue", 200);
  books = Json.decodeValue(buf, Books.class);
  context.assertEquals(2, books.getTotalRecords());
  context.assertEquals(1, books.getResultInfo().getDiagnostics().size());
  context.assertTrue(books.getResultInfo().getDiagnostics().get(0).getMessage().contains("Cannot deserialize instance of"));
  context.assertEquals(2, books.getResultInfo().getTotalRecords());
  context.assertEquals(0, books.getBooks().size());

  // see that we can handle a subset of the Book properties: id and status
  // use case: replace "SELECT jsonb FROM ..." by "SELECT jsonb_build_object('id', id, 'status', jsonb->'status') FROM ..."
  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test?query=slim%3Dtrue", 200);
  JsonObject jo = new JsonObject(buf);
  context.assertEquals(2, jo.getInteger("totalRecords"));
  SlimBook sb = jo.getJsonArray("books").getJsonObject(0).mapTo(SlimBook.class);
  context.assertEquals(0, sb.getStatus());
  context.assertNotNull(sb.getId());
  sb = jo.getJsonArray("books").getJsonObject(1).mapTo(SlimBook.class);
  context.assertEquals(0, sb.getStatus());
  context.assertNotNull(sb.getId());

  buf = checkURLs(context, "http://localhost:" + port + "/rmbtests/test?query=wrapper%3Dtrue", 200);
  books = Json.decodeValue(buf, Books.class);
  context.assertEquals(2, books.getTotalRecords());
}
 
Example 20
Source File: GraphQLInput.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
static GraphQLInput decode(Buffer buffer) {
  final Object value = Json.decodeValue(buffer);
  return decode(value);
}