This is an automated email from the ASF dual-hosted git repository.

slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-site-plugin.git

commit aaf9f9dc1c23273c51ec0257820e5815c2019431
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Wed Nov 4 08:51:05 2026 +0000

    [MSITE-849] Make MavenProject injectable while site:run renders pages
    
    site:run rendered pages on the HTTP server's own threads, where Maven's 
execution scopes (MavenProject, MojoExecution) are not available, so Doxia 
components that inject them failed per page with OutOfScopeException. Requests 
are now served on the Mojo thread. Unexpected failures while serving a request 
return a 500 instead of dropping the connection.
---
 .../maven/plugins/site/run/DoxiaHandler.java       |  4 +
 .../maven/plugins/site/run/MojoThreadExecutor.java | 65 ++++++++++++++++
 .../apache/maven/plugins/site/run/SiteRunMojo.java | 16 +---
 .../plugins/site/run/MojoThreadExecutorTest.java   | 86 ++++++++++++++++++++++
 4 files changed, 159 insertions(+), 12 deletions(-)

diff --git a/src/main/java/org/apache/maven/plugins/site/run/DoxiaHandler.java 
b/src/main/java/org/apache/maven/plugins/site/run/DoxiaHandler.java
index ee410494..bb84c5a9 100644
--- a/src/main/java/org/apache/maven/plugins/site/run/DoxiaHandler.java
+++ b/src/main/java/org/apache/maven/plugins/site/run/DoxiaHandler.java
@@ -119,6 +119,10 @@ public class DoxiaHandler implements HttpHandler {
             }
         } catch (RendererException e) {
             sendError(exchange, 500, "Error rendering document: " + 
e.getMessage());
+        } catch (RuntimeException e) {
+            // e.g. a Doxia component that cannot be instantiated; the JDK 
server would only drop the connection
+            log.error("Error handling " + exchange.getRequestURI().getPath(), 
e);
+            sendError(exchange, 500, "Error rendering document: " + e);
         }
     }
 
diff --git 
a/src/main/java/org/apache/maven/plugins/site/run/MojoThreadExecutor.java 
b/src/main/java/org/apache/maven/plugins/site/run/MojoThreadExecutor.java
new file mode 100644
index 00000000..40a1e127
--- /dev/null
+++ b/src/main/java/org/apache/maven/plugins/site/run/MojoThreadExecutor.java
@@ -0,0 +1,65 @@
+/*
+ * 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.maven.plugins.site.run;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.Executor;
+import java.util.concurrent.LinkedBlockingQueue;
+
+/**
+ * An {@link Executor} that runs every submitted task on the thread calling 
{@link #runUntilStopped()}.
+ * <p>
+ * {@code site:run} hands HTTP requests to this executor and serves them from 
the Mojo thread. Maven's
+ * thread-bound scopes ({@code MavenProject}, {@code MojoExecution}, {@code 
MavenSession}) are only
+ * available on that thread, and Doxia components contributed by site 
dependencies, such as parsers, are
+ * instantiated lazily while a page is rendered.
+ */
+class MojoThreadExecutor implements Executor {
+    private static final Runnable STOP = () -> {};
+
+    private final BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();
+
+    @Override
+    public void execute(Runnable task) {
+        tasks.add(task);
+    }
+
+    /**
+     * Runs submitted tasks one at a time on the calling thread until {@link 
#stop()} is called. A task that
+     * fails does not end the loop.
+     *
+     * @throws InterruptedException if the calling thread is interrupted while 
waiting for a task
+     */
+    void runUntilStopped() throws InterruptedException {
+        for (Runnable task = tasks.take(); task != STOP; task = tasks.take()) {
+            try {
+                task.run();
+            } catch (RuntimeException e) {
+                // the task reports its own failure to the client; keep serving
+            }
+        }
+    }
+
+    /**
+     * Ends {@link #runUntilStopped()} once the tasks submitted before this 
call have run.
+     */
+    void stop() {
+        tasks.add(STOP);
+    }
+}
diff --git a/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java 
b/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java
index 23101839..76e83de2 100644
--- a/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java
+++ b/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java
@@ -27,9 +27,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 
 import com.sun.net.httpserver.HttpServer;
 import org.apache.maven.doxia.site.inheritance.SiteModelInheritanceAssembler;
@@ -101,11 +98,8 @@ public class SiteRunMojo extends AbstractSiteRenderingMojo {
             throw new MojoExecutionException("Error creating HTTP server on " 
+ host + ":" + port, e);
         }
 
-        ExecutorService executor = Executors.newCachedThreadPool(runnable -> {
-            Thread thread = new Thread(runnable, "site:run");
-            thread.setDaemon(true);
-            return thread;
-        });
+        // Pages are rendered on this thread: Maven's execution scopes are 
bound to it (MSITE-849)
+        MojoThreadExecutor executor = new MojoThreadExecutor();
         server.setExecutor(executor);
         server.createContext(
                 "/", new DoxiaHandler(tempWebappDirectory, siteRenderer, 
i18nDoxiaContexts, getLocales(), getLog()));
@@ -118,18 +112,16 @@ public class SiteRunMojo extends 
AbstractSiteRenderingMojo {
                 .build());
 
         // Watch it
-        CountDownLatch latch = new CountDownLatch(1);
         Runtime.getRuntime()
                 .addShutdownHook(new Thread(
                         () -> {
                             server.stop(0);
-                            executor.shutdown();
-                            latch.countDown();
+                            executor.stop();
                         },
                         "site:run-shutdown"));
 
         try {
-            latch.await();
+            executor.runUntilStopped();
         } catch (InterruptedException e) {
             getLog().warn("site:run server was interrupted", e);
         }
diff --git 
a/src/test/java/org/apache/maven/plugins/site/run/MojoThreadExecutorTest.java 
b/src/test/java/org/apache/maven/plugins/site/run/MojoThreadExecutorTest.java
new file mode 100644
index 00000000..c3bb2027
--- /dev/null
+++ 
b/src/test/java/org/apache/maven/plugins/site/run/MojoThreadExecutorTest.java
@@ -0,0 +1,86 @@
+/*
+ * 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.maven.plugins.site.run;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Tests for {@link MojoThreadExecutor} (MSITE-849).
+ */
+class MojoThreadExecutorTest {
+
+    /**
+     * Tasks submitted from other threads, as the HTTP server does, see the 
thread-bound state of the
+     * thread running the loop, which is how Maven's execution scopes are 
looked up.
+     */
+    @Test
+    void runsTasksOnTheLoopThread() throws Exception {
+        ThreadLocal<String> scope = new ThreadLocal<>();
+        MojoThreadExecutor executor = new MojoThreadExecutor();
+        AtomicReference<String> seen = new AtomicReference<>();
+        AtomicReference<Thread> ranOn = new AtomicReference<>();
+        CountDownLatch done = new CountDownLatch(1);
+
+        Thread submitter = new Thread(() -> {
+            executor.execute(() -> {
+                seen.set(scope.get());
+                ranOn.set(Thread.currentThread());
+                done.countDown();
+            });
+            try {
+                assertTrue(done.await(10, TimeUnit.SECONDS));
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+            } finally {
+                executor.stop();
+            }
+        });
+
+        scope.set("mojo execution scope");
+        submitter.start();
+        executor.runUntilStopped();
+        submitter.join();
+
+        assertEquals("mojo execution scope", seen.get());
+        assertSame(Thread.currentThread(), ranOn.get());
+    }
+
+    @Test
+    void failingTaskDoesNotStopTheLoop() throws Exception {
+        MojoThreadExecutor executor = new MojoThreadExecutor();
+        AtomicReference<Boolean> second = new AtomicReference<>(false);
+
+        executor.execute(() -> {
+            throw new IllegalStateException("boom");
+        });
+        executor.execute(() -> second.set(true));
+        executor.stop();
+        executor.runUntilStopped();
+
+        assertTrue(second.get());
+    }
+}

Reply via email to