Creating anonymous snippets
We first need a web client object to issue HTTP requests to the Gist API:
webClient = WebClient.create(vertx, new WebClientOptions()
.setSsl(true)
.setUserAgent("vert-x3"));
Tip | Since requests are made using HTTPS, we need to configure the web client with SSL support. |
Tip | We override the default user agent with vert-x3 but you may opt to use your own value instead. |
We then modify the web router configuration in the HttpServerVerticle
class to add a new route for triggering backups:
router.get("/backup").handler(this::backupHandler);
The code for this handler is the following:
private void backupHandler(RoutingContext context) {
dbService.fetchAllPagesData(reply -> {
if (reply.succeeded()) {
JsonArray filesObject = new JsonArray();
JsonObject payload = new JsonObject() (1)
.put("files", filesObject)
.put("language", "plaintext")
.put("title", "vertx-wiki-backup")
.put("public", true);
reply
.result()
.forEach(page -> {
JsonObject fileObject = new JsonObject(); (2)
fileObject.put("name", page.getString("NAME"));
fileObject.put("content", page.getString("CONTENT"));
filesObject.add(fileObject);
});
webClient.post(443, "snippets.glot.io", "/snippets") (3)
.putHeader("Content-Type", "application/json")
.as(BodyCodec.jsonObject()) (4)
.sendJsonObject(payload, ar -> { (5)
if (ar.succeeded()) {
HttpResponse<JsonObject> response = ar.result();
if (response.statusCode() == 200) {
String url = "https://glot.io/snippets/" + response.body().getString("id");
context.put("backup_gist_url", url); (6)
indexHandler(context);
} else {
StringBuilder message = new StringBuilder()
.append("Could not backup the wiki: ")
.append(response.statusMessage());
JsonObject body = response.body();
if (body != null) {
message.append(System.getProperty("line.separator"))
.append(body.encodePrettily());
}
LOGGER.error(message.toString());
context.fail(502);
}
} else {
Throwable err = ar.cause();
LOGGER.error("HTTP Client error", err);
context.fail(err);
}
});
} else {
context.fail(reply.cause());
}
});
}
The snippet creation request payload is a JSON document as outlined in the service API documentation.
Each file is an entry under the
files
object of the payload, with a title and content.The web client needs to issue a
POST
request on port 443 (HTTPS), and the path must be/snippets
.The
BodyCodec
class provides a helper to specify that the response will be directly converted to a Vert.xJsonObject
instance. It is also possible to useBodyCodec#json(Class<T>)
and the JSON data will be mapped to a Java object of typeT
(this uses Jackson data mapping under the hood).sendJsonObject
is a helper for triggering the HTTP request with a JSON payload.Upon success we can get the snippet identifier, and construct a URL to the user-friendly web representation.