I have VertX application with a config.json file. I want to edit one of the properties in the file during an HTTP request.
Is it possible?
Json Config:
{
"REQUEST_OPTIONS": {
"dataFilter": [
{
"name": "xxx",
"values": [1, 2, 3] -> want to edit this specific field!
},
{
"name": "yyy",
"values": [4, 5, 6]
}
]
}
}
Start method:
@Override
public void start(Promise<Void> startPromise) {
CompositeFuture.all(
//Some other Futures ,
Future.future(ConfigRetriever.create(vertx)::getConfig)
.flatMap(config -> storeData(config)
.compose(maybeStoreData -> CompositeFuture.all(
matcherVerticle(subject).apply(maybeStoreData),
http(sharedData, maybeStoreData).apply(config)
))))
.<Void>mapEmpty()
.onComplete(startPromise);
Router code:
router.get("/api/action").handler(performAction(configJson));
Action request:
private Handler<RoutingContext> performAction(JsonObject config) {
return routingContext -> Try.of(() -> Json.decodeValue(routingContext.getBody(), RequestDto.class))
.onFailure(ex -> log.warn("Failed to process the RequestDto: ", ex))
.andThen(requestDto -> ???UPDATE CONFIG FILE according to requestDto ???)
.onFailure(ex -> log.warn("Failed to save request: ", ex))
.onFailure(ex -> routingContext.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()))
.onSuccess(handler -> routingContext.response().setStatusCode(HttpResponseStatus.OK.code()));
}
Given that you have your JsonObject already, you can write it to disk using fileSystem().writeFile()
.
Here's a full example:
Vertx vertx = Vertx.vertx();
var json = new JsonObject("{\n" +
" \"REQUEST_OPTIONS\": {\n" +
" \"dataFilter\": [\n" +
" {\n" +
" \"name\": \"xxx\",\n" +
" \"values\": [1, 2, 3]" +
" },\n" +
" {\n" +
" \"name\": \"yyy\",\n" +
" \"values\": [4, 5, 6]\n" +
" }\n" +
" ]\n" +
" }\n" +
"}");
json.copy()
.getJsonObject("REQUEST_OPTIONS")
// Accessing the dataFilter array
.getJsonArray("dataFilter")
// Getting the first element of dataFilter array
.getJsonObject(0)
// Accessing the values array
.getJsonArray("values")
.add(4);
vertx.fileSystem().writeFile("./new.json", json.toBuffer());