From 0a5956182a15c347741a14c8ebb0e4ec8da8f8f9 Mon Sep 17 00:00:00 2001 From: Matheus Cruz Date: Mon, 4 Nov 2024 12:02:39 -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 727afd45f6d77d..fc78f9b1eccdcc 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 keyPairs) { + + KeyPairContext ctx = liveReloadBuildItem.getContextObject(KeyPairContext.class); // <1> + if (ctx == null && !liveReloadBuildItem.isLiveReload()) { // <2> + KeyPair keyPair = generateKeyPair(2048); + Map properties = generateDevServiceProperties(keyPair); + liveReloadBuildItem.setContextObject( // <3> + KeyPairContext.class, new KeyPairContext(properties)); + keyPairs.produce(new KeyPairBuildItem(properties)); + } + + if (ctx != null) { + Map properties = ctx.getProperties(); + keyPairs.produce(new KeyPairBuildItem(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