From 293afab0f7b052d8de8f0aa36184fe5e13267b56 Mon Sep 17 00:00:00 2001 From: Matheus Cruz Date: Mon, 4 Nov 2024 09:51:57 -0300 Subject: [PATCH] Add detail about how to set/get context across live reloads --- .../src/main/asciidoc/writing-extensions.adoc | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/src/main/asciidoc/writing-extensions.adoc b/docs/src/main/asciidoc/writing-extensions.adoc index 727afd45f6d77..a1690b6e63822 100644 --- a/docs/src/main/asciidoc/writing-extensions.adoc +++ b/docs/src/main/asciidoc/writing-extensions.adoc @@ -1970,6 +1970,35 @@ information about this start, in particular: It also provides a global context map you can use to store information between restarts, without needing to resort to static fields. +Here is an example of a build step that persists context across live reloads: + +[source,java] +---- +@BuildStep(onlyIf = {IsDevelopment.class}) +public void keyPairDevService(LiveReloadBuildItem liveReloadBuildItem, BuildProducer devServices) { + +KeyPairContext ctx = liveReloadBuildItem.getContextObject(KeyPairContext.class); // <1> + if (ctx == null && !liveReloadBuildItem.isLiveReload()) { // <2> + KeyPair keyPair = KeyUtils.generateKeyPair(KEY_SIZE); + Map properties = generateDevServiceProperties(keyPair); + liveReloadBuildItem.setContext( // <3> + KeyPairContext.class, new KeyPairContext(properties)); + devServices.produce(smallryeJwtDevServiceWith(properties)); + } + + if (ctx != null) { + Map properties = ctx.getProperties(); + devServices.produce(smallryeJwtDevServiceWith(properties)); + } +} + +static record KeyPairContext(Map properties) {} +---- + +<1> You can retrieve the context from `LiveReloadBuildItem`. This call returns `null` if there is no context for the specified type; otherwise, it returns the stored instance from a previous live reload execution. +<2> You can check if this is the first execution (not a live reload). +<3> The `LiveReloadBuildItem#setContext` method allows you to set a context across live reloads. + ==== Triggering Live Reload Live reload is generally triggered by an HTTP request, however not all applications are HTTP applications and some extensions