private void addItem(RoutingContext rc) { String body = rc.getBodyAsString(); if (body != null) { Item item = Json.decodeValue(body, Item.class); if (item.getQuantity() == 0) { redis.hdel("my-shopping-list", item.getName(), res -> { if (res.failed()) { rc.fail(res.cause()); } else { getShoppingList(rc); } }); } else { redis.hset("my-shopping-list", item.getName(), Integer.toString(item.getQuantity()), res -> { if (res.failed()) { rc.fail(res.cause()); } else { getShoppingList(rc); } }); } } else { rc.response().setStatusCode(400).end(); } }
public static <T> T decodeBodyToObject(RoutingContext routingContext, Class<T> clazz) { try { return Json.decodeValue(routingContext.getBodyAsString("UTF-8"), clazz); } catch (DecodeException exception) { routingContext.fail(exception); return null; } }
private void getOne(RoutingContext routingContext) { String id = routingContext.request().getParam("id"); try { Integer idAsInteger = Integer.valueOf(id); Article article = products.get(idAsInteger); if (article == null) { // Not found routingContext.response().setStatusCode(404).end(); } else { routingContext.response() .setStatusCode(200) .putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(article)); } } catch (NumberFormatException e) { routingContext.response().setStatusCode(400).end(); } }
private void updateOne(RoutingContext routingContext) { String id = routingContext.request().getParam("id"); try { Integer idAsInteger = Integer.valueOf(id); Article article = products.get(idAsInteger); if (article == null) { // Not found routingContext.response().setStatusCode(404).end(); } else { JsonObject body = routingContext.getBodyAsJson(); article.setTitle(body.getString("title")).setUrl(body.getString("url")); products.put(idAsInteger, article); routingContext.response() .setStatusCode(200) .putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(article)); } } catch (NumberFormatException e) { routingContext.response().setStatusCode(400).end(); } }
/** * Returns a handler writing the received {@link AsyncResult} to the routing context and setting the HTTP status to * the given status. * @param context the routing context * @param status the status * @return the handler */ private static <T> Handler<AsyncResult<T>> writeJsonResponse(RoutingContext context, int status) { return ar -> { if (ar.failed()) { if (ar.cause() instanceof NoSuchElementException) { context.response().setStatusCode(404).end(ar.cause().getMessage()); } else { context.fail(ar.cause()); } } else { context.response().setStatusCode(status) .putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(ar.result())); } }; }
@Test public void checkThatWeCanAdd(TestContext context) { Async async = context.async(); final String json = Json.encodePrettily(new Article("Some title", "Some url")); vertx.createHttpClient().post(port, "localhost", "/api/articles") .putHeader("Content-Type", "application/json") .putHeader("Content-Length", Integer.toString(json.length())) .handler(response -> { context.assertEquals(response.statusCode(), 201); context.assertTrue(response.headers().get("content-type").contains("application/json")); response.bodyHandler(body -> { Article article = Json.decodeValue(body.toString(), Article.class); context.assertEquals(article.getTitle(), "Some title"); context.assertEquals(article.getUrl(), "Some url"); context.assertNotNull(article.getId()); async.complete(); }); }) .write(json) .end(); }
@Override public String[] decodeFromWire(int position, Buffer buffer) { int pos = position; int length = buffer.getInt(pos); // Get JSON string by it`s length // Jump 4 because getInt() == 4 bytes String jsonStr = buffer.getString(pos+=4, pos+length); return Json.decodeValue(jsonStr, String[].class); }
@Override public PersonName decodeFromWire(int position, Buffer buffer) { int pos = position; int length = buffer.getInt(pos); // Get JSON string by it`s length // Jump 4 because getInt() == 4 bytes String jsonStr = buffer.getString(pos+=4, pos+length); return Json.decodeValue(jsonStr, PersonName.class); }
@Override public void handle(RoutingContext routingContext) { String content = routingContext.getBodyAsString(); final ChatMessage chatMessage = Json.decodeValue(content, ChatMessage.class); String messageId = UUID.randomUUID().toString(); chatMessage.setId(messageId); chatMessage.setCreated(System.currentTimeMillis()); redisClient.hset(MESSAGES, messageId, Json.encode(chatMessage), result -> {}); vertx.eventBus().send(ChatAddresses.MESSAGES.getAddress(), chatMessage); routingContext.response() .setStatusCode(201) .putHeader("content-type", "application/json; charset=utf-8") .end(messageId); }
@Override public ChatMessage decodeFromWire(int position, Buffer buffer) { int pos = position; int length = buffer.getInt(pos); // Get JSON string by it`s length // Jump 4 because getInt() == 4 bytes String jsonStr = buffer.getString(pos+=4, pos+length); return Json.decodeValue(jsonStr, ChatMessage.class); }
public <B> void buildSuccess(RoutingContext routingContext, B body) { LOG.debug("Building success message"); Completable.fromAction( () -> routingContext.response() .setStatusCode(200) .putHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE) .putHeader("Link", buildLinkHeaderValue()) .end(body != null ? Json.encodePrettily(body) : StringUtils.EMPTY)) .subscribeOn(Schedulers.io()) .subscribe( () -> {}, // Do nothing on success (ex) -> routingContext.fail(ex) ); }
private static void write(HttpServerResponse response, Problem problem) { int statusCode = problem.getStatus() != null ? problem.getStatus().getStatusCode() : Status.OK.getStatusCode(); response.setChunked(true).putHeader("Content-Type", "application/problem+json"); try { response .setStatusCode(statusCode) .write(Json.encode(problem)); } catch (EncodeException e) { LOG.error("Error while writing problem to JSON", e); response .setStatusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) .write(INTERNAL_SERVER_ERROR); } finally { response.end(); } }
@Override public void start(Future<Void> startFuture) throws Exception { Json.mapper.registerModule(new JavaTimeModule()); FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.readFile("swagger.json", readFile -> { if (readFile.succeeded()) { Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8"))); Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver()); deployVerticles(startFuture); vertx.createHttpServer() .requestHandler(swaggerRouter::accept) .listen(8080); startFuture.complete(); } else { startFuture.fail(readFile.cause()); } }); }
@Override public Promise<StateTrigger<Msg<Json>>> handle(Msg<JsonArray> msg) throws Throwable { List list = msg.body().stream() .map( obj -> authorizer .authorize( Authorizer.AuthorizeParams.builder() .action(action) .userId(msg.userId()) .request(obj) .build() ) ) .collect(Collectors.toList()); return authorize(list, msg); }
/** * Registers a handler for accessing multiple configuration keys (input: String[] (Json), * reply type: Map<String,String></String,String> (Json). * @param address the event bus address to register. * @param eventBus the event bus. * @return the consumer registered. */ public static MessageConsumer<String> registerMultiConfigEntryProvider(String address, EventBus eventBus){ MessageConsumer<String> consumer = eventBus.consumer(address); consumer.handler(h -> { String val = h.body(); Configuration config = ConfigurationProvider.getConfiguration(); Map<String,String> entries = new TreeMap<>(); if(val!=null){ String[] sections = Json.decodeValue(val, String[].class); for (String section : sections) { if(section!=null) { entries.putAll(config.with(ConfigurationFunctions.section(section)).getProperties()); } } }else{ entries.putAll(config.getProperties()); } h.reply(Json.encode(entries)); }); return consumer; }
@Test public void testMap(final TestContext testContext){ final Async async = testContext.async(); String selector = "[]{\"user.*\"}"; vertxContext.vertx().eventBus().send(TamayaConfigurationProducer.DEFAULT_CONFIG_GET_MULTI_ADDRESS, selector, reply -> { testContext.assertNotNull(reply.result()); testContext.assertNotNull(reply.result().body()); Map<String,String> config = Json.decodeValue((String)reply.result().body(), Map.class); Map<String,String> compareTo = ConfigurationProvider.getConfiguration() .with(ConfigurationFunctions.filter((k,v) -> { return k.matches("user."); })).getProperties(); testContext.assertEquals(config.size(), compareTo.size()); for(Map.Entry<String,String> en:compareTo.entrySet()){ testContext.assertEquals( config.get(en.getKey()), en.getValue()); } async.complete(); }); }
@Test public void testDeploymentDescriptor3() { 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 + " }" + 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); }
private void handleListBooks(RoutingContext routingContext) { eventBus.send("de.nierbeck.vertx.jdbc.read", new Book(), message -> { HttpServerResponse response = routingContext.response(); if (!message.failed()) { @SuppressWarnings("unchecked") List<Book> customMessage = (List<Book>) message.result().body(); LOGGER.log(Level.INFO, "Receiver ->>>>>>>> " + customMessage); if (customMessage != null) { response.putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(customMessage)); } } else { LOGGER.log(Level.SEVERE, "message failed"); } response.closed(); }); }
@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); }
/** * Helper to actually launch (deploy) a module on a node. */ private void callDeploy(String nodeId, DeploymentDescriptor dd, Handler<ExtendedAsyncResult<DeploymentDescriptor>> fut) { logger.debug("callDeploy starting for " + Json.encode(dd)); getNode(nodeId, noderes -> { if (noderes.failed()) { fut.handle(new Failure<>(noderes.getType(), noderes.cause())); } else { OkapiClient ok = new OkapiClient(noderes.result().getUrl(), vertx, null); String reqdata = Json.encode(dd); ok.post("/_/deployment/modules", reqdata, okres -> { ok.close(); if (okres.failed()) { fut.handle(new Failure<>(okres.getType(), okres.cause().getMessage())); } else { DeploymentDescriptor pmd = Json.decodeValue(okres.result(), DeploymentDescriptor.class); fut.handle(new Success<>(pmd)); } }); } }); }
private void createEnv(ProxyContext pc, String body, Handler<ExtendedAsyncResult<String>> fut) { try { final EnvEntry pmd = Json.decodeValue(body, EnvEntry.class); envManager.add(pmd, res -> { if (res.failed()) { fut.handle(new Failure<>(res.getType(), res.cause())); return; } final String js = Json.encodePrettily(pmd); location(pc, pmd.getName(), null, js, fut); }); } catch (DecodeException ex) { fut.handle(new Failure<>(USER, ex)); } }
private void receiveCookBook(RoutingContext routingContext) { String id = routingContext.request().getParam("id"); Book book = new Book(); book.setId(Long.valueOf(id)); eventBus.send("de.nierbeck.vertx.jdbc.read", book, message -> { HttpServerResponse response = routingContext.response(); if (!message.failed()) { Book customMessage = (Book) message.result().body(); LOGGER.log(Level.INFO,"Receiver ->>>>>>>> " + customMessage); if (customMessage != null) { response.putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(customMessage)); } } else { LOGGER.log(Level.SEVERE, "message failed"); } response.closed(); }); }
/** * Find the tenant API interface. Supports several deprecated versions of the * tenant interface: the 'tenantInterface' field in MD; if the module provides * a '_tenant' interface without RoutingEntries, and finally the proper way, * if the module provides a '_tenant' interface that is marked as a system * interface, and has a RoutingEntry that supports POST. * * @param module * @param fut callback with the path to the interface, "" if no interface, or * a failure * */ private void getTenantInterface(ModuleDescriptor md, Handler<ExtendedAsyncResult<String>> fut) { InterfaceDescriptor[] prov = md.getProvidesList(); logger.debug("findTenantInterface: prov: " + Json.encode(prov)); for (InterfaceDescriptor pi : prov) { logger.debug("findTenantInterface: Looking at " + pi.getId()); if ("_tenant".equals(pi.getId())) { getTenantInterface1(pi, fut, md); return; } } fut.handle(new Failure<>(NOT_FOUND, "No _tenant interface found for " + md.getId())); }
/** * Checks if is valid json. * * @param content * the content * @return true, if is valid json */ protected boolean isValidJson(String content) { try { Json.decodeValue(content, Object.class); return true; } catch (Exception e) { return false; } }
@Test public void testRecordCreation() { ObjectMeta metadata = new ObjectMeta(); metadata.setName("my-service"); metadata.setUid("uuid"); metadata.setNamespace("my-project"); ServiceSpec spec = new ServiceSpec(); ServicePort port = new ServicePort(); port.setTargetPort(new IntOrString(8080)); port.setPort(1524); spec.setPorts(Collections.singletonList(port)); Service service = new Service(); service.setMetadata(metadata); service.setSpec(spec); Record record = KubernetesServiceImporter.createRecord(new JsonObject(Json.encodeToBuffer(service))); assertThat(record).isNotNull(); assertThat(record.getName()).isEqualTo("my-service"); assertThat(record.getMetadata().getString("kubernetes.name")).isEqualTo("my-service"); assertThat(record.getMetadata().getString("kubernetes.namespace")).isEqualTo("my-project"); assertThat(record.getMetadata().getString("kubernetes.uuid")).isEqualTo("uuid"); assertThat(record.getType()).isEqualTo(ServiceType.UNKNOWN); assertThat(record.getLocation().getInteger("port")).isEqualTo(1524); }
public void update(T md, Handler<ExtendedAsyncResult<Void>> fut) { PostgresQuery q = pg.getQuery(); String sql = "INSERT INTO " + table + "(" + jsonColumn + ") VALUES (?::JSONB)" + " ON CONFLICT ((" + idIndex + ")) DO UPDATE SET " + jsonColumn + "= ?::JSONB"; String s = Json.encode(md); JsonObject doc = new JsonObject(s); JsonArray jsa = new JsonArray(); jsa.add(doc.encode()); jsa.add(doc.encode()); q.updateWithParams(sql, jsa, res -> { if (res.failed()) { fut.handle(new Failure<>(INTERNAL, res.cause())); } else { q.close(); fut.handle(new Success<>()); } }); }
@Test(timeout = 2000) public void testGetPetById(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/v2/pet/1", response -> { response.bodyHandler(body -> { JsonObject jsonObject = new JsonObject(body.toString()); try { Pet resultDog = Json.mapper.readValue(jsonObject.encode(), Pet.class); context.assertEquals(dog, resultDog); } catch (Exception e) { context.fail(e); } async.complete(); }); response.exceptionHandler(err -> { context.fail(err); }); }); }
@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); }); }); }
public void insert(T dd, Handler<ExtendedAsyncResult<Void>> fut) { PostgresQuery q = pg.getQuery(); final String sql = "INSERT INTO " + table + "(" + jsonColumn + ") VALUES (?::JSONB)"; String s = Json.encode(dd); JsonObject doc = new JsonObject(s); JsonArray jsa = new JsonArray(); jsa.add(doc.encode()); q.queryWithParams(sql, jsa, res -> { if (res.failed()) { fut.handle(new Failure<>(res.getType(), res.cause())); } else { q.close(); fut.handle(new Success<>()); } }); }
private void addFull(String urlBase, ModuleDescriptor ml, Handler<ExtendedAsyncResult<ModuleDescriptor>> fut) { String url = urlBase; if (!url.endsWith("/")) { url += "/"; } url += "_/proxy/modules"; Buffer body = Buffer.buffer(); HttpClientRequest req = httpClient.postAbs(url, res -> { res.handler(body::appendBuffer); res.endHandler(x -> { if (res.statusCode() != 201) { fut.handle(new Failure<>(ErrorType.USER, body.toString())); } else { ModuleDescriptor md = Json.decodeValue(body.toString(), ModuleDescriptor.class); fut.handle(new Success<>(md)); } }); res.exceptionHandler(x -> fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage()))); }); req.exceptionHandler(x -> fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage()))); req.end(Json.encodePrettily(ml)); }
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); } }; }
@Override public void start(Future<Void> startFuture) throws Exception { Json.mapper.registerModule(new JavaTimeModule()); FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.readFile("swagger.json", readFile -> { if (readFile.succeeded()) { Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8"))); SwaggerManager.getInstance().setSwagger(swagger); Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver()); deployVerticles(startFuture); vertx.createHttpServer() .requestHandler(swaggerRouter::accept) .listen(config().getInteger("http.port", 8080)); startFuture.complete(); } else { startFuture.fail(readFile.cause()); } }); }
@Start public void start() { Route route = router.get("/messages"); routes.add(route); route.handler(routingContext -> { messageStore.listMessagesAsJson().subscribe( messages -> routingContext.response().putHeader("content-type", "application/json; charset=utf-8").setChunked(true).write(Json.encodePrettily(messages)), e -> { routingContext.fail(500); e.printStackTrace(); }, () -> routingContext.response().end()); }); }
/** * Transform JSONOBJECT into array * @param type * @param json * @param * @return */ public static <T> T[] jsonToArr(Class<T[]> type, List<JsonObject> json){ try { T[] dd = JsonTransform.builder.fromJson( Json.encodePrettily( json ), type ); return dd; }catch (Exception e){ e.printStackTrace(); return null; } }
private void createTenant(ProxyContext pc, String body, Handler<ExtendedAsyncResult<String>> fut) { try { final TenantDescriptor td = Json.decodeValue(body, TenantDescriptor.class); if (td.getId() == null || td.getId().isEmpty()) { td.setId(UUID.randomUUID().toString()); } final String id = td.getId(); if (!id.matches("^[a-z0-9_-]+$")) { fut.handle(new Failure<>(USER, "Invalid tenant id '" + id + "'")); return; } Tenant t = new Tenant(td); tenantManager.insert(t, res -> { if (res.failed()) { fut.handle(new Failure<>(res.getType(), res.cause())); return; } location(pc, id, null, Json.encodePrettily(t.getDescriptor()), fut); }); } catch (DecodeException ex) { fut.handle(new Failure<>(USER, ex)); } }
private void updateTenant(String id, String body, Handler<ExtendedAsyncResult<String>> fut) { try { final TenantDescriptor td = Json.decodeValue(body, TenantDescriptor.class); if (!id.equals(td.getId())) { fut.handle(new Failure<>(USER, "Tenant.id=" + td.getId() + " id=" + id)); return; } Tenant t = new Tenant(td); tenantManager.updateDescriptor(td, res -> { if (res.failed()) { fut.handle(new Failure<>(res.getType(), res.cause())); return; } final String s = Json.encodePrettily(t.getDescriptor()); fut.handle(new Success<>(s)); }); } catch (DecodeException ex) { fut.handle(new Failure<>(USER, ex)); } }
private Observable<ObjectNode> observeGetObject(String endpoint) { ObservableHandler<HttpClientResponse> responseObservable = RxHelper.observableHandler(); client.getNow(endpoint, responseObservable.toHandler()); return responseObservable .flatMap(response -> { if (response.statusCode() == HTTP_OK) { ObservableHandler<Buffer> observable = RxHelper.observableHandler(); response.bodyHandler(observable.toHandler()); return observable; } else { throw new RuntimeException(String.format( "Endpoint '%s' get returned %d status", endpoint, response.statusCode())); } }) .map(buffer -> Json.decodeValue(buffer.toString(UTF_8.name()), ObjectNode.class)); }