From e2bf21e148ff53a5f639e511925fab3b2713eacc Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:31:47 +0100 Subject: [PATCH 01/22] WW-5864 docs(spec): design for the struts:watch Maven goal Co-Authored-By: Claude Opus 5.5 --- ...-11-14-struts-maven-plugin-watch-design.md | 167 ++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-14-struts-maven-plugin-watch-design.md diff --git a/docs/superpowers/specs/2026-11-14-struts-maven-plugin-watch-design.md b/docs/superpowers/specs/2026-11-14-struts-maven-plugin-watch-design.md new file mode 100644 index 0000000000..01c977941f --- /dev/null +++ b/docs/superpowers/specs/2026-11-14-struts-maven-plugin-watch-design.md @@ -0,0 +1,167 @@ +# Struts Maven Plugin: `struts:watch` — Design + +Date: 2026-11-14 · Ticket: [WW-5864](https://issues.apache.org/jira/browse/WW-5864) · Status: approved + +## Intent + +Developers working on a Struts application under `mvn jetty:run` (or any server that runs +from `target/classes`) with `struts.devMode=true` expect edits to `struts.xml` and message +bundles to show up on the next request. Today they have to restart the server. + +A spike (2026-11-14, showcase app, devMode on, Jetty 11 plugin) showed that Struts' own +reloading works — the gap is in the build layout: + +| Change | Edited in `src/main/resources` | Same edit in `target/classes` | +|---|---|---| +| New action in `struts.xml` | not picked up | picked up on the next request | +| Message in `globalMessages.properties` | not picked up | picked up on the next request | +| Action class (recompiled) | — | old class keeps running | + +Struts watches the URL it loaded each file from (`DefaultFileManager` / `FileRevision`, +checked per request by `ConfigurationManager.conditionalReload()`). Under `jetty:run` that is +`target/classes/...`, and nothing copies edits there while the server runs. When something +does, Jetty's own scanner (`` in the showcase pom) additionally restarts the whole +webapp, duplicating the work Struts already did. + +`struts:watch` closes the copy gap: it watches the project's resource directories and pushes +changed files into the output directory through Maven's own resource processing, so Struts' +existing reload picks them up. + +## Goals + +- Save a resource file in `src/main/resources`, refresh the browser, see the change — no + server restart, no IDE build step, works from the command line. +- Honour the project's Maven resource configuration: the declared `` directories, + includes/excludes, `targetPath`, and filtering (`${...}` placeholders), so the file in + `target/classes` is exactly what `process-resources` would have produced. +- Run alongside whatever server the developer already uses (`jetty:run`, Cargo, Tomcat + plugin, an IDE-managed server) with no dependency on any of them. +- Help the developer see the loop working: log each file pushed, warn when Struts' reload + switches look off. + +## Non-goals + +- **Java class reloading.** Out of scope (decided). Developers keep using a restart or JVM + hotswap under a debugger. +- **Starting or embedding a server.** The plugin never owns Jetty/Tomcat (decided: alongside, + not a wrapper). +- **Webapp files (JSP/FTL in `src/main/webapp`).** Already served from source by `jetty:run`. +- **Gradle, and Struts Boot apps.** A later, separate question. +- **Multi-module applications** (resources in a jar module, `jetty:run` in the war module). + Single module only for now (decided). The goal watches the module it runs in; run from a + reactor with more than one project, it fails fast with a message to run it in the module + that owns the resources (`-pl `) instead of silently watching only the first one. +- **Any change to Struts core's reload mechanism.** The spike showed it works. + +## Anti-goals + +- A file in `target/classes` that differs from what `process-resources` would produce + (unfiltered placeholders, ignored excludes). Developers would chase phantom bugs. +- Anything that leaks into the deployed application — this is a build-time tool only. +- A save that triggers a full webapp restart in the documented setup. + +## Constraints + +- Lives in the Struts reactor, released with Struts. First `maven-plugin` packaging module in + the repo: needs `maven-plugin-plugin` and the Maven plugin API (`provided` scope). +- Java 17 (`maven.compiler.release` in the root pom). +- ASF naming: `maven-*-plugin` is reserved for Apache Maven; the artifact is + `struts-maven-plugin`, giving the prefix `struts` → `mvn struts:watch`. Prefix resolution + works when the plugin is declared in the application's pom (no `pluginGroups` needed). +- macOS: the JDK `WatchService` is polling-based with a ~10 s default interval there, which + is too slow for save-and-refresh. + +## Approaches considered + +1. **IDE build + Jetty scan config (docs only).** IntelliJ ⌘F9 / Eclipse auto-build already + copy resources. No code, but needs the IDE and a habit; no help from the CLI. +2. **Point Jetty's classloader at `src/main/resources` (pom recipe).** No code, no build step, + but loses resource filtering and it is unverified whether `extraClasspath` can precede + `target/classes`. +3. **Struts core watches source folders in devMode.** Server-agnostic, but bakes the Maven + layout into core, ignores filtering, and adds devMode code that reads outside the + classpath — new core surface and security review. +4. **Struts Maven plugin** — chosen. Two variants: + - **Alongside (`struts:watch`)** — chosen: small, no server dependency, survives server + version changes; costs a second command (or a background mode, see below). + - Wrapper (`struts:run` embedding a server) — rejected: Struts would own a server version, + its Jakarta line and every config option developers expect from `jetty:run`; effectively + a second Struts Boot. + +## Design + +### Module + +- Location: `tools/struts-maven-plugin` (new top-level `tools` aggregator; `plugins/` is + reserved for runtime Struts plugins). _My call._ +- `groupId` `org.apache.struts`, `artifactId` `struts-maven-plugin`, packaging `maven-plugin`. +- No dependency on `struts2-core` — it never loads Struts classes. + +### Goal `watch` + +- Default: blocking. Developer runs `mvn struts:watch` in a second terminal next to + `mvn jetty:run`. Ctrl+C stops it. +- Background mode (`true` / `-Dstruts.watch.background=true`): + the goal starts a daemon watcher thread and returns, so binding it to `process-resources` + in the app's pom makes `mvn jetty:run` alone enough (jetty:run forks the lifecycle, then + blocks; the watcher lives as long as the Maven JVM). _My call; the builder must verify the + thread survives `jetty:run`'s forked lifecycle._ +- A bound background execution is a no-op unless explicitly switched on + (`-Dstruts.watch=true`, typically `mvn jetty:run -Dstruts.watch`), so committing the binding + to an application pom never starts a watcher in `package`/`install`/CI/release builds. + _My call._ +- Watched roots: every `` directory from the project model (`project.getResources()`), + not a hard-coded `src/main/resources`. +- On change: re-process **only the changed file** with the project's resource settings via + `maven-filtering` (`MavenResourcesFiltering`, the library `maven-resources-plugin` uses), + honouring includes/excludes, `targetPath`, filtering, encoding and delimiters. Write to + `project.getBuild().getOutputDirectory()`. +- Filtering settings that are not in the project model (delimiters, `escapeString`, + `nonFilteredFileExtensions`, `propertiesEncoding`, `useDefaultDelimiters`, + `addDefaultExcludes`) are read from the effective `maven-resources-plugin` configuration of + the `default-resources` execution in the model — no mirror parameters on `struts:watch`, so + the two cannot drift. _My call._ +- A change to a filter file (`build.filters`) re-pushes every filtered resource. _My call._ +- Extra `copy-resources` executions writing into the output directory are out of scope. _My call._ +- On delete: remove the corresponding output file. +- Change detection: a last-modified/size polling scan of the watched roots at a configurable + interval (default 500 ms), not `WatchService`, because of the macOS constraint. Debounce so + an editor's save-via-rename produces one push. +- Logging: one INFO line per push (`pushed struts.xml → target/classes/struts.xml`). + +### Struts-specific help + +- At start, best-effort check of `struts.devMode`, `struts.configuration.xml.reload` and + `struts.i18n.reload` in the output directory's `struts.xml` / `struts.properties`; WARN when + devMode is explicitly `false` or a reload switch is explicitly `false`. Best-effort only — + constants set from Spring, Java config or system properties are invisible, so never fail. +- Docs show the Jetty plugin config that stops Jetty's scanner restarting on resource + changes. _Unverified whether Jetty 11/12's `scanClassesPattern` excludes cover this; the + builder must confirm, or document `0` as the fallback._ + +### Showcase and docs + +- `apps/showcase` declares the plugin with a bound background execution, inert without + `-Dstruts.watch` (so CI and the `jetty:start` ITs never run a watcher), and its Jetty config + is switched to the documented "no restart on resource change" setup — the showcase is the + reference setup. Showcase keeps `devMode=false` (it also runs the ITs). The plugin's own + invoker IT is what actually exercises the watcher. _My call._ +- The plugin's generated goal docs ship with the module; the struts-site usage page is a + follow-up PR in that repo. _My call._ +- Fix version comes from the ticket. + +## Testing + +- The watcher/copier is a plain class tested without Maven (JUnit 4, matching the repo): + change, add, delete, excluded file ignored, filtered placeholder resolved, `targetPath` + respected, debounce. +- One integration test through `maven-invoker-plugin` (or the plugin testing harness) on a + tiny fixture project running the goal in background mode. _Builder's choice of harness._ + +## Left to the builder + +- Exact `maven-plugin-plugin` / `maven-filtering` versions and the Maven API baseline. +- Thread/lifecycle handling for background mode and clean shutdown. +- Test harness for the integration test. +- Whether the `tools` aggregator joins the default reactor or a profile (default preferred, so + it is released with every Struts release). From 2471b04e08b0ca7cc489c8461a67139d36c3aa08 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:34:28 +0100 Subject: [PATCH 02/22] WW-5864 docs(plan): implementation plan for the struts:watch goal Co-Authored-By: Claude Opus 5.5 --- .../2026-11-14-struts-maven-plugin-watch.md | 314 ++++++++++++++++++ 1 file changed, 314 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-14-struts-maven-plugin-watch.md diff --git a/docs/superpowers/plans/2026-11-14-struts-maven-plugin-watch.md b/docs/superpowers/plans/2026-11-14-struts-maven-plugin-watch.md new file mode 100644 index 0000000000..2cd2efb609 --- /dev/null +++ b/docs/superpowers/plans/2026-11-14-struts-maven-plugin-watch.md @@ -0,0 +1,314 @@ +# `struts:watch` Maven Goal Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A `struts-maven-plugin` whose `watch` goal pushes changed resource files into +`target/classes` (with the project's own filtering), so Struts' devMode reload picks them up +without a server restart. + +**Architecture:** Pure, Maven-free core classes (scan → diff/debounce → push) behind a thin +`WatchMojo`. Pushing reuses `maven-filtering`'s `MavenResourcesFiltering` with settings read +from the project's effective `maven-resources-plugin` configuration. A best-effort inspector +warns when Struts' reload switches are off. One invoker IT drives the real goal. + +**Tech Stack:** Java 17, Maven Plugin API + annotations, `maven-filtering`, +`plexus-utils` (`DirectoryScanner`, `Xpp3Dom`), JUnit 4 + AssertJ, `maven-invoker-plugin`. + +**Spec:** `docs/superpowers/specs/2026-11-14-struts-maven-plugin-watch-design.md` (WW-5864) + +## Global Constraints + +- Every commit message starts `WW-5864 `; branch `feat/WW-5864-struts-maven-plugin-watch`. +- Module path `tools/struts-maven-plugin`; `groupId` `org.apache.struts`, `artifactId` + `struts-maven-plugin`, packaging `maven-plugin` → goal prefix `struts`. +- Java package `org.apache.struts2.maven.watch`. +- No dependency on `struts2-core`. Maven API artifacts are `provided` scope. +- Tests are JUnit 4 (`org.junit.Test`) + AssertJ. No Jupiter. +- Every new file carries the ASF license header (RAT runs in the build), including invoker + fixture files. +- Polling, not `WatchService`. Default interval 500 ms. +- Single module only: if the goal is about to run and `session.getProjects().size() > 1`, + fail with: `struts:watch supports a single module; run it in the module that owns the + resources, e.g. -pl `. +- Background mode does nothing unless `struts.watch=true`. Blocking mode always runs. +- Never fetch an external DTD while reading `struts.xml`. +- Default to no code comments (user's global rule); Javadoc only on Mojo parameters, where it + becomes the generated goal docs. +- Build with `./mvnw -B ... > log 2>&1; echo $?` and read the log; never judge a build from a + filtered pipe. + +## Review Focus + +1. **Editor atomic save** (temp file + rename, or delete-then-create within one poll): one + push, never a delete of the output file. → Task 2 test + `deleteFollowedByRecreateBeforeStableIsAPushNotADelete`. +2. **New file in a new sub-directory** (`com/acme/FooAction.properties`): output parent + directories are created. → Task 3 test `pushCreatesMissingParentDirectories`. +3. **`target/` cleaned while watching** (`mvn clean` in another terminal): the next change + still pushes. → Task 3 test `pushAfterOutputDirectoryDeletedRecreatesIt`. +4. **Push failure** (filtering error, locked file): logged, watcher keeps running. → Task 2 + test `pusherFailureIsReportedAndWatchingContinues`. +5. **Binary resource in a filtered directory** (an image under a `true` + resource): copied byte-for-byte via `nonFilteredFileExtensions`. → Task 3 test + `binaryFileInFilteredResourceIsCopiedUnchanged`. + +--- + +### Task 1: Module skeleton and resources-plugin settings + +**Files:** +- Create: `tools/pom.xml` (aggregator, `artifactId` `struts2-tools`, packaging `pom`, parent + `struts2-parent` with `relativePath` `../parent/pom.xml`, module `struts-maven-plugin`) +- Create: `tools/struts-maven-plugin/pom.xml` +- Modify: `pom.xml` (root ``: add `tools` after `boot`) +- Create: `tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java` +- Test: `tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java` + +**Interfaces:** +- Produces: `ResourcesPluginSettings` (immutable) with + `static ResourcesPluginSettings from(Xpp3Dom configuration, String projectEncoding)` (null + configuration → defaults) and getters `getEncoding()`, `getPropertiesEncoding()`, + `getDelimiters(): LinkedHashSet`, `isUseDefaultDelimiters()`, `getEscapeString()`, + `getNonFilteredFileExtensions(): List`, `isAddDefaultExcludes()`. +- Produces: `static Xpp3Dom effectiveResourcesConfiguration(MavenProject project)` on the same + class — the `maven-resources-plugin` plugin-level configuration merged with its + `default-resources` execution configuration (execution wins). + +- [ ] **Step 1: Plugin pom.** Parent `struts2-tools`. Plugins: `maven-plugin-plugin` 3.15.1 + (`goalPrefix` `struts`, `helpmojo` execution). Dependencies: `maven-plugin-api` and + `maven-core` 3.9.11 `provided`; `maven-plugin-annotations` 3.15.1 `provided`; + `org.apache.maven.shared:maven-filtering` 3.4.0; `junit`, `assertj-core` `test` (versions + from the parent's dependencyManagement). Check Central for newer releases of the four pinned + versions; prefer the newest that supports Java 17 and Maven 3.9. +- [ ] **Step 2: Write the failing tests** in `ResourcesPluginSettingsTest`: + - `defaultsWhenNoConfiguration`: `from(null, "UTF-8")` → encoding `UTF-8`, delimiters + empty, `isUseDefaultDelimiters()` true, `isAddDefaultExcludes()` true, + `getNonFilteredFileExtensions()` empty, escape string null. + - `readsAllFilteringSettings`: an `Xpp3Dom` built from + `ISO-8859-1UTF-8@false\pngfalse` + (parse with `Xpp3DomBuilder.build(new StringReader(...))`) → each getter returns that value. + - `executionConfigurationOverridesPluginConfiguration`: a `MavenProject` with a + `maven-resources-plugin` whose plugin config sets `encoding` `A` and whose + `default-resources` execution sets `encoding` `B` → `effectiveResourcesConfiguration` + yields `B`. +- [ ] **Step 3: Run** `./mvnw -B test -DskipAssembly -pl tools/struts-maven-plugin -am > /watch-build.log 2>&1; echo $?` + (log outside the repo — a log in the root fails RAT) — expect compile failure / test failures. +- [ ] **Step 4: Implement** `ResourcesPluginSettings`. Merge with + `Xpp3Dom.mergeXpp3Dom(execution, plugin)`. +- [ ] **Step 5: Run the tests** — expect PASS, and the full module build (`verify`) green + including RAT. +- [ ] **Step 6: Commit** `WW-5864 build(tools): add struts-maven-plugin module skeleton`. + +### Task 2: Scanning and the debounced watcher loop + +**Files:** +- Create: `.../watch/WatchedRoot.java`, `.../watch/FileStamp.java`, `.../watch/SourceFile.java`, + `.../watch/ResourceScanner.java`, `.../watch/ResourcePusher.java`, + `.../watch/ResourceWatcher.java` +- Test: `.../watch/ResourceScannerTest.java`, `.../watch/ResourceWatcherTest.java` + +**Interfaces:** +- Produces: `WatchedRoot` — `Path directory`, `List includes`, + `List excludes`, `String targetPath` (nullable), `boolean filtering`; built from a + Maven `Resource` with `static WatchedRoot of(Resource resource, Path basedir)`. +- Produces: `FileStamp(long lastModified, long size)` with value equality. +- Produces: `ResourceScanner` — `ResourceScanner(List roots, boolean + addDefaultExcludes)`, `Map scan()`, where + `SourceFile(WatchedRoot root, String relativePath)` has value equality. Uses + `DirectoryScanner` with the root's includes (default `**/**`) and excludes; a missing + root directory yields no entries. +- Produces: `ResourcePusher` interface — `void push(SourceFile file) throws IOException`, + `void delete(SourceFile file) throws IOException`. +- Produces: `ResourceWatcher` — `ResourceWatcher(ResourceScanner scanner, ResourcePusher + pusher, List filterFiles, Consumer info, BiConsumer error)`; + `void start()` (takes the baseline scan), `void pollOnce()`, `void run(Duration interval, + BooleanSupplier keepRunning)`. + +Debounce rule (not determined by the signatures): a path is acted on only when two +consecutive scans agree on it after it differed from the last acted-on state — present with +the same stamp in both → `push`; absent in both → `delete`. A filter-file stamp change, once +stable across two scans, pushes every file whose root has `filtering == true`. + +- [ ] **Step 1: Write the failing tests.** `ResourceScannerTest` (temp dirs via + `TemporaryFolder`): `listsFilesHonouringIncludesAndExcludes`, + `skipsDefaultExcludesWhenEnabled` (`.DS_Store`/`*~` ignored), + `missingRootDirectoryYieldsNoFiles`. `ResourceWatcherTest` with a recording fake pusher and a + fake scanner fed a list of scan results: + - `changeIsPushedOnceAfterTwoStableScans` → after scans `{a:1}`,`{a:2}`,`{a:2}`,`{a:2}`: + pushes `[a]`. + - `deletionIsMirroredAfterTwoStableScans` → `{a:1}`,`{}`,`{}`: deletes `[a]`. + - `deleteFollowedByRecreateBeforeStableIsAPushNotADelete` → `{a:1}`,`{}`,`{a:2}`,`{a:2}`: + deletes `[]`, pushes `[a]`. + - `unchangedFilesAreNeverPushed` → `{a:1}`,`{a:1}`,`{a:1}`: pushes `[]`. + - `filterFileChangeRepushesFilteredResourcesOnly` → filtered root file `f`, unfiltered `u`, + filter-file stamp changes and stabilises: pushes `[f]`. + - `pusherFailureIsReportedAndWatchingContinues` → pusher throws on `a`, then `b` changes: + `error` called once for `a`, `b` still pushed. + - `runStopsWhenKeepRunningTurnsFalse` → `run(Duration.ofMillis(10), ...)` returns. +- [ ] **Step 2: Run** — expect FAIL (classes missing). +- [ ] **Step 3: Implement** the five types. `ResourceScanner` should be non-final with + `scan()` overridable, so tests can feed scans. +- [ ] **Step 4: Run** — expect PASS. +- [ ] **Step 5: Commit** `WW-5864 feat(tools): scan resource roots and debounce changes`. + +### Task 3: Filtering pusher + +**Files:** +- Create: `.../watch/FilteringResourcePusher.java` +- Test: `.../watch/FilteringResourcePusherTest.java` + +**Interfaces:** +- Consumes: `ResourcePusher`, `SourceFile`, `WatchedRoot` (Task 2); `ResourcesPluginSettings` + (Task 1). +- Produces: `FilteringResourcePusher(MavenResourcesFiltering filtering, MavenProject project, + MavenSession session, ResourcesPluginSettings settings, Path outputDirectory)`, plus + `Path outputPathOf(SourceFile file)` = `outputDirectory[/targetPath]/relativePath`. + +- [ ] **Step 1: Write the failing tests** (use `DefaultMavenResourcesFiltering` wired by hand + or via a Sisu/`PlexusTestCase`-free construction; temp dirs): + - `pushCopiesUnfilteredFile` → bytes equal. + - `pushFiltersPlaceholdersFromProjectProperties` → source `name=${greeting}`, project + property `greeting=hi` → output `name=hi`. + - `pushHonoursCustomDelimiter` → settings delimiter `@`, source `name=@greeting@` → `name=hi`. + - `pushHonoursTargetPath` → root `targetPath` `conf` → output at `conf/a.xml`. + - `pushCreatesMissingParentDirectories` → `com/acme/FooAction.properties` lands. + - `pushAfterOutputDirectoryDeletedRecreatesIt`. + - `binaryFileInFilteredResourceIsCopiedUnchanged` → `nonFilteredFileExtensions` `png`, + a PNG with `${` bytes stays byte-identical. + - `deleteRemovesOutputFile` and `deleteOfMissingOutputIsANoOp`. +- [ ] **Step 2: Run** — expect FAIL. +- [ ] **Step 3: Implement.** For `push`, build a one-file `Resource` (directory = root, + `includes` = the relative path, `targetPath`, `filtering`) and call + `MavenResourcesFiltering.filterResources(MavenResourcesExecution)` with the settings + applied (encoding, propertiesEncoding, delimiters, useDefaultDelimiters, escapeString, + nonFilteredFileExtensions, `build.filters`, overwrite = true). +- [ ] **Step 4: Run** — expect PASS. +- [ ] **Step 5: Commit** `WW-5864 feat(tools): push changed resources through maven-filtering`. + +### Task 4: Struts reload-settings inspector + +**Files:** +- Create: `.../watch/StrutsReloadInspector.java` +- Test: `.../watch/StrutsReloadInspectorTest.java` + +**Interfaces:** +- Produces: `StrutsReloadInspector(Path outputDirectory)`, `List warnings()`. + +Rule (mirrors `StrutsBeanSelectionProvider#switchDevMode`): read `` from +`outputDirectory/struts.xml` and keys from `outputDirectory/struts.properties` (properties win +on conflict). Effective `struts.configuration.xml.reload` / `struts.i18n.reload` = explicit +value if present, else the devMode value. Warn per switch that is effectively not `true`. +Missing files, parse errors and absent keys produce no exception; when neither file sets +`struts.devMode`, emit one soft warning that devMode was not found (it may be set elsewhere). + +- [ ] **Step 1: Write the failing tests:** + - `devModeTrueNoWarnings`. + - `devModeFalseWarnsForBothReloadSwitches` → two warnings naming + `struts.configuration.xml.reload` and `struts.i18n.reload`. + - `explicitFalseOverridesDevMode` → devMode `true`, `struts.i18n.reload` `false` → one + warning naming `struts.i18n.reload`. + - `propertiesFileOverridesXml`. + - `devModeNotFoundGivesSoftWarning`. + - `doesNotFetchExternalDtd` → `struts.xml` with + `` parses and yields the + constants (no network). + - `malformedXmlProducesNoException`. +- [ ] **Step 2: Run** — expect FAIL. +- [ ] **Step 3: Implement** with `DocumentBuilderFactory`: disable + `http://apache.org/xml/features/nonvalidating/load-external-dtd`, external general and + parameter entities, and XInclude; set `setExpandEntityReferences(false)`. +- [ ] **Step 4: Run** — expect PASS. +- [ ] **Step 5: Commit** `WW-5864 feat(tools): warn when Struts reload switches are off`. + +### Task 5: `WatchMojo` + +**Files:** +- Create: `.../watch/WatchMojo.java` +- Test: `.../watch/WatchMojoTest.java` + +**Interfaces:** +- Consumes: everything above. +- Produces: `@Mojo(name = "watch", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, + threadSafe = true)` with parameters: + - `pollInterval` (`long`, ms, default `500`, property `struts.watch.pollInterval`) + - `background` (`boolean`, default `false`, property `struts.watch.background`) + - `enabled` (`boolean`, default `false`, property `struts.watch`) — consulted only when + `background` is true + - `timeout` (`long`, seconds, default `0` = until stopped, property `struts.watch.timeout`) + — blocking mode stops after it; used by scripted runs and the IT + - injected `MavenProject`, `MavenSession`, `MavenResourcesFiltering`. +- Produces: package-private `boolean shouldRun()` and `void checkSingleModule()` for tests. + +Behaviour: `background && !enabled` → log one debug line, return. Otherwise +`checkSingleModule()`; log inspector warnings at WARN; build roots from +`project.getResources()`; at start push every file whose output is missing or older than its +source; then blocking → `watcher.run(...)` on the calling thread until Ctrl+C or `timeout`; +background → start a daemon thread named `struts-watch` running `watcher.run(...)` and +return. Log one INFO line per push: `pushed -> `. + +- [ ] **Step 1: Write the failing tests:** + - `backgroundWithoutEnabledDoesNotRun` → `shouldRun()` false. + - `backgroundWithEnabledRuns` and `blockingAlwaysRuns`. + - `multiModuleSessionFailsWithGuidance` → `checkSingleModule()` throws + `MojoFailureException` whose message contains `-pl `. + - `staleOutputsArePushedAtStart` → source newer than output gets pushed, up-to-date one not. +- [ ] **Step 2: Run** — expect FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** — expect PASS; `./mvnw -B verify -DskipAssembly -pl tools/struts-maven-plugin -am` green, and the generated `struts:help` lists the four parameters. +- [ ] **Step 5: Commit** `WW-5864 feat(tools): add the struts:watch goal`. + +### Task 6: Invoker integration test + +**Files:** +- Modify: `tools/struts-maven-plugin/pom.xml` (`maven-invoker-plugin` 3.9.1: `install` + + `integration-test` + `verify`, `cloneProjectsTo` `target/it`, `postBuildHookScript` + `verify`, `preBuildHookScript` `prebuild`) +- Create: `tools/struts-maven-plugin/src/it/watch-pushes-change/{pom.xml,invoker.properties,prebuild.groovy,verify.groovy,src/main/resources/struts.xml,src/main/resources/messages.properties}` + +- [ ] **Step 1: Fixture.** Pom declares the plugin at `@project.version@`, a filtered resource + directory, and property `greeting=hi`. `messages.properties` is `msg=${greeting}-v1`. + `invoker.properties`: `invoker.goals = process-resources ${project.groupId}:${project.artifactId}:${project.version}:watch -Dstruts.watch.timeout=20`. +- [ ] **Step 2: `prebuild.groovy`** starts a daemon thread that sleeps 8 s, then rewrites + `src/main/resources/messages.properties` to `msg=${greeting}-v2` and deletes nothing. +- [ ] **Step 3: `verify.groovy`** asserts `target/classes/messages.properties` contains + `msg=hi-v2` and `build.log` contains `pushed messages.properties`. +- [ ] **Step 4: Run** `./mvnw -B verify -DskipAssembly -pl tools/struts-maven-plugin -am` — + expect the IT to pass. Then temporarily break the push (return early in + `FilteringResourcePusher.push`) and confirm the IT fails; revert. +- [ ] **Step 5: Commit** `WW-5864 test(tools): invoker IT for struts:watch`. + +### Task 7: Showcase reference setup and Jetty scanner + +**Files:** +- Modify: `apps/showcase/pom.xml` (Jetty plugin config; add `struts-maven-plugin` with an + execution `watch` bound to `process-resources`, `true`) +- Modify: `apps/rest-showcase/pom.xml` (Jetty scanner config only) + +- [ ] **Step 1: Find the Jetty 11 scanner setting** that keeps scanning compiled classes but + ignores resource files in `target/classes`: check `jetty-maven-plugin` 11.0.26's + `scanClassesPattern` (``). Record the outcome in the commit message. If no such + exclude exists, set `0` instead. +- [ ] **Step 2: Apply** it to both showcase poms and add the bound background execution to + `apps/showcase/pom.xml`. +- [ ] **Step 3: Prove CI stays inert:** `./mvnw -B package -DskipTests -DskipITs -DskipAssembly -pl apps/showcase -am` + exits 0 and the log has no `pushed` / `struts-watch` lines. +- [ ] **Step 4: Manual end-to-end check** (temporarily set `struts.devMode=true` in the + showcase `struts.xml`, do not commit it): + `./mvnw -B -pl apps/showcase -DskipAssembly -Dstruts.watch jetty:run`, then add a probe + action to `src/main/resources/struts.xml` and change a key in `globalMessages.properties`. + Expect: a `pushed` line for each, the new action answering on the next request, the new + message rendering, and no Jetty `Restarting` line. This is the check that the background + thread survives `jetty:run`'s forked lifecycle. +- [ ] **Step 5: Commit** `WW-5864 build(showcase): reference struts:watch setup and Jetty scanner`. + +### Task 8: Docs + +**Files:** +- Create: `tools/struts-maven-plugin/README.md` (RAT excludes `**/README.md`) + +- [ ] **Step 1:** README: what the goal does and does not do (Java classes out of scope), + the two ways to run it (`mvn struts:watch -pl ` next to the server; + `mvn jetty:run -Dstruts.watch` with the bound execution), the four parameters, the Jetty + scanner setting from Task 7, and the single-module limitation. +- [ ] **Step 2: Commit** `WW-5864 docs(tools): struts-maven-plugin usage`. The struts-site + page is a follow-up PR in that repo. From cf10e4632b02d11593be71ffa041647f832f7d74 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:38:07 +0100 Subject: [PATCH 03/22] WW-5864 build(tools): add struts-maven-plugin module skeleton Co-Authored-By: Claude Sonnet 5.5 --- pom.xml | 1 + tools/pom.xml | 38 +++++ tools/struts-maven-plugin/pom.xml | 105 ++++++++++++++ .../maven/watch/ResourcesPluginSettings.java | 130 ++++++++++++++++++ .../watch/ResourcesPluginSettingsTest.java | 88 ++++++++++++ 5 files changed, 362 insertions(+) create mode 100644 tools/pom.xml create mode 100644 tools/struts-maven-plugin/pom.xml create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java create mode 100644 tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java diff --git a/pom.xml b/pom.xml index d94f5aeb08..19d190ee02 100644 --- a/pom.xml +++ b/pom.xml @@ -88,6 +88,7 @@ core plugins boot + tools apps diff --git a/tools/pom.xml b/tools/pom.xml new file mode 100644 index 0000000000..2f52cfe491 --- /dev/null +++ b/tools/pom.xml @@ -0,0 +1,38 @@ + + + + 4.0.0 + + org.apache.struts + struts2-parent + 7.5.0-SNAPSHOT + ../parent/pom.xml + + + struts2-tools + pom + Struts 2 Tools + + + struts-maven-plugin + + diff --git a/tools/struts-maven-plugin/pom.xml b/tools/struts-maven-plugin/pom.xml new file mode 100644 index 0000000000..44809796e2 --- /dev/null +++ b/tools/struts-maven-plugin/pom.xml @@ -0,0 +1,105 @@ + + + + 4.0.0 + + org.apache.struts + struts2-tools + 7.5.0-SNAPSHOT + ../pom.xml + + + struts-maven-plugin + maven-plugin + Struts 2 Maven Plugin + + + 3.9.16 + 3.16.0 + + + + + + maven-jar-plugin + + + + + + org.apache.maven.plugins + maven-plugin-plugin + ${maven.plugin.tools.version} + + struts + + + + help-mojo + + helpmojo + + + org.apache.struts2.maven.watch + + + + + + + + + + org.apache.maven + maven-plugin-api + ${maven.api.version} + provided + + + org.apache.maven + maven-core + ${maven.api.version} + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + ${maven.plugin.tools.version} + provided + + + org.apache.maven.shared + maven-filtering + 3.5.1 + + + junit + junit + test + + + org.assertj + assertj-core + test + + + diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java new file mode 100644 index 0000000000..8640f5c774 --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java @@ -0,0 +1,130 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; + +public final class ResourcesPluginSettings { + + private static final String RESOURCES_PLUGIN_KEY = "org.apache.maven.plugins:maven-resources-plugin"; + private static final String RESOURCES_EXECUTION_ID = "default-resources"; + + private final String encoding; + private final String propertiesEncoding; + private final LinkedHashSet delimiters; + private final boolean useDefaultDelimiters; + private final String escapeString; + private final List nonFilteredFileExtensions; + private final boolean addDefaultExcludes; + + private ResourcesPluginSettings(String encoding, String propertiesEncoding, LinkedHashSet delimiters, + boolean useDefaultDelimiters, String escapeString, + List nonFilteredFileExtensions, boolean addDefaultExcludes) { + this.encoding = encoding; + this.propertiesEncoding = propertiesEncoding; + this.delimiters = delimiters; + this.useDefaultDelimiters = useDefaultDelimiters; + this.escapeString = escapeString; + this.nonFilteredFileExtensions = Collections.unmodifiableList(nonFilteredFileExtensions); + this.addDefaultExcludes = addDefaultExcludes; + } + + public static ResourcesPluginSettings from(Xpp3Dom configuration, String projectEncoding) { + return new ResourcesPluginSettings( + text(configuration, "encoding", projectEncoding), + text(configuration, "propertiesEncoding", null), + new LinkedHashSet<>(texts(configuration, "delimiters")), + flag(configuration, "useDefaultDelimiters"), + text(configuration, "escapeString", null), + texts(configuration, "nonFilteredFileExtensions"), + flag(configuration, "addDefaultExcludes")); + } + + public static Xpp3Dom effectiveResourcesConfiguration(MavenProject project) { + Plugin plugin = project.getBuild().getPluginsAsMap().get(RESOURCES_PLUGIN_KEY); + if (plugin == null) { + return null; + } + Xpp3Dom pluginConfiguration = (Xpp3Dom) plugin.getConfiguration(); + PluginExecution execution = plugin.getExecutionsAsMap().get(RESOURCES_EXECUTION_ID); + Xpp3Dom executionConfiguration = execution == null ? null : (Xpp3Dom) execution.getConfiguration(); + if (executionConfiguration == null) { + return pluginConfiguration; + } + return Xpp3Dom.mergeXpp3Dom(new Xpp3Dom(executionConfiguration), pluginConfiguration); + } + + private static String text(Xpp3Dom configuration, String name, String fallback) { + Xpp3Dom child = configuration == null ? null : configuration.getChild(name); + return child == null || child.getValue() == null ? fallback : child.getValue(); + } + + private static boolean flag(Xpp3Dom configuration, String name) { + return Boolean.parseBoolean(text(configuration, name, "true")); + } + + private static List texts(Xpp3Dom configuration, String name) { + List values = new ArrayList<>(); + Xpp3Dom parent = configuration == null ? null : configuration.getChild(name); + if (parent != null) { + for (Xpp3Dom child : parent.getChildren()) { + if (child.getValue() != null) { + values.add(child.getValue()); + } + } + } + return values; + } + + public String getEncoding() { + return encoding; + } + + public String getPropertiesEncoding() { + return propertiesEncoding; + } + + public LinkedHashSet getDelimiters() { + return new LinkedHashSet<>(delimiters); + } + + public boolean isUseDefaultDelimiters() { + return useDefaultDelimiters; + } + + public String getEscapeString() { + return escapeString; + } + + public List getNonFilteredFileExtensions() { + return nonFilteredFileExtensions; + } + + public boolean isAddDefaultExcludes() { + return addDefaultExcludes; + } +} diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java new file mode 100644 index 0000000000..a7e05ed66a --- /dev/null +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.xml.Xpp3DomBuilder; +import org.junit.Test; + +import java.io.StringReader; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ResourcesPluginSettingsTest { + + @Test + public void defaultsWhenNoConfiguration() { + ResourcesPluginSettings settings = ResourcesPluginSettings.from(null, "UTF-8"); + + assertThat(settings.getEncoding()).isEqualTo("UTF-8"); + assertThat(settings.getDelimiters()).isEmpty(); + assertThat(settings.isUseDefaultDelimiters()).isTrue(); + assertThat(settings.isAddDefaultExcludes()).isTrue(); + assertThat(settings.getNonFilteredFileExtensions()).isEmpty(); + assertThat(settings.getEscapeString()).isNull(); + } + + @Test + public void readsAllFilteringSettings() throws Exception { + Xpp3Dom configuration = Xpp3DomBuilder.build(new StringReader( + "ISO-8859-1" + + "UTF-8" + + "@" + + "false" + + "\\" + + "png" + + "false")); + + ResourcesPluginSettings settings = ResourcesPluginSettings.from(configuration, "UTF-8"); + + assertThat(settings.getEncoding()).isEqualTo("ISO-8859-1"); + assertThat(settings.getPropertiesEncoding()).isEqualTo("UTF-8"); + assertThat(settings.getDelimiters()).containsExactly("@"); + assertThat(settings.isUseDefaultDelimiters()).isFalse(); + assertThat(settings.getEscapeString()).isEqualTo("\\"); + assertThat(settings.getNonFilteredFileExtensions()).isEqualTo(List.of("png")); + assertThat(settings.isAddDefaultExcludes()).isFalse(); + } + + @Test + public void executionConfigurationOverridesPluginConfiguration() throws Exception { + Plugin plugin = new Plugin(); + plugin.setGroupId("org.apache.maven.plugins"); + plugin.setArtifactId("maven-resources-plugin"); + plugin.setConfiguration(Xpp3DomBuilder.build(new StringReader( + "A"))); + PluginExecution execution = new PluginExecution(); + execution.setId("default-resources"); + execution.setConfiguration(Xpp3DomBuilder.build(new StringReader( + "B"))); + plugin.addExecution(execution); + MavenProject project = new MavenProject(); + project.getBuild().addPlugin(plugin); + + Xpp3Dom effective = ResourcesPluginSettings.effectiveResourcesConfiguration(project); + + assertThat(effective.getChild("encoding").getValue()).isEqualTo("B"); + } +} From 4ae6d976eb9d83182a7c35a7f96496dcbc930a88 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:40:44 +0100 Subject: [PATCH 04/22] WW-5864 feat(tools): scan resource roots and debounce changes Co-Authored-By: Claude Sonnet 5.5 --- .../apache/struts2/maven/watch/FileStamp.java | 22 ++ .../struts2/maven/watch/ResourcePusher.java | 28 +++ .../struts2/maven/watch/ResourceScanner.java | 61 ++++++ .../struts2/maven/watch/ResourceWatcher.java | 141 +++++++++++++ .../struts2/maven/watch/SourceFile.java | 22 ++ .../struts2/maven/watch/WatchedRoot.java | 37 ++++ .../maven/watch/ResourceScannerTest.java | 98 +++++++++ .../maven/watch/ResourceWatcherTest.java | 194 ++++++++++++++++++ 8 files changed, 603 insertions(+) create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FileStamp.java create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcePusher.java create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceScanner.java create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/SourceFile.java create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchedRoot.java create mode 100644 tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java create mode 100644 tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FileStamp.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FileStamp.java new file mode 100644 index 0000000000..d8aa7196f2 --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FileStamp.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +public record FileStamp(long lastModified, long size) { +} diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcePusher.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcePusher.java new file mode 100644 index 0000000000..132860705a --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcePusher.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import java.io.IOException; + +public interface ResourcePusher { + + void push(SourceFile file) throws IOException; + + void delete(SourceFile file) throws IOException; +} diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceScanner.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceScanner.java new file mode 100644 index 0000000000..7d84ce6126 --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceScanner.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.codehaus.plexus.util.DirectoryScanner; + +import java.io.File; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class ResourceScanner { + + private final List roots; + private final boolean addDefaultExcludes; + + public ResourceScanner(List roots, boolean addDefaultExcludes) { + this.roots = List.copyOf(roots); + this.addDefaultExcludes = addDefaultExcludes; + } + + public Map scan() { + Map result = new LinkedHashMap<>(); + for (WatchedRoot root : roots) { + File directory = root.directory().toFile(); + if (!directory.isDirectory()) { + continue; + } + DirectoryScanner scanner = new DirectoryScanner(); + scanner.setBasedir(directory); + scanner.setIncludes(root.includes().isEmpty() ? new String[]{"**/**"} + : root.includes().toArray(new String[0])); + scanner.setExcludes(root.excludes().toArray(new String[0])); + if (addDefaultExcludes) { + scanner.addDefaultExcludes(); + } + scanner.scan(); + for (String relativePath : scanner.getIncludedFiles()) { + File file = new File(directory, relativePath); + result.put(new SourceFile(root, relativePath), new FileStamp(file.lastModified(), file.length())); + } + } + return result; + } +} diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java new file mode 100644 index 0000000000..49c33d85ce --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; + +public class ResourceWatcher { + + private final ResourceScanner scanner; + private final ResourcePusher pusher; + private final List filterFiles; + private final Consumer info; + private final BiConsumer error; + + private Map previous = Map.of(); + private Map acted = Map.of(); + private Map previousFilterStamps = Map.of(); + private Map actedFilterStamps = Map.of(); + + public ResourceWatcher(ResourceScanner scanner, ResourcePusher pusher, List filterFiles, + Consumer info, BiConsumer error) { + this.scanner = scanner; + this.pusher = pusher; + this.filterFiles = List.copyOf(filterFiles); + this.info = info; + this.error = error; + } + + public void start() { + previous = scanner.scan(); + acted = previous; + previousFilterStamps = filterStamps(); + actedFilterStamps = previousFilterStamps; + } + + public void pollOnce() { + Map current = scanner.scan(); + Map currentFilterStamps = filterStamps(); + Set handled = new HashSet<>(); + + Set paths = new HashSet<>(current.keySet()); + paths.addAll(previous.keySet()); + paths.addAll(acted.keySet()); + Map nextActed = new HashMap<>(acted); + for (SourceFile file : paths) { + FileStamp now = current.get(file); + if (Objects.equals(now, previous.get(file)) && !Objects.equals(now, acted.get(file))) { + if (now == null) { + nextActed.remove(file); + delete(file); + } else { + nextActed.put(file, now); + push(file); + handled.add(file); + } + } + } + + if (currentFilterStamps.equals(previousFilterStamps) && !currentFilterStamps.equals(actedFilterStamps)) { + actedFilterStamps = currentFilterStamps; + for (SourceFile file : current.keySet()) { + if (file.root().filtering() && !handled.contains(file)) { + push(file); + } + } + } + + acted = nextActed; + previous = current; + previousFilterStamps = currentFilterStamps; + } + + public void run(Duration interval, BooleanSupplier keepRunning) { + while (keepRunning.getAsBoolean()) { + pollOnce(); + try { + Thread.sleep(interval.toMillis()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + + private void push(SourceFile file) { + try { + pusher.push(file); + info.accept("Pushed " + file.relativePath()); + } catch (IOException | RuntimeException e) { + error.accept("Failed to push " + file.relativePath(), e); + } + } + + private void delete(SourceFile file) { + try { + pusher.delete(file); + info.accept("Deleted " + file.relativePath()); + } catch (IOException | RuntimeException e) { + error.accept("Failed to delete " + file.relativePath(), e); + } + } + + private Map filterStamps() { + Map stamps = new HashMap<>(); + for (Path path : filterFiles) { + File file = path.toFile(); + if (file.isFile()) { + stamps.put(path, new FileStamp(file.lastModified(), file.length())); + } + } + return stamps; + } +} diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/SourceFile.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/SourceFile.java new file mode 100644 index 0000000000..16b95b1c69 --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/SourceFile.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +public record SourceFile(WatchedRoot root, String relativePath) { +} diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchedRoot.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchedRoot.java new file mode 100644 index 0000000000..68b8194ab8 --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchedRoot.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.model.Resource; + +import java.nio.file.Path; +import java.util.List; + +public record WatchedRoot(Path directory, List includes, List excludes, String targetPath, + boolean filtering) { + + public static WatchedRoot of(Resource resource, Path basedir) { + return new WatchedRoot( + basedir.resolve(resource.getDirectory()), + List.copyOf(resource.getIncludes()), + List.copyOf(resource.getExcludes()), + resource.getTargetPath(), + resource.isFiltering()); + } +} diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java new file mode 100644 index 0000000000..93d9a734ed --- /dev/null +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ResourceScannerTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + private WatchedRoot root(Path dir, List includes, List excludes) { + return new WatchedRoot(dir, includes, excludes, null, false); + } + + private Set paths(Map scan) { + return scan.keySet().stream().map(SourceFile::relativePath) + .map(p -> p.replace(File.separatorChar, '/')).collect(Collectors.toSet()); + } + + @Test + public void listsFilesHonouringIncludesAndExcludes() throws Exception { + Path dir = temp.newFolder("res").toPath(); + Files.createDirectories(dir.resolve("sub")); + Files.writeString(dir.resolve("a.properties"), "a=1"); + Files.writeString(dir.resolve("sub/b.properties"), "b=1"); + Files.writeString(dir.resolve("c.txt"), "c"); + Files.writeString(dir.resolve("sub/skip.properties"), "s"); + + ResourceScanner scanner = new ResourceScanner( + List.of(root(dir, List.of("**/*.properties"), List.of("**/skip.*"))), true); + + Map scan = scanner.scan(); + + assertThat(paths(scan)).containsExactlyInAnyOrder("a.properties", "sub/b.properties"); + assertThat(scan.get(new SourceFile(root(dir, List.of("**/*.properties"), List.of("**/skip.*")), "a.properties")).size()) + .isEqualTo(3); + } + + @Test + public void emptyIncludesMeansEverything() throws Exception { + Path dir = temp.newFolder("res").toPath(); + Files.writeString(dir.resolve("a.txt"), "a"); + Files.writeString(dir.resolve("b.xml"), "b"); + + ResourceScanner scanner = new ResourceScanner(List.of(root(dir, List.of(), List.of())), true); + + assertThat(paths(scanner.scan())).containsExactlyInAnyOrder("a.txt", "b.xml"); + } + + @Test + public void skipsDefaultExcludesWhenEnabled() throws Exception { + Path dir = temp.newFolder("res").toPath(); + Files.writeString(dir.resolve("a.txt"), "a"); + Files.writeString(dir.resolve(".DS_Store"), "x"); + Files.writeString(dir.resolve("a.txt~"), "x"); + + assertThat(paths(new ResourceScanner(List.of(root(dir, List.of(), List.of())), true).scan())) + .containsExactly("a.txt"); + assertThat(paths(new ResourceScanner(List.of(root(dir, List.of(), List.of())), false).scan())) + .contains("a.txt", ".DS_Store", "a.txt~"); + } + + @Test + public void missingRootDirectoryYieldsNoFiles() { + Path dir = temp.getRoot().toPath().resolve("absent"); + + assertThat(new ResourceScanner(List.of(root(dir, List.of(), List.of())), true).scan()).isEmpty(); + } +} diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java new file mode 100644 index 0000000000..36f7d2af98 --- /dev/null +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java @@ -0,0 +1,194 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ResourceWatcherTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + private final WatchedRoot plain = new WatchedRoot(Path.of("plain"), List.of(), List.of(), null, false); + private final WatchedRoot filtered = new WatchedRoot(Path.of("filtered"), List.of(), List.of(), null, true); + + private final List pushed = new ArrayList<>(); + private final List deleted = new ArrayList<>(); + private final List errors = new ArrayList<>(); + private final List failOn = new ArrayList<>(); + + private final ResourcePusher pusher = new ResourcePusher() { + @Override + public void push(SourceFile file) throws IOException { + if (failOn.contains(file.relativePath())) { + throw new IOException("boom " + file.relativePath()); + } + pushed.add(file.relativePath()); + } + + @Override + public void delete(SourceFile file) { + deleted.add(file.relativePath()); + } + }; + + private static class FakeScanner extends ResourceScanner { + private final Deque> scans = new ArrayDeque<>(); + + FakeScanner() { + super(List.of(), true); + } + + FakeScanner add(Map scan) { + scans.add(scan); + return this; + } + + @Override + public Map scan() { + return scans.size() > 1 ? scans.poll() : scans.peek(); + } + } + + private Map scan(WatchedRoot root, Object... pathAndStamp) { + Map result = new LinkedHashMap<>(); + for (int i = 0; i < pathAndStamp.length; i += 2) { + result.put(new SourceFile(root, (String) pathAndStamp[i]), + new FileStamp(((Number) pathAndStamp[i + 1]).longValue(), 1)); + } + return result; + } + + private ResourceWatcher watcher(FakeScanner scanner, List filterFiles) { + return new ResourceWatcher(scanner, pusher, filterFiles, m -> { }, (m, e) -> errors.add(m)); + } + + private void drive(ResourceWatcher watcher, int polls) { + watcher.start(); + for (int i = 0; i < polls; i++) { + watcher.pollOnce(); + } + } + + @Test + public void changeIsPushedOnceAfterTwoStableScans() { + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)).add(scan(plain, "a", 2)); + drive(watcher(scanner, List.of()), 3); + + assertThat(pushed).containsExactly("a"); + assertThat(deleted).isEmpty(); + } + + @Test + public void changeIsNotPushedAfterOnlyOneScan() { + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)).add(scan(plain, "a", 2)); + drive(watcher(scanner, List.of()), 1); + + assertThat(pushed).isEmpty(); + } + + @Test + public void deletionIsMirroredAfterTwoStableScans() { + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)).add(scan(plain)); + drive(watcher(scanner, List.of()), 2); + + assertThat(deleted).containsExactly("a"); + assertThat(pushed).isEmpty(); + } + + @Test + public void deleteFollowedByRecreateBeforeStableIsAPushNotADelete() { + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)).add(scan(plain)) + .add(scan(plain, "a", 2)); + drive(watcher(scanner, List.of()), 3); + + assertThat(deleted).isEmpty(); + assertThat(pushed).containsExactly("a"); + } + + @Test + public void unchangedFilesAreNeverPushed() { + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)); + drive(watcher(scanner, List.of()), 3); + + assertThat(pushed).isEmpty(); + assertThat(deleted).isEmpty(); + } + + @Test + public void filterFileChangeRepushesFilteredResourcesOnly() throws Exception { + Path filterFile = temp.newFile("filter.properties").toPath(); + Files.writeString(filterFile, "k=v"); + Map files = scan(filtered, "f", 1); + files.putAll(scan(plain, "u", 1)); + FakeScanner scanner = new FakeScanner().add(files); + ResourceWatcher watcher = watcher(scanner, List.of(filterFile)); + watcher.start(); + + Files.writeString(filterFile, "k=changed-longer"); + watcher.pollOnce(); + assertThat(pushed).isEmpty(); + watcher.pollOnce(); + + assertThat(pushed).containsExactly("f"); + watcher.pollOnce(); + assertThat(pushed).containsExactly("f"); + } + + @Test + public void pusherFailureIsReportedAndWatchingContinues() { + failOn.add("a"); + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1, "b", 1)) + .add(scan(plain, "a", 2, "b", 1)).add(scan(plain, "a", 2, "b", 2)) + .add(scan(plain, "a", 2, "b", 2)); + drive(watcher(scanner, List.of()), 3); + + assertThat(errors).hasSize(1); + assertThat(errors.get(0)).contains("a"); + assertThat(pushed).containsExactly("b"); + } + + @Test + public void runStopsWhenKeepRunningTurnsFalse() { + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)); + ResourceWatcher watcher = watcher(scanner, List.of()); + AtomicInteger remaining = new AtomicInteger(3); + watcher.start(); + + watcher.run(Duration.ofMillis(10), () -> remaining.decrementAndGet() >= 0); + + assertThat(remaining.get()).isNegative(); + } +} From d1d2c69a1d7d4c20cf7d90915d2c4811b9f4f6bd Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:42:20 +0100 Subject: [PATCH 05/22] WW-5864 fix(tools): keep watching when a resource scan fails Co-Authored-By: Claude Sonnet 5.5 --- .../struts2/maven/watch/ResourceWatcher.java | 8 +++++++- .../struts2/maven/watch/ResourceWatcherTest.java | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java index 49c33d85ce..ce95e2da66 100644 --- a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java @@ -62,7 +62,13 @@ public void start() { } public void pollOnce() { - Map current = scanner.scan(); + Map current; + try { + current = scanner.scan(); + } catch (RuntimeException e) { + error.accept("Failed to scan resources", e); + return; + } Map currentFilterStamps = filterStamps(); Set handled = new HashSet<>(); diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java index 36f7d2af98..d089f9dfd0 100644 --- a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java @@ -66,6 +66,8 @@ public void delete(SourceFile file) { private static class FakeScanner extends ResourceScanner { private final Deque> scans = new ArrayDeque<>(); + private int failOnCall = -1; + private int calls; FakeScanner() { super(List.of(), true); @@ -78,6 +80,9 @@ FakeScanner add(Map scan) { @Override public Map scan() { + if (++calls == failOnCall) { + throw new IllegalStateException("vanished"); + } return scans.size() > 1 ? scans.poll() : scans.peek(); } } @@ -180,6 +185,16 @@ public void pusherFailureIsReportedAndWatchingContinues() { assertThat(pushed).containsExactly("b"); } + @Test + public void scanFailureIsReportedAndWatchingContinues() { + FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)).add(scan(plain, "a", 2)); + scanner.failOnCall = 3; + drive(watcher(scanner, List.of()), 3); + + assertThat(errors).hasSize(1); + assertThat(pushed).containsExactly("a"); + } + @Test public void runStopsWhenKeepRunningTurnsFalse() { FakeScanner scanner = new FakeScanner().add(scan(plain, "a", 1)); From 102d84f75bb8f5496d35ba833caf9092911604f4 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:44:37 +0100 Subject: [PATCH 06/22] WW-5864 feat(tools): push changed resources through maven-filtering Co-Authored-By: Claude Sonnet 5.5 --- .../maven/watch/FilteringResourcePusher.java | 85 ++++++++ .../watch/FilteringResourcePusherTest.java | 182 ++++++++++++++++++ 2 files changed, 267 insertions(+) create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java create mode 100644 tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java new file mode 100644 index 0000000000..a4641fc7fc --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.execution.MavenSession; +import org.apache.maven.model.Resource; +import org.apache.maven.project.MavenProject; +import org.apache.maven.shared.filtering.MavenFilteringException; +import org.apache.maven.shared.filtering.MavenResourcesExecution; +import org.apache.maven.shared.filtering.MavenResourcesFiltering; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +public final class FilteringResourcePusher implements ResourcePusher { + + private final MavenResourcesFiltering filtering; + private final MavenProject project; + private final MavenSession session; + private final ResourcesPluginSettings settings; + private final Path outputDirectory; + + public FilteringResourcePusher(MavenResourcesFiltering filtering, MavenProject project, MavenSession session, + ResourcesPluginSettings settings, Path outputDirectory) { + this.filtering = filtering; + this.project = project; + this.session = session; + this.settings = settings; + this.outputDirectory = outputDirectory; + } + + @Override + public void push(SourceFile file) throws IOException { + WatchedRoot root = file.root(); + Resource resource = new Resource(); + resource.setDirectory(root.directory().toString()); + resource.setIncludes(List.of(file.relativePath())); + resource.setTargetPath(root.targetPath()); + resource.setFiltering(root.filtering()); + + MavenResourcesExecution execution = new MavenResourcesExecution( + List.of(resource), outputDirectory.toFile(), project, settings.getEncoding(), + project.getBuild().getFilters(), List.of(), session); + execution.setPropertiesEncoding(settings.getPropertiesEncoding()); + execution.setDelimiters(settings.getDelimiters(), settings.isUseDefaultDelimiters()); + execution.setEscapeString(settings.getEscapeString()); + execution.setNonFilteredFileExtensions(settings.getNonFilteredFileExtensions()); + execution.setAddDefaultExcludes(settings.isAddDefaultExcludes()); + execution.setOverwrite(true); + try { + filtering.filterResources(execution); + } catch (MavenFilteringException e) { + throw new IOException("Cannot filter " + file.relativePath(), e); + } + } + + @Override + public void delete(SourceFile file) throws IOException { + Files.deleteIfExists(outputPathOf(file)); + } + + public Path outputPathOf(SourceFile file) { + String targetPath = file.root().targetPath(); + Path base = targetPath == null || targetPath.isEmpty() ? outputDirectory : outputDirectory.resolve(targetPath); + return base.resolve(file.relativePath()); + } +} diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java new file mode 100644 index 0000000000..15ee57494b --- /dev/null +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java @@ -0,0 +1,182 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.execution.DefaultMavenExecutionRequest; +import org.apache.maven.execution.DefaultMavenExecutionResult; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.project.MavenProject; +import org.apache.maven.shared.filtering.DefaultMavenFileFilter; +import org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.sonatype.plexus.build.incremental.ThreadBuildContext; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FilteringResourcePusherTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + private Path source; + private Path output; + private MavenProject project; + + @Before + public void setUp() throws IOException { + source = temp.newFolder("src").toPath(); + output = temp.getRoot().toPath().resolve("classes"); + project = new MavenProject(); + project.getProperties().setProperty("greeting", "hi"); + } + + private FilteringResourcePusher pusher(Xpp3Dom configuration) { + DefaultMavenResourcesFiltering filtering = + new DefaultMavenResourcesFiltering(new DefaultMavenFileFilter(new ThreadBuildContext()), new ThreadBuildContext()); + MavenSession session = new MavenSession(null, new DefaultMavenExecutionRequest(), new DefaultMavenExecutionResult(), project); + return new FilteringResourcePusher(filtering, project, session, + ResourcesPluginSettings.from(configuration, "UTF-8"), output); + } + + private SourceFile write(String relativePath, byte[] content, boolean filtering, String targetPath) throws IOException { + Path file = source.resolve(relativePath); + Files.createDirectories(file.getParent()); + Files.write(file, content); + return new SourceFile(new WatchedRoot(source, List.of(), List.of(), targetPath, filtering), relativePath); + } + + private SourceFile write(String relativePath, String content, boolean filtering) throws IOException { + return write(relativePath, content.getBytes(StandardCharsets.UTF_8), filtering, null); + } + + @Test + public void pushCopiesUnfilteredFile() throws IOException { + byte[] content = "name=${greeting}\n".getBytes(StandardCharsets.UTF_8); + SourceFile file = write("a.properties", content, false, null); + + pusher(null).push(file); + + assertThat(output.resolve("a.properties")).hasBinaryContent(content); + } + + @Test + public void pushFiltersPlaceholdersFromProjectProperties() throws IOException { + SourceFile file = write("a.properties", "name=${greeting}\n", true); + + pusher(null).push(file); + + assertThat(output.resolve("a.properties")).hasContent("name=hi"); + } + + @Test + public void pushHonoursCustomDelimiter() throws IOException { + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom delimiters = new Xpp3Dom("delimiters"); + Xpp3Dom delimiter = new Xpp3Dom("delimiter"); + delimiter.setValue("@"); + delimiters.addChild(delimiter); + configuration.addChild(delimiters); + Xpp3Dom useDefault = new Xpp3Dom("useDefaultDelimiters"); + useDefault.setValue("false"); + configuration.addChild(useDefault); + SourceFile file = write("a.properties", "name=@greeting@ other=${greeting}\n", true); + + pusher(configuration).push(file); + + assertThat(output.resolve("a.properties")).hasContent("name=hi other=${greeting}"); + } + + @Test + public void pushHonoursTargetPath() throws IOException { + SourceFile file = write("a.xml", "${greeting}".getBytes(StandardCharsets.UTF_8), true, "conf"); + + pusher(null).push(file); + + assertThat(output.resolve("conf/a.xml")).hasContent("hi"); + assertThat(pusher(null).outputPathOf(file)).isEqualTo(output.resolve("conf/a.xml")); + } + + @Test + public void pushCreatesMissingParentDirectories() throws IOException { + SourceFile file = write("com/acme/FooAction.properties", "k=v\n", false); + + pusher(null).push(file); + + assertThat(output.resolve("com/acme/FooAction.properties")).exists(); + } + + @Test + public void pushAfterOutputDirectoryDeletedRecreatesIt() throws IOException { + SourceFile file = write("a.properties", "k=v\n", false); + FilteringResourcePusher pusher = pusher(null); + pusher.push(file); + Files.delete(output.resolve("a.properties")); + Files.delete(output); + + pusher.push(file); + + assertThat(output.resolve("a.properties")).exists(); + } + + @Test + public void binaryFileInFilteredResourceIsCopiedUnchanged() throws IOException { + Xpp3Dom configuration = new Xpp3Dom("configuration"); + Xpp3Dom extensions = new Xpp3Dom("nonFilteredFileExtensions"); + Xpp3Dom extension = new Xpp3Dom("nonFilteredFileExtension"); + extension.setValue("png"); + extensions.addChild(extension); + configuration.addChild(extensions); + byte[] png = {(byte) 0x89, 'P', 'N', 'G', '$', '{', 'g', 'r', 'e', 'e', 't', 'i', 'n', 'g', '}', (byte) 0xff}; + SourceFile file = write("logo.png", png, true, null); + + pusher(configuration).push(file); + + assertThat(output.resolve("logo.png")).hasBinaryContent(png); + } + + @Test + public void deleteRemovesOutputFile() throws IOException { + SourceFile file = write("a.properties", "k=v\n", false); + FilteringResourcePusher pusher = pusher(null); + pusher.push(file); + + pusher.delete(file); + + assertThat(output.resolve("a.properties")).doesNotExist(); + } + + @Test + public void deleteOfMissingOutputIsANoOp() throws IOException { + SourceFile file = write("a.properties", "k=v\n", false); + + pusher(null).delete(file); + + assertThat(output.resolve("a.properties")).doesNotExist(); + } +} From 18b430ea53f6cd02ab79207735f105730a9db11e Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:48:56 +0100 Subject: [PATCH 07/22] WW-5864 feat(tools): warn when Struts reload switches are off Co-Authored-By: Claude Sonnet 5.5 --- .../maven/watch/StrutsReloadInspector.java | 119 ++++++++++++++++++ .../watch/StrutsReloadInspectorTest.java | 118 +++++++++++++++++ 2 files changed, 237 insertions(+) create mode 100644 tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/StrutsReloadInspector.java create mode 100644 tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/StrutsReloadInspectorTest.java diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/StrutsReloadInspector.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/StrutsReloadInspector.java new file mode 100644 index 0000000000..45920cbe09 --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/StrutsReloadInspector.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class StrutsReloadInspector { + + private static final String DEV_MODE = "struts.devMode"; + private static final String XML_RELOAD = "struts.configuration.xml.reload"; + private static final String I18N_RELOAD = "struts.i18n.reload"; + + private final Map settings = new HashMap<>(); + + public StrutsReloadInspector(Path outputDirectory) { + readXml(outputDirectory.resolve("struts.xml")); + readProperties(outputDirectory.resolve("struts.properties")); + } + + public List warnings() { + List warnings = new ArrayList<>(); + String devMode = settings.get(DEV_MODE); + if (devMode == null) { + warnings.add("struts.devMode was not found in struts.xml or struts.properties; " + + "if it is set elsewhere, ignore this. Otherwise pushed changes may not be picked up."); + } + for (String key : new String[]{XML_RELOAD, I18N_RELOAD}) { + String explicit = settings.get(key); + String effective = explicit != null ? explicit : devMode; + if (effective != null && !"true".equalsIgnoreCase(effective.trim())) { + warnings.add(key + " is not true; pushed changes will not be picked up " + + "until the application is restarted. Set struts.devMode=true or " + key + "=true."); + } + } + return warnings; + } + + private void readXml(Path file) { + Document document = parse(file); + if (document == null) { + return; + } + NodeList constants = document.getDocumentElement().getElementsByTagName("constant"); + for (int i = 0; i < constants.getLength(); i++) { + Element constant = (Element) constants.item(i); + if (constant.hasAttribute("name") && constant.hasAttribute("value")) { + settings.put(constant.getAttribute("name"), constant.getAttribute("value")); + } + } + } + + private Document parse(Path file) { + if (!Files.isRegularFile(file)) { + return null; + } + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setXIncludeAware(false); + factory.setExpandEntityReferences(false); + DocumentBuilder builder = factory.newDocumentBuilder(); + builder.setEntityResolver((publicId, systemId) -> new InputSource(new StringReader(""))); + try (InputStream in = Files.newInputStream(file)) { + return builder.parse(in); + } + } catch (Exception e) { + return null; + } + } + + private void readProperties(Path file) { + if (!Files.isRegularFile(file)) { + return; + } + Properties properties = new Properties(); + try (InputStream in = Files.newInputStream(file)) { + properties.load(in); + } catch (IOException | IllegalArgumentException e) { + return; + } + for (String name : properties.stringPropertyNames()) { + settings.put(name, properties.getProperty(name)); + } + } +} diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/StrutsReloadInspectorTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/StrutsReloadInspectorTest.java new file mode 100644 index 0000000000..7b00cff66d --- /dev/null +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/StrutsReloadInspectorTest.java @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StrutsReloadInspectorTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private void xml(String... constants) throws IOException { + xmlWithDoctype("", constants); + } + + private void xmlWithDoctype(String doctype, String... constants) throws IOException { + StringBuilder sb = new StringBuilder("\n") + .append(doctype).append("\n"); + for (int i = 0; i < constants.length; i += 2) { + sb.append("\n"); + } + sb.append("\n"); + write("struts.xml", sb.toString()); + } + + private void write(String name, String content) throws IOException { + Files.write(tmp.getRoot().toPath().resolve(name), content.getBytes(StandardCharsets.UTF_8)); + } + + private List warnings() { + return new StrutsReloadInspector(tmp.getRoot().toPath()).warnings(); + } + + @Test + public void devModeTrueNoWarnings() throws IOException { + xml("struts.devMode", "true"); + + assertThat(warnings()).isEmpty(); + } + + @Test + public void devModeFalseWarnsForBothReloadSwitches() throws IOException { + xml("struts.devMode", "false"); + + List warnings = warnings(); + + assertThat(warnings).hasSize(2); + assertThat(warnings.get(0)).contains("struts.configuration.xml.reload"); + assertThat(warnings.get(1)).contains("struts.i18n.reload"); + } + + @Test + public void explicitFalseOverridesDevMode() throws IOException { + xml("struts.devMode", "true", "struts.i18n.reload", "false"); + + List warnings = warnings(); + + assertThat(warnings).hasSize(1); + assertThat(warnings.get(0)).contains("struts.i18n.reload"); + } + + @Test + public void propertiesFileOverridesXml() throws IOException { + xml("struts.devMode", "false"); + write("struts.properties", "struts.devMode=true\n"); + + assertThat(warnings()).isEmpty(); + } + + @Test + public void devModeNotFoundGivesSoftWarning() { + List warnings = warnings(); + + assertThat(warnings).hasSize(1); + assertThat(warnings.get(0)).contains("struts.devMode"); + } + + @Test + public void doesNotFetchExternalDtd() throws IOException { + xmlWithDoctype("\n", + "struts.devMode", "true"); + + assertThat(warnings()).isEmpty(); + } + + @Test + public void malformedXmlProducesNoException() throws IOException { + write("struts.xml", ""; + + /** + * Milliseconds between scans of the resource directories. + */ + @Parameter(property = "struts.watch.pollInterval", defaultValue = "500") + long pollInterval = 500; + + /** + * Run the watcher on a daemon thread and return, so it can be bound to a lifecycle phase. + * Requires struts.watch=true to do anything. + */ + @Parameter(property = "struts.watch.background", defaultValue = "false") + boolean background; + + /** + * Switches background watching on. Consulted only when background is true. + */ + @Parameter(property = "struts.watch", defaultValue = "false") + boolean enabled; + + /** + * Seconds after which a blocking run stops; 0 means run until interrupted. + */ + @Parameter(property = "struts.watch.timeout", defaultValue = "0") + long timeout; + + @Parameter(defaultValue = "${project}", readonly = true, required = true) + MavenProject project; + + @Parameter(defaultValue = "${session}", readonly = true, required = true) + MavenSession session; + + @Inject + MavenResourcesFiltering resourcesFiltering; + + @Override + public void execute() throws MojoFailureException { + if (!shouldRun()) { + getLog().debug("struts:watch is in background mode and struts.watch is not true; not watching"); + return; + } + checkSingleModule(); + + Path basedir = project.getBasedir().toPath(); + Path outputDirectory = new File(project.getBuild().getOutputDirectory()).toPath(); + for (String warning : new StrutsReloadInspector(outputDirectory).warnings()) { + getLog().warn(warning); + } + + ResourcesPluginSettings settings = ResourcesPluginSettings.from( + ResourcesPluginSettings.effectiveResourcesConfiguration(project), + project.getProperties().getProperty("project.build.sourceEncoding")); + List roots = project.getResources().stream() + .map(resource -> WatchedRoot.of(resource, basedir)) + .toList(); + ResourceScanner scanner = new ResourceScanner(roots, settings.isAddDefaultExcludes()); + FilteringResourcePusher filteringPusher = + new FilteringResourcePusher(resourcesFiltering, project, session, settings, outputDirectory); + ResourcePusher pusher = loggingPusher(filteringPusher, basedir); + + pushStaleOutputs(scanner.scan(), filteringPusher::outputPathOf, pusher); + + List filterFiles = project.getBuild().getFilters().stream() + .map(filter -> basedir.resolve(filter)) + .toList(); + ResourceWatcher watcher = new ResourceWatcher(scanner, pusher, filterFiles, + message -> getLog().debug(message), (message, e) -> getLog().error(message, e)); + watcher.start(); + + Duration interval = Duration.ofMillis(pollInterval); + if (background) { + Thread thread = new Thread(() -> watcher.run(interval, () -> true), "struts-watch"); + thread.setDaemon(true); + thread.start(); + getLog().info("Watching " + roots.size() + " resource root(s) in the background"); + return; + } + getLog().info("Watching " + roots.size() + " resource root(s); press Ctrl+C to stop"); + long deadline = timeout > 0 ? System.nanoTime() + Duration.ofSeconds(timeout).toNanos() : 0; + BooleanSupplier keepRunning = () -> deadline == 0 || System.nanoTime() - deadline < 0; + watcher.run(interval, keepRunning); + } + + boolean shouldRun() { + return !background || enabled; + } + + void checkSingleModule() throws MojoFailureException { + if (session.getProjects().size() > 1) { + throw new MojoFailureException(MULTI_MODULE_MESSAGE); + } + } + + static void pushStaleOutputs(Map scan, Function outputPathOf, + ResourcePusher pusher) { + for (Map.Entry entry : scan.entrySet()) { + File output = outputPathOf.apply(entry.getKey()).toFile(); + if (!output.isFile() || output.lastModified() < entry.getValue().lastModified()) { + try { + pusher.push(entry.getKey()); + } catch (IOException | RuntimeException e) { + throw new IllegalStateException("Cannot push " + entry.getKey().relativePath(), e); + } + } + } + } + + private ResourcePusher loggingPusher(FilteringResourcePusher delegate, Path basedir) { + return new ResourcePusher() { + @Override + public void push(SourceFile file) throws IOException { + delegate.push(file); + getLog().info("pushed " + file.relativePath() + " -> " + + basedir.relativize(delegate.outputPathOf(file))); + } + + @Override + public void delete(SourceFile file) throws IOException { + delegate.delete(file); + getLog().info("deleted " + file.relativePath()); + } + }; + } +} diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java new file mode 100644 index 0000000000..799d672e8c --- /dev/null +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.project.MavenProject; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class WatchMojoTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + @Test + public void backgroundWithoutEnabledDoesNotRun() { + WatchMojo mojo = new WatchMojo(); + mojo.background = true; + mojo.enabled = false; + assertThat(mojo.shouldRun()).isFalse(); + } + + @Test + public void backgroundWithEnabledRuns() { + WatchMojo mojo = new WatchMojo(); + mojo.background = true; + mojo.enabled = true; + assertThat(mojo.shouldRun()).isTrue(); + } + + @Test + public void blockingAlwaysRuns() { + WatchMojo mojo = new WatchMojo(); + mojo.background = false; + mojo.enabled = false; + assertThat(mojo.shouldRun()).isTrue(); + } + + @Test + public void multiModuleSessionFailsWithGuidance() { + WatchMojo mojo = new WatchMojo(); + MavenSession session = mock(MavenSession.class); + when(session.getProjects()).thenReturn(List.of(new MavenProject(), new MavenProject())); + mojo.session = session; + assertThatThrownBy(mojo::checkSingleModule) + .isInstanceOf(MojoFailureException.class) + .hasMessageContaining("-pl "); + } + + @Test + public void staleOutputsArePushedAtStart() throws Exception { + Path src = temp.newFolder("src").toPath(); + Path out = temp.newFolder("out").toPath(); + File stale = write(src.resolve("stale.txt"), 2000); + File fresh = write(src.resolve("fresh.txt"), 1000); + File missing = write(src.resolve("missing.txt"), 1000); + write(out.resolve("stale.txt"), 1000); + write(out.resolve("fresh.txt"), 2000); + + WatchedRoot root = new WatchedRoot(src, List.of(), List.of(), null, false); + Map scan = new LinkedHashMap<>(); + for (File f : List.of(stale, fresh, missing)) { + scan.put(new SourceFile(root, f.getName()), new FileStamp(f.lastModified(), f.length())); + } + List pushed = new ArrayList<>(); + ResourcePusher pusher = new ResourcePusher() { + public void push(SourceFile file) { + pushed.add(file.relativePath()); + } + + public void delete(SourceFile file) { + } + }; + + WatchMojo.pushStaleOutputs(scan, file -> out.resolve(file.relativePath()), pusher); + + assertThat(pushed).containsExactlyInAnyOrder("stale.txt", "missing.txt"); + } + + private File write(Path path, long lastModified) throws Exception { + Files.writeString(path, "x"); + File file = path.toFile(); + assertThat(file.setLastModified(lastModified)).isTrue(); + return file; + } +} From d75f44ee19eaa2aa19dbb0be6732b8b8ba659733 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:52:20 +0100 Subject: [PATCH 09/22] WW-5864 fix(tools): report stale-push failures and keep going Co-Authored-By: Claude Sonnet 5.5 --- .../apache/struts2/maven/watch/WatchMojo.java | 8 +++-- .../struts2/maven/watch/WatchMojoTest.java | 33 ++++++++++++++++++- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java index 4dbaae7fdf..9d0b944074 100644 --- a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java @@ -34,6 +34,7 @@ import java.time.Duration; import java.util.List; import java.util.Map; +import java.util.function.BiConsumer; import java.util.function.BooleanSupplier; import java.util.function.Function; @@ -102,7 +103,8 @@ public void execute() throws MojoFailureException { new FilteringResourcePusher(resourcesFiltering, project, session, settings, outputDirectory); ResourcePusher pusher = loggingPusher(filteringPusher, basedir); - pushStaleOutputs(scanner.scan(), filteringPusher::outputPathOf, pusher); + pushStaleOutputs(scanner.scan(), filteringPusher::outputPathOf, pusher, + (message, e) -> getLog().error(message, e)); List filterFiles = project.getBuild().getFilters().stream() .map(filter -> basedir.resolve(filter)) @@ -136,14 +138,14 @@ void checkSingleModule() throws MojoFailureException { } static void pushStaleOutputs(Map scan, Function outputPathOf, - ResourcePusher pusher) { + ResourcePusher pusher, BiConsumer error) { for (Map.Entry entry : scan.entrySet()) { File output = outputPathOf.apply(entry.getKey()).toFile(); if (!output.isFile() || output.lastModified() < entry.getValue().lastModified()) { try { pusher.push(entry.getKey()); } catch (IOException | RuntimeException e) { - throw new IllegalStateException("Cannot push " + entry.getKey().relativePath(), e); + error.accept("Failed to push " + entry.getKey().relativePath(), e); } } } diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java index 799d672e8c..5523c84082 100644 --- a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java @@ -103,11 +103,42 @@ public void delete(SourceFile file) { } }; - WatchMojo.pushStaleOutputs(scan, file -> out.resolve(file.relativePath()), pusher); + WatchMojo.pushStaleOutputs(scan, file -> out.resolve(file.relativePath()), pusher, (m, e) -> { }); assertThat(pushed).containsExactlyInAnyOrder("stale.txt", "missing.txt"); } + @Test + public void stalePushFailureIsReportedAndRemainingFilesArePushed() throws Exception { + Path src = temp.newFolder("src2").toPath(); + Path out = temp.newFolder("out2").toPath(); + WatchedRoot root = new WatchedRoot(src, List.of(), List.of(), null, false); + Map scan = new LinkedHashMap<>(); + for (String name : List.of("bad.txt", "good.txt")) { + File f = write(src.resolve(name), 1000); + scan.put(new SourceFile(root, name), new FileStamp(f.lastModified(), f.length())); + } + List pushed = new ArrayList<>(); + List errors = new ArrayList<>(); + ResourcePusher pusher = new ResourcePusher() { + public void push(SourceFile file) throws java.io.IOException { + if (file.relativePath().equals("bad.txt")) { + throw new java.io.IOException("locked"); + } + pushed.add(file.relativePath()); + } + + public void delete(SourceFile file) { + } + }; + + WatchMojo.pushStaleOutputs(scan, file -> out.resolve(file.relativePath()), pusher, + (message, e) -> errors.add(message)); + + assertThat(pushed).containsExactly("good.txt"); + assertThat(errors).containsExactly("Failed to push bad.txt"); + } + private File write(Path path, long lastModified) throws Exception { Files.writeString(path, "x"); File file = path.toFile(); From 0fb7e3943f4f2f4fa4b082c92a46783a9ca58ce5 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:55:42 +0100 Subject: [PATCH 10/22] WW-5864 test(tools): invoker IT for struts:watch Co-Authored-By: Claude Sonnet 5.5 --- tools/struts-maven-plugin/pom.xml | 22 ++++++++ .../it/watch-pushes-change/invoker.properties | 19 +++++++ .../src/it/watch-pushes-change/pom.xml | 54 +++++++++++++++++++ .../it/watch-pushes-change/prebuild.groovy | 26 +++++++++ .../src/main/resources/messages.properties | 19 +++++++ .../src/main/resources/struts.xml | 25 +++++++++ .../src/it/watch-pushes-change/verify.groovy | 22 ++++++++ 7 files changed, 187 insertions(+) create mode 100644 tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties create mode 100644 tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml create mode 100644 tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy create mode 100644 tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/messages.properties create mode 100644 tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/struts.xml create mode 100644 tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy diff --git a/tools/struts-maven-plugin/pom.xml b/tools/struts-maven-plugin/pom.xml index a685b28166..266c4d9d49 100644 --- a/tools/struts-maven-plugin/pom.xml +++ b/tools/struts-maven-plugin/pom.xml @@ -64,6 +64,28 @@ + + maven-invoker-plugin + 3.10.1 + + ${project.build.directory}/it + ${project.build.directory}/local-repo + src/it + prebuild + verify + true + + + + integration-test + + install + integration-test + verify + + + + diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties b/tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties new file mode 100644 index 0000000000..0c21882c70 --- /dev/null +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties @@ -0,0 +1,19 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +invoker.goals = process-resources ${project.groupId}:${project.artifactId}:${project.version}:watch diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml b/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml new file mode 100644 index 0000000000..e84e8d4413 --- /dev/null +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml @@ -0,0 +1,54 @@ + + + + 4.0.0 + + org.apache.struts.it + watch-pushes-change + 1.0-SNAPSHOT + jar + + + UTF-8 + hi + + + + + + src/main/resources + true + + + + + @project.groupId@ + @project.artifactId@ + @project.version@ + + 20 + 200 + + + + + diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy b/tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy new file mode 100644 index 0000000000..6c10bb2e15 --- /dev/null +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +def messages = new File(basedir, 'src/main/resources/messages.properties') +def editor = new Thread({ + Thread.sleep(8000) + messages.text = messages.text.replace('-v1', '-v2\n') +}) +editor.setDaemon(true) +editor.start() diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/messages.properties b/tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/messages.properties new file mode 100644 index 0000000000..b4e502fe80 --- /dev/null +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/messages.properties @@ -0,0 +1,19 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +msg=${greeting}-v1 diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/struts.xml b/tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/struts.xml new file mode 100644 index 0000000000..7783333258 --- /dev/null +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/src/main/resources/struts.xml @@ -0,0 +1,25 @@ + + + + + + diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy b/tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy new file mode 100644 index 0000000000..ce2aba6c3e --- /dev/null +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +def classes = new File(basedir, 'target/classes/messages.properties') +assert classes.text.contains('msg=hi-v2') : "filtered v2 missing: ${classes.text}" +assert new File(basedir, 'build.log').text.contains('pushed messages.properties') From 59ca0eedc40d1fe6f8dc10d73154f757d3f995fb Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 08:59:24 +0100 Subject: [PATCH 11/22] WW-5864 test(tools): gate the IT edit on the watch loop having started Co-Authored-By: Claude Sonnet 5.5 --- .../src/it/watch-pushes-change/pom.xml | 2 +- .../src/it/watch-pushes-change/prebuild.groovy | 11 +++++++++-- .../src/it/watch-pushes-change/verify.groovy | 5 ++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml b/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml index e84e8d4413..9436fff2cb 100644 --- a/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml @@ -45,7 +45,7 @@ @project.artifactId@ @project.version@ - 20 + 30 200 diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy b/tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy index 6c10bb2e15..ab1e39b008 100644 --- a/tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/prebuild.groovy @@ -18,9 +18,16 @@ */ def messages = new File(basedir, 'src/main/resources/messages.properties') +def buildLog = new File(basedir, 'build.log') def editor = new Thread({ - Thread.sleep(8000) - messages.text = messages.text.replace('-v1', '-v2\n') + long giveUp = System.nanoTime() + 60_000_000_000L + while (System.nanoTime() < giveUp) { + if (buildLog.exists() && buildLog.text.contains('Watching 1 resource root(s)')) { + messages.text = messages.text.replace('-v1', '-v2\n') + return + } + Thread.sleep(100) + } }) editor.setDaemon(true) editor.start() diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy b/tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy index ce2aba6c3e..a65f083f82 100644 --- a/tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/verify.groovy @@ -19,4 +19,7 @@ def classes = new File(basedir, 'target/classes/messages.properties') assert classes.text.contains('msg=hi-v2') : "filtered v2 missing: ${classes.text}" -assert new File(basedir, 'build.log').text.contains('pushed messages.properties') +def log = new File(basedir, 'build.log').text +int watching = log.indexOf('Watching 1 resource root(s)') +assert watching >= 0 +assert log.indexOf('pushed messages.properties', watching) > watching : 'no push after the watch loop started' From e5287727bb092ce2e5891810327a792d031cde12 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:12:59 +0100 Subject: [PATCH 12/22] WW-5864 build(showcase): reference struts:watch setup and Jetty scanner Add a background struts:watch execution (process-resources) to the showcase, inert unless -Dstruts.watch is given. Jetty scanner research: jetty-maven-plugin 11.0.26 exposes scanClassesPattern (includes/excludes), so scanning compiled classes is kept and only **/*.class is scanned; resource pushes into target/classes no longer restart the webapp. 0 was not needed. rest-showcase uses scanIntervalSeconds, which does not exist in the 11.0.26 plugin.xml (silently ignored), so scanning there was never configured via that name; the same scanClassesPattern is added so it holds if scanning is enabled. Co-Authored-By: Claude Sonnet 5.5 --- apps/rest-showcase/pom.xml | 5 +++++ apps/showcase/pom.xml | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/apps/rest-showcase/pom.xml b/apps/rest-showcase/pom.xml index a70a734016..4b12b5b61c 100644 --- a/apps/rest-showcase/pom.xml +++ b/apps/rest-showcase/pom.xml @@ -135,6 +135,11 @@ CTRL+C 8999 10 + + + **/*.class + + ${basedir}/src/main/webapp/ /struts2-rest-showcase diff --git a/apps/showcase/pom.xml b/apps/showcase/pom.xml index 37b0c8c859..96cbb20ac4 100644 --- a/apps/showcase/pom.xml +++ b/apps/showcase/pom.xml @@ -189,6 +189,23 @@ + + org.apache.struts + struts-maven-plugin + ${project.version} + + + watch + process-resources + + watch + + + true + + + + org.apache.maven.plugins maven-dependency-plugin @@ -285,6 +302,11 @@ 8090 10 + + + **/*.class + + ${project.build.directory}/extraclasspath/struts2-velocity-tools-view-jakarta.jar, From 40c2d9e9e72b803b6c3f8be798b90abfde822661 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:14:24 +0100 Subject: [PATCH 13/22] WW-5864 docs(tools): struts-maven-plugin usage Co-Authored-By: Claude Sonnet 5.5 --- tools/struts-maven-plugin/README.md | 89 +++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 tools/struts-maven-plugin/README.md diff --git a/tools/struts-maven-plugin/README.md b/tools/struts-maven-plugin/README.md new file mode 100644 index 0000000000..48ffb639af --- /dev/null +++ b/tools/struts-maven-plugin/README.md @@ -0,0 +1,89 @@ +# Struts Maven Plugin + +`struts:watch` copies edited resources (`struts.xml`, `*.properties`, FreeMarker templates, validation files) into +`target/classes` while an application runs, so Struts' own reload picks them up without a rebuild or restart. + +It pushes resource changes only. It does not compile or reload Java classes: use a restart or debugger hotswap for +those. Webapp files (JSP, FTL under `src/main/webapp`) are already served from source. + +## Application setup + +The application must have reloading on: `struts.devMode=true` (with the reload switches not explicitly `false`), or +`struts.configuration.xml.reload=true` and `struts.i18n.reload=true`. An explicit `false` wins over `devMode`. The goal +logs a warning at startup when it can see the switches are off (best effort: it reads only `struts.xml` and +`struts.properties` in the output directory). + +Declare the plugin in the application's `pom.xml`; the `struts:` prefix resolves from there, no `pluginGroups` entry +is needed. + +```xml + + org.apache.struts + struts-maven-plugin + ${struts.version} + +``` + +## Running it + +Next to a server started in another terminal, the goal blocks until Ctrl+C: + +``` +mvn struts:watch -pl +``` + +Or bound to `process-resources` in the background, switched on from the command line, together with the Jetty plugin: + +```xml + + watch + process-resources + + watch + + + true + + +``` + +``` +mvn jetty:run -Dstruts.watch +``` + +Without `-Dstruts.watch` a background execution does nothing. + +Each push is logged, for example `pushed struts.xml -> target/classes/struts.xml`. Files whose output is missing or +older than the source are pushed once at startup. Filtering follows the module's `maven-resources-plugin` +configuration. + +## Parameters + +| Parameter | Property | Default | Meaning | +|---|---|---|---| +| `pollInterval` | `struts.watch.pollInterval` | `500` | Milliseconds between scans of the resource directories | +| `background` | `struts.watch.background` | `false` | Run on a daemon thread and return, so the goal can be bound to a phase | +| `enabled` | `struts.watch` | `false` | Switches background watching on; consulted only when `background` is `true` | +| `timeout` | `struts.watch.timeout` | `0` | Seconds after which a blocking run stops; `0` runs until interrupted | + +## Jetty scanner + +Pushed resources land in `target/classes`, which the Jetty Maven plugin's scanner would treat as a change and restart +the webapp. Restrict its class scan to compiled classes so recompiles still restart the webapp but resource pushes do +not: + +```xml + + + **/*.class + + +``` + +`apps/showcase/pom.xml` has both the bound execution and this setting. Its committed `struts.xml` keeps `devMode` and +the reload switches off, so to try it there flip them locally. + +## Limitations + +- Single module only: in a multi-reactor build the goal fails with a message to run it with `-pl `. +- No Java class reloading, no Gradle support, no Struts Boot support. From d0570f0b5bcdc8fc04e723fb8ccacbe549209231 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:15:23 +0100 Subject: [PATCH 14/22] WW-5864 docs(tools): fix README version placeholder and warning notes Co-Authored-By: Claude Sonnet 5.5 --- tools/struts-maven-plugin/README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tools/struts-maven-plugin/README.md b/tools/struts-maven-plugin/README.md index 48ffb639af..e4c7e6184d 100644 --- a/tools/struts-maven-plugin/README.md +++ b/tools/struts-maven-plugin/README.md @@ -10,7 +10,7 @@ those. Webapp files (JSP, FTL under `src/main/webapp`) are already served from s The application must have reloading on: `struts.devMode=true` (with the reload switches not explicitly `false`), or `struts.configuration.xml.reload=true` and `struts.i18n.reload=true`. An explicit `false` wins over `devMode`. The goal -logs a warning at startup when it can see the switches are off (best effort: it reads only `struts.xml` and +logs a warning at startup when it can see the switches are off, or when `struts.devMode` is not found at all (best effort: it reads only `struts.xml` and `struts.properties` in the output directory). Declare the plugin in the application's `pom.xml`; the `struts:` prefix resolves from there, no `pluginGroups` entry @@ -20,19 +20,21 @@ is needed. org.apache.struts struts-maven-plugin - ${struts.version} + X.Y.Z ``` +`X.Y.Z` is the Struts version; the plugin is released together with Struts. + ## Running it Next to a server started in another terminal, the goal blocks until Ctrl+C: -``` +```sh mvn struts:watch -pl ``` -Or bound to `process-resources` in the background, switched on from the command line, together with the Jetty plugin: +Or bound to `process-resources` in the background, switched on from the command line, together with the Jetty plugin. This `` goes inside the plugin declaration above: ```xml @@ -47,7 +49,7 @@ Or bound to `process-resources` in the background, switched on from the command ``` -``` +```sh mvn jetty:run -Dstruts.watch ``` From 2200e51dfd95e499d05c18c297489d6fbd853187 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:22:29 +0100 Subject: [PATCH 15/22] WW-5864 build(rest-showcase): revert scanClassesPattern addition Co-Authored-By: Claude Opus 5.5 --- apps/rest-showcase/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/apps/rest-showcase/pom.xml b/apps/rest-showcase/pom.xml index 4b12b5b61c..a70a734016 100644 --- a/apps/rest-showcase/pom.xml +++ b/apps/rest-showcase/pom.xml @@ -135,11 +135,6 @@ CTRL+C 8999 10 - - - **/*.class - - ${basedir}/src/main/webapp/ /struts2-rest-showcase From 707242d72b97760376c358dbda0b11623f21f499 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:23:11 +0100 Subject: [PATCH 16/22] WW-5864 build(tools): skippable invoker IT resolving from the outer local repo -DskipITs skips the invocation, src/it/settings.xml points the IT at the outer local repository instead of Central, the fixture timeout drops to 10 s and invoker.timeoutInSeconds guards against a hang. Co-Authored-By: Claude Opus 5.5 --- tools/struts-maven-plugin/pom.xml | 3 + tools/struts-maven-plugin/src/it/settings.xml | 55 +++++++++++++++++++ .../it/watch-pushes-change/invoker.properties | 1 + .../src/it/watch-pushes-change/pom.xml | 2 +- 4 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 tools/struts-maven-plugin/src/it/settings.xml diff --git a/tools/struts-maven-plugin/pom.xml b/tools/struts-maven-plugin/pom.xml index 266c4d9d49..f9fbb50f37 100644 --- a/tools/struts-maven-plugin/pom.xml +++ b/tools/struts-maven-plugin/pom.xml @@ -35,6 +35,7 @@ 3.9.16 3.16.0 + false @@ -71,6 +72,8 @@ ${project.build.directory}/it ${project.build.directory}/local-repo src/it + src/it/settings.xml + ${skipITs} prebuild verify true diff --git a/tools/struts-maven-plugin/src/it/settings.xml b/tools/struts-maven-plugin/src/it/settings.xml new file mode 100644 index 0000000000..d1ccda1942 --- /dev/null +++ b/tools/struts-maven-plugin/src/it/settings.xml @@ -0,0 +1,55 @@ + + + + + + it-repo + + true + + + + local.central + @localRepositoryUrl@ + + true + + + true + + + + + + local.central + @localRepositoryUrl@ + + true + + + true + + + + + + diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties b/tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties index 0c21882c70..72090fa0e3 100644 --- a/tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/invoker.properties @@ -17,3 +17,4 @@ # under the License. # invoker.goals = process-resources ${project.groupId}:${project.artifactId}:${project.version}:watch +invoker.timeoutInSeconds = 120 diff --git a/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml b/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml index 9436fff2cb..28be65314a 100644 --- a/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml +++ b/tools/struts-maven-plugin/src/it/watch-pushes-change/pom.xml @@ -45,7 +45,7 @@ @project.artifactId@ @project.version@ - 30 + 10 200 From 02e6d3318fc1e796fef86721b882cfce6a309af3 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:23:52 +0100 Subject: [PATCH 17/22] WW-5864 fix(tools): push overlapping roots in scan order Co-Authored-By: Claude Opus 5.5 --- .../struts2/maven/watch/ResourceWatcher.java | 6 ++-- .../maven/watch/ResourceScannerTest.java | 12 +++++++ .../maven/watch/ResourceWatcherTest.java | 33 +++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java index ce95e2da66..fd02710b6f 100644 --- a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourceWatcher.java @@ -24,6 +24,8 @@ import java.time.Duration; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -72,10 +74,10 @@ public void pollOnce() { Map currentFilterStamps = filterStamps(); Set handled = new HashSet<>(); - Set paths = new HashSet<>(current.keySet()); + Set paths = new LinkedHashSet<>(current.keySet()); paths.addAll(previous.keySet()); paths.addAll(acted.keySet()); - Map nextActed = new HashMap<>(acted); + Map nextActed = new LinkedHashMap<>(acted); for (SourceFile file : paths) { FileStamp now = current.get(file); if (Objects.equals(now, previous.get(file)) && !Objects.equals(now, acted.get(file))) { diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java index 93d9a734ed..8a443fddc7 100644 --- a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceScannerTest.java @@ -95,4 +95,16 @@ public void missingRootDirectoryYieldsNoFiles() { assertThat(new ResourceScanner(List.of(root(dir, List.of(), List.of())), true).scan()).isEmpty(); } + + @Test + public void overlappingRootsAreListedInRootOrder() throws Exception { + Path dir = temp.newFolder("res").toPath(); + Files.writeString(dir.resolve("a.txt"), "a"); + WatchedRoot first = new WatchedRoot(dir, List.of(), List.of(), "first", false); + WatchedRoot second = new WatchedRoot(dir, List.of(), List.of(), "second", false); + + Map scan = new ResourceScanner(List.of(first, second), true).scan(); + + assertThat(scan.keySet()).containsExactly(new SourceFile(first, "a.txt"), new SourceFile(second, "a.txt")); + } } diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java index d089f9dfd0..2713d86cb1 100644 --- a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourceWatcherTest.java @@ -206,4 +206,37 @@ public void runStopsWhenKeepRunningTurnsFalse() { assertThat(remaining.get()).isNegative(); } + + @Test + public void overlappingRootsArePushedInScanOrder() { + List roots = new ArrayList<>(); + for (int i = 0; i < 6; i++) { + roots.add(new WatchedRoot(Path.of("same"), List.of(), List.of(), "t" + i, false)); + } + Map before = new LinkedHashMap<>(); + Map after = new LinkedHashMap<>(); + for (WatchedRoot root : roots) { + before.putAll(scan(root, "a", 1)); + after.putAll(scan(root, "a", 2)); + } + List targets = new ArrayList<>(); + ResourcePusher recording = new ResourcePusher() { + @Override + public void push(SourceFile file) { + targets.add(file.root().targetPath()); + } + + @Override + public void delete(SourceFile file) { + } + }; + FakeScanner scanner = new FakeScanner().add(before).add(after); + ResourceWatcher watcher = new ResourceWatcher(scanner, recording, List.of(), m -> { }, (m, e) -> { }); + + watcher.start(); + watcher.pollOnce(); + watcher.pollOnce(); + + assertThat(targets).containsExactly("t0", "t1", "t2", "t3", "t4", "t5"); + } } From b87303edbc708b51a266f882c0daca44c0927be8 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:25:00 +0100 Subject: [PATCH 18/22] WW-5864 fix(tools): follow plugin-level filters and escaping settings Reads , , , and from the effective maven-resources-plugin configuration, watches the combined filter files, and warns when or is set. Co-Authored-By: Claude Opus 5.5 --- .../maven/watch/FilteringResourcePusher.java | 10 ++- .../maven/watch/ResourcesPluginSettings.java | 81 ++++++++++++++----- .../apache/struts2/maven/watch/WatchMojo.java | 10 ++- .../watch/FilteringResourcePusherTest.java | 47 ++++++++++- .../watch/ResourcesPluginSettingsTest.java | 48 +++++++++++ 5 files changed, 167 insertions(+), 29 deletions(-) diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java index a4641fc7fc..2ce8c029bb 100644 --- a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/FilteringResourcePusher.java @@ -37,14 +37,16 @@ public final class FilteringResourcePusher implements ResourcePusher { private final MavenSession session; private final ResourcesPluginSettings settings; private final Path outputDirectory; + private final List filterFiles; public FilteringResourcePusher(MavenResourcesFiltering filtering, MavenProject project, MavenSession session, - ResourcesPluginSettings settings, Path outputDirectory) { + ResourcesPluginSettings settings, Path outputDirectory, List filterFiles) { this.filtering = filtering; this.project = project; this.session = session; this.settings = settings; this.outputDirectory = outputDirectory; + this.filterFiles = filterFiles.stream().map(Path::toString).toList(); } @Override @@ -58,7 +60,11 @@ public void push(SourceFile file) throws IOException { MavenResourcesExecution execution = new MavenResourcesExecution( List.of(resource), outputDirectory.toFile(), project, settings.getEncoding(), - project.getBuild().getFilters(), List.of(), session); + filterFiles, List.of(), session); + execution.setInjectProjectBuildFilters(false); + execution.setEscapeWindowsPaths(settings.isEscapeWindowsPaths()); + execution.setSupportMultiLineFiltering(settings.isSupportMultiLineFiltering()); + execution.setFilterFilenames(settings.isFileNameFiltering()); execution.setPropertiesEncoding(settings.getPropertiesEncoding()); execution.setDelimiters(settings.getDelimiters(), settings.isUseDefaultDelimiters()); execution.setEscapeString(settings.getEscapeString()); diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java index 8640f5c774..849a35b67f 100644 --- a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/ResourcesPluginSettings.java @@ -23,6 +23,7 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -40,28 +41,33 @@ public final class ResourcesPluginSettings { private final String escapeString; private final List nonFilteredFileExtensions; private final boolean addDefaultExcludes; - - private ResourcesPluginSettings(String encoding, String propertiesEncoding, LinkedHashSet delimiters, - boolean useDefaultDelimiters, String escapeString, - List nonFilteredFileExtensions, boolean addDefaultExcludes) { - this.encoding = encoding; - this.propertiesEncoding = propertiesEncoding; - this.delimiters = delimiters; - this.useDefaultDelimiters = useDefaultDelimiters; - this.escapeString = escapeString; - this.nonFilteredFileExtensions = Collections.unmodifiableList(nonFilteredFileExtensions); - this.addDefaultExcludes = addDefaultExcludes; + private final List filters; + private final boolean useBuildFilters; + private final boolean escapeWindowsPaths; + private final boolean supportMultiLineFiltering; + private final boolean fileNameFiltering; + private final String outputDirectory; + private final boolean skip; + + private ResourcesPluginSettings(Xpp3Dom configuration, String projectEncoding) { + this.encoding = text(configuration, "encoding", projectEncoding); + this.propertiesEncoding = text(configuration, "propertiesEncoding", null); + this.delimiters = new LinkedHashSet<>(texts(configuration, "delimiters")); + this.useDefaultDelimiters = flag(configuration, "useDefaultDelimiters", "true"); + this.escapeString = text(configuration, "escapeString", null); + this.nonFilteredFileExtensions = Collections.unmodifiableList(texts(configuration, "nonFilteredFileExtensions")); + this.addDefaultExcludes = flag(configuration, "addDefaultExcludes", "true"); + this.filters = Collections.unmodifiableList(texts(configuration, "filters")); + this.useBuildFilters = flag(configuration, "useBuildFilters", "true"); + this.escapeWindowsPaths = flag(configuration, "escapeWindowsPaths", "true"); + this.supportMultiLineFiltering = flag(configuration, "supportMultiLineFiltering", "false"); + this.fileNameFiltering = flag(configuration, "fileNameFiltering", "false"); + this.outputDirectory = text(configuration, "outputDirectory", null); + this.skip = flag(configuration, "skip", "false"); } public static ResourcesPluginSettings from(Xpp3Dom configuration, String projectEncoding) { - return new ResourcesPluginSettings( - text(configuration, "encoding", projectEncoding), - text(configuration, "propertiesEncoding", null), - new LinkedHashSet<>(texts(configuration, "delimiters")), - flag(configuration, "useDefaultDelimiters"), - text(configuration, "escapeString", null), - texts(configuration, "nonFilteredFileExtensions"), - flag(configuration, "addDefaultExcludes")); + return new ResourcesPluginSettings(configuration, projectEncoding); } public static Xpp3Dom effectiveResourcesConfiguration(MavenProject project) { @@ -83,8 +89,8 @@ private static String text(Xpp3Dom configuration, String name, String fallback) return child == null || child.getValue() == null ? fallback : child.getValue(); } - private static boolean flag(Xpp3Dom configuration, String name) { - return Boolean.parseBoolean(text(configuration, name, "true")); + private static boolean flag(Xpp3Dom configuration, String name, String defaultValue) { + return Boolean.parseBoolean(text(configuration, name, defaultValue)); } private static List texts(Xpp3Dom configuration, String name) { @@ -127,4 +133,37 @@ public List getNonFilteredFileExtensions() { public boolean isAddDefaultExcludes() { return addDefaultExcludes; } + + public List filterFiles(List buildFilters, Path basedir) { + List combined = new ArrayList<>(); + if (useBuildFilters) { + combined.addAll(buildFilters); + } + combined.addAll(filters); + return combined.stream().map(basedir::resolve).toList(); + } + + public boolean isEscapeWindowsPaths() { + return escapeWindowsPaths; + } + + public boolean isSupportMultiLineFiltering() { + return supportMultiLineFiltering; + } + + public boolean isFileNameFiltering() { + return fileNameFiltering; + } + + public List warnings() { + List warnings = new ArrayList<>(); + if (outputDirectory != null) { + warnings.add("maven-resources-plugin " + outputDirectory + + " is ignored; struts:watch writes to the project's build output directory"); + } + if (skip) { + warnings.add("maven-resources-plugin is true; struts:watch pushes resources regardless"); + } + return warnings; + } } diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java index 9d0b944074..fc73a4828d 100644 --- a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java @@ -95,20 +95,22 @@ public void execute() throws MojoFailureException { ResourcesPluginSettings settings = ResourcesPluginSettings.from( ResourcesPluginSettings.effectiveResourcesConfiguration(project), project.getProperties().getProperty("project.build.sourceEncoding")); + for (String warning : settings.warnings()) { + getLog().warn(warning); + } + List filterFiles = settings.filterFiles(project.getBuild().getFilters(), basedir); List roots = project.getResources().stream() .map(resource -> WatchedRoot.of(resource, basedir)) .toList(); ResourceScanner scanner = new ResourceScanner(roots, settings.isAddDefaultExcludes()); FilteringResourcePusher filteringPusher = - new FilteringResourcePusher(resourcesFiltering, project, session, settings, outputDirectory); + new FilteringResourcePusher(resourcesFiltering, project, session, settings, outputDirectory, + filterFiles); ResourcePusher pusher = loggingPusher(filteringPusher, basedir); pushStaleOutputs(scanner.scan(), filteringPusher::outputPathOf, pusher, (message, e) -> getLog().error(message, e)); - List filterFiles = project.getBuild().getFilters().stream() - .map(filter -> basedir.resolve(filter)) - .toList(); ResourceWatcher watcher = new ResourceWatcher(scanner, pusher, filterFiles, message -> getLog().debug(message), (message, e) -> getLog().error(message, e)); watcher.start(); diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java index 15ee57494b..32d76efb9d 100644 --- a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/FilteringResourcePusherTest.java @@ -25,6 +25,7 @@ import org.apache.maven.shared.filtering.DefaultMavenFileFilter; import org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering; import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -32,6 +33,7 @@ import org.sonatype.plexus.build.incremental.ThreadBuildContext; import java.io.IOException; +import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -60,8 +62,9 @@ private FilteringResourcePusher pusher(Xpp3Dom configuration) { DefaultMavenResourcesFiltering filtering = new DefaultMavenResourcesFiltering(new DefaultMavenFileFilter(new ThreadBuildContext()), new ThreadBuildContext()); MavenSession session = new MavenSession(null, new DefaultMavenExecutionRequest(), new DefaultMavenExecutionResult(), project); - return new FilteringResourcePusher(filtering, project, session, - ResourcesPluginSettings.from(configuration, "UTF-8"), output); + ResourcesPluginSettings settings = ResourcesPluginSettings.from(configuration, "UTF-8"); + return new FilteringResourcePusher(filtering, project, session, settings, output, + settings.filterFiles(project.getBuild().getFilters(), temp.getRoot().toPath())); } private SourceFile write(String relativePath, byte[] content, boolean filtering, String targetPath) throws IOException { @@ -179,4 +182,44 @@ public void deleteOfMissingOutputIsANoOp() throws IOException { assertThat(output.resolve("a.properties")).doesNotExist(); } + + @Test + public void pushSubstitutesPropertiesFromPluginLevelFilters() throws IOException { + Files.writeString(temp.getRoot().toPath().resolve("extra.properties"), "extra=from-plugin-filter\n"); + SourceFile file = write("a.properties", "name=${extra}\n", true); + + pusher(configuration("extra.properties")).push(file); + + assertThat(output.resolve("a.properties")).hasContent("name=from-plugin-filter"); + } + + @Test + public void pushSubstitutesPropertiesFromBuildFilters() throws IOException { + Files.writeString(temp.getRoot().toPath().resolve("build.properties"), "fromBuild=yes\n"); + project.getBuild().addFilter("build.properties"); + SourceFile file = write("a.properties", "v=${fromBuild}\n", true); + + pusher(null).push(file); + + assertThat(output.resolve("a.properties")).hasContent("v=yes"); + } + + @Test + public void useBuildFiltersFalseIgnoresBuildFilters() throws IOException { + Files.writeString(temp.getRoot().toPath().resolve("build.properties"), "fromBuild=yes\n"); + project.getBuild().addFilter("build.properties"); + SourceFile file = write("a.properties", "v=${fromBuild}\n", true); + + pusher(configuration("false")).push(file); + + assertThat(output.resolve("a.properties")).hasContent("v=${fromBuild}"); + } + + private static Xpp3Dom configuration(String children) { + try { + return Xpp3DomBuilder.build(new StringReader("" + children + "")); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } } diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java index a7e05ed66a..c97e2b1f82 100644 --- a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/ResourcesPluginSettingsTest.java @@ -26,6 +26,7 @@ import org.junit.Test; import java.io.StringReader; +import java.nio.file.Path; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -42,6 +43,53 @@ public void defaultsWhenNoConfiguration() { assertThat(settings.isAddDefaultExcludes()).isTrue(); assertThat(settings.getNonFilteredFileExtensions()).isEmpty(); assertThat(settings.getEscapeString()).isNull(); + assertThat(settings.isEscapeWindowsPaths()).isTrue(); + assertThat(settings.isSupportMultiLineFiltering()).isFalse(); + assertThat(settings.isFileNameFiltering()).isFalse(); + assertThat(settings.filterFiles(List.of("build.properties"), Path.of("/base"))) + .containsExactly(Path.of("/base/build.properties")); + assertThat(settings.warnings()).isEmpty(); + } + + @Test + public void readsFilterFileAndEscapingSettings() throws Exception { + Xpp3Dom configuration = Xpp3DomBuilder.build(new StringReader( + "plugin.properties" + + "false" + + "true" + + "true")); + + ResourcesPluginSettings settings = ResourcesPluginSettings.from(configuration, "UTF-8"); + + assertThat(settings.isEscapeWindowsPaths()).isFalse(); + assertThat(settings.isSupportMultiLineFiltering()).isTrue(); + assertThat(settings.isFileNameFiltering()).isTrue(); + assertThat(settings.filterFiles(List.of("build.properties"), Path.of("/base"))) + .containsExactly(Path.of("/base/build.properties"), Path.of("/base/plugin.properties")); + } + + @Test + public void useBuildFiltersFalseKeepsOnlyPluginFilters() throws Exception { + Xpp3Dom configuration = Xpp3DomBuilder.build(new StringReader( + "false" + + "plugin.properties")); + + ResourcesPluginSettings settings = ResourcesPluginSettings.from(configuration, "UTF-8"); + + assertThat(settings.filterFiles(List.of("build.properties"), Path.of("/base"))) + .containsExactly(Path.of("/base/plugin.properties")); + } + + @Test + public void warnsAboutOutputDirectoryAndSkip() throws Exception { + Xpp3Dom configuration = Xpp3DomBuilder.build(new StringReader( + "/elsewheretrue")); + + ResourcesPluginSettings settings = ResourcesPluginSettings.from(configuration, "UTF-8"); + + assertThat(settings.warnings()).hasSize(2); + assertThat(settings.warnings().get(0)).contains("", "/elsewhere"); + assertThat(settings.warnings().get(1)).contains(""); } @Test From d40f83950b896496f9eb034522195401be963a4e Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:25:49 +0100 Subject: [PATCH 19/22] WW-5864 fix(tools): one reported background watcher per output directory A Throwable escaping the background watcher is logged before the thread ends, and a second bound execution in the same JVM for the same output directory logs that a watcher is already running and returns. Co-Authored-By: Claude Opus 5.5 --- .../apache/struts2/maven/watch/WatchMojo.java | 74 +++++++++++++++---- .../struts2/maven/watch/WatchMojoTest.java | 68 +++++++++++++++++ 2 files changed, 129 insertions(+), 13 deletions(-) diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java index fc73a4828d..8843bb2df8 100644 --- a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java @@ -34,6 +34,8 @@ import java.time.Duration; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.BooleanSupplier; import java.util.function.Function; @@ -44,6 +46,8 @@ public class WatchMojo extends AbstractMojo { static final String MULTI_MODULE_MESSAGE = "struts:watch supports a single module; run it in the module that owns the resources, e.g. -pl "; + private static final Set BACKGROUND_WATCHERS = ConcurrentHashMap.newKeySet(); + /** * Milliseconds between scans of the resource directories. */ @@ -86,8 +90,40 @@ public void execute() throws MojoFailureException { } checkSingleModule(); - Path basedir = project.getBasedir().toPath(); Path outputDirectory = new File(project.getBuild().getOutputDirectory()).toPath(); + if (background) { + watchInBackground(outputDirectory); + return; + } + ResourceWatcher watcher = prepareWatcher(outputDirectory); + getLog().info("Watching " + project.getResources().size() + " resource root(s); press Ctrl+C to stop"); + long deadline = timeout > 0 ? System.nanoTime() + Duration.ofSeconds(timeout).toNanos() : 0; + BooleanSupplier keepRunning = () -> deadline == 0 || System.nanoTime() - deadline < 0; + watcher.run(Duration.ofMillis(pollInterval), keepRunning); + } + + private void watchInBackground(Path outputDirectory) { + if (!claimBackgroundWatcher(outputDirectory)) { + getLog().info("struts:watch is already watching " + outputDirectory + " in this JVM; not starting another"); + return; + } + try { + ResourceWatcher watcher = prepareWatcher(outputDirectory); + Duration interval = Duration.ofMillis(pollInterval); + Runnable task = backgroundTask(() -> watcher.run(interval, () -> true), outputDirectory, + (message, e) -> getLog().error(message, e)); + Thread thread = new Thread(task, "struts-watch"); + thread.setDaemon(true); + thread.start(); + } catch (RuntimeException | Error e) { + releaseBackgroundWatcher(outputDirectory); + throw e; + } + getLog().info("Watching " + project.getResources().size() + " resource root(s) in the background"); + } + + private ResourceWatcher prepareWatcher(Path outputDirectory) { + Path basedir = project.getBasedir().toPath(); for (String warning : new StrutsReloadInspector(outputDirectory).warnings()) { getLog().warn(warning); } @@ -114,19 +150,31 @@ public void execute() throws MojoFailureException { ResourceWatcher watcher = new ResourceWatcher(scanner, pusher, filterFiles, message -> getLog().debug(message), (message, e) -> getLog().error(message, e)); watcher.start(); + return watcher; + } - Duration interval = Duration.ofMillis(pollInterval); - if (background) { - Thread thread = new Thread(() -> watcher.run(interval, () -> true), "struts-watch"); - thread.setDaemon(true); - thread.start(); - getLog().info("Watching " + roots.size() + " resource root(s) in the background"); - return; - } - getLog().info("Watching " + roots.size() + " resource root(s); press Ctrl+C to stop"); - long deadline = timeout > 0 ? System.nanoTime() + Duration.ofSeconds(timeout).toNanos() : 0; - BooleanSupplier keepRunning = () -> deadline == 0 || System.nanoTime() - deadline < 0; - watcher.run(interval, keepRunning); + static boolean claimBackgroundWatcher(Path outputDirectory) { + return BACKGROUND_WATCHERS.add(registryKey(outputDirectory)); + } + + static void releaseBackgroundWatcher(Path outputDirectory) { + BACKGROUND_WATCHERS.remove(registryKey(outputDirectory)); + } + + private static Path registryKey(Path outputDirectory) { + return outputDirectory.toAbsolutePath().normalize(); + } + + static Runnable backgroundTask(Runnable work, Path outputDirectory, BiConsumer error) { + return () -> { + try { + work.run(); + } catch (Throwable e) { + error.accept("struts:watch background watcher for " + outputDirectory + " stopped", e); + } finally { + releaseBackgroundWatcher(outputDirectory); + } + }; } boolean shouldRun() { diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java index 5523c84082..83b04868e2 100644 --- a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java @@ -20,10 +20,12 @@ import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.ArgumentCaptor; import java.io.File; import java.nio.file.Files; @@ -35,7 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class WatchMojoTest { @@ -139,6 +144,69 @@ public void delete(SourceFile file) { assertThat(errors).containsExactly("Failed to push bad.txt"); } + @Test + public void secondBackgroundWatcherForTheSameOutputDirectoryIsRefused() throws Exception { + Path out = temp.newFolder("claimed").toPath(); + Path other = temp.newFolder("other").toPath(); + try { + assertThat(WatchMojo.claimBackgroundWatcher(out)).isTrue(); + assertThat(WatchMojo.claimBackgroundWatcher(out.resolve("x").resolve(".."))).isFalse(); + assertThat(WatchMojo.claimBackgroundWatcher(other)).isTrue(); + + WatchMojo.releaseBackgroundWatcher(out); + + assertThat(WatchMojo.claimBackgroundWatcher(out)).isTrue(); + } finally { + WatchMojo.releaseBackgroundWatcher(out); + WatchMojo.releaseBackgroundWatcher(other); + } + } + + @Test + public void boundExecutionReturnsWhenAWatcherAlreadyRunsForTheOutputDirectory() throws Exception { + Path out = temp.newFolder("running").toPath(); + WatchMojo mojo = new WatchMojo(); + mojo.background = true; + mojo.enabled = true; + MavenSession session = mock(MavenSession.class); + when(session.getProjects()).thenReturn(List.of(new MavenProject())); + mojo.session = session; + mojo.project = new MavenProject(); + mojo.project.getBuild().setOutputDirectory(out.toString()); + Log log = mock(Log.class); + mojo.setLog(log); + WatchMojo.claimBackgroundWatcher(out); + try { + mojo.execute(); + } finally { + WatchMojo.releaseBackgroundWatcher(out); + } + + ArgumentCaptor info = ArgumentCaptor.forClass(CharSequence.class); + verify(log).info(info.capture()); + assertThat(info.getValue().toString()).contains("already watching"); + verify(log, never()).warn(any(CharSequence.class)); + } + + @Test + public void backgroundTaskReportsEscapingThrowableAndReleasesItsClaim() throws Exception { + Path out = temp.newFolder("dying").toPath(); + List reported = new ArrayList<>(); + Error failure = new LinkageError("boom"); + WatchMojo.claimBackgroundWatcher(out); + + WatchMojo.backgroundTask(() -> { + throw failure; + }, out, (message, e) -> reported.add(e)).run(); + + assertThat(reported).containsExactly(failure); + try { + assertThat(WatchMojo.claimBackgroundWatcher(out)).isTrue(); + } finally { + WatchMojo.releaseBackgroundWatcher(out); + } + } + private File write(Path path, long lastModified) throws Exception { Files.writeString(path, "x"); File file = path.toFile(); From d8e5526101d42672c07982d2707b256e50c89cd5 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:29:15 +0100 Subject: [PATCH 20/22] WW-5864 docs(tools): pasteable execution snippet and multi-module notes Co-Authored-By: Claude Opus 5.5 --- tools/struts-maven-plugin/README.md | 40 +++++++++++++++++++---------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/tools/struts-maven-plugin/README.md b/tools/struts-maven-plugin/README.md index e4c7e6184d..4ae083a850 100644 --- a/tools/struts-maven-plugin/README.md +++ b/tools/struts-maven-plugin/README.md @@ -31,22 +31,32 @@ is needed. Next to a server started in another terminal, the goal blocks until Ctrl+C: ```sh -mvn struts:watch -pl +mvn struts:watch ``` -Or bound to `process-resources` in the background, switched on from the command line, together with the Jetty plugin. This `` goes inside the plugin declaration above: +In a multi-module build, run it from the root with `-pl `. Do not add `-am`: it puts the module's dependencies +into the build too, and the goal then fails because it supports a single module. + +Or bound to `process-resources` in the background, switched on from the command line, together with the Jetty plugin: ```xml - - watch - process-resources - - watch - - - true - - + + org.apache.struts + struts-maven-plugin + X.Y.Z + + + watch + process-resources + + watch + + + true + + + + ``` ```sh @@ -57,7 +67,8 @@ Without `-Dstruts.watch` a background execution does nothing. Each push is logged, for example `pushed struts.xml -> target/classes/struts.xml`. Files whose output is missing or older than the source are pushed once at startup. Filtering follows the module's `maven-resources-plugin` -configuration. +configuration, including its plugin-level ``. The pom is read once at startup: restart the goal after changing +the resource or filtering configuration. ## Parameters @@ -87,5 +98,6 @@ the reload switches off, so to try it there flip them locally. ## Limitations -- Single module only: in a multi-reactor build the goal fails with a message to run it with `-pl `. +- Single module only: in a multi-module build the goal fails with a message to run it with `-pl ` (without + `-am`). - No Java class reloading, no Gradle support, no Struts Boot support. From ea4814954d9947a7042d4a30161c719992bb74a4 Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 09:50:48 +0100 Subject: [PATCH 21/22] WW-5864 docs(tools): dev profile to keep struts:watch on locally Co-Authored-By: Claude Opus 5.5 --- tools/struts-maven-plugin/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tools/struts-maven-plugin/README.md b/tools/struts-maven-plugin/README.md index 4ae083a850..7b52e05cfd 100644 --- a/tools/struts-maven-plugin/README.md +++ b/tools/struts-maven-plugin/README.md @@ -65,6 +65,24 @@ mvn jetty:run -Dstruts.watch Without `-Dstruts.watch` a background execution does nothing. +To keep it on while developing, set the property in a profile rather than in the pom's top-level ``. +Switched on there, every `package`, `install` and CI build would start a watcher, and a multi-module build would fail +the single-module check: + +```xml + + + dev + + true + + + +``` + +Run `mvn jetty:run -Pdev`, or list `dev` under `` in your own `~/.m2/settings.xml` so plain +`mvn jetty:run` watches on your machine while CI never does. + Each push is logged, for example `pushed struts.xml -> target/classes/struts.xml`. Files whose output is missing or older than the source are pushed once at startup. Filtering follows the module's `maven-resources-plugin` configuration, including its plugin-level ``. The pom is read once at startup: restart the goal after changing From bdebab4e6981d9c7a571752877745b2141430bda Mon Sep 17 00:00:00 2001 From: Lukasz Lenart Date: Sat, 14 Nov 2026 10:00:39 +0100 Subject: [PATCH 22/22] WW-5864 chore(tools): mark the Struts Maven Plugin as experimental The module name carries the [EXPERIMENTAL] suffix like Struts Boot, and the README says goals, parameters and defaults may change between minor releases. Co-Authored-By: Claude Opus 5.5 --- tools/struts-maven-plugin/README.md | 2 ++ tools/struts-maven-plugin/pom.xml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/struts-maven-plugin/README.md b/tools/struts-maven-plugin/README.md index 7b52e05cfd..7e0ac3ff23 100644 --- a/tools/struts-maven-plugin/README.md +++ b/tools/struts-maven-plugin/README.md @@ -3,6 +3,8 @@ `struts:watch` copies edited resources (`struts.xml`, `*.properties`, FreeMarker templates, validation files) into `target/classes` while an application runs, so Struts' own reload picks them up without a rebuild or restart. +The Struts Maven Plugin is experimental: its goals, parameters and defaults may change between minor releases. + It pushes resource changes only. It does not compile or reload Java classes: use a restart or debugger hotswap for those. Webapp files (JSP, FTL under `src/main/webapp`) are already served from source. diff --git a/tools/struts-maven-plugin/pom.xml b/tools/struts-maven-plugin/pom.xml index f9fbb50f37..d59ce7881e 100644 --- a/tools/struts-maven-plugin/pom.xml +++ b/tools/struts-maven-plugin/pom.xml @@ -30,7 +30,7 @@ struts-maven-plugin maven-plugin - Struts 2 Maven Plugin + Struts 2 Maven Plugin [EXPERIMENTAL] 3.9.16