-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathrun-all-quarkus.java
More file actions
285 lines (244 loc) · 12.5 KB
/
run-all-quarkus.java
File metadata and controls
285 lines (244 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 21
//DEPS com.microsoft.playwright:playwright:1.55.0
//DEPS info.picocli:picocli:4.7.7
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.*;
import picocli.CommandLine;
import picocli.CommandLine.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@Command(name = "run-all-quarkus",
mixinStandardHelpOptions = true,
description = "For each subfolder: mvn quarkus:dev → open with Playwright → click Solve → screenshot → stop.")
class App implements Runnable {
@Option(names = {"-d","--java-folder"}, required = true,
description = "Folder containing your Quarkus app directories (each must be a Maven project).")
Path javaFolder;
@Option(names = {"-u","--url"}, defaultValue = "http://localhost:8080",
description = "Base URL to open in the browser (default: ${DEFAULT-VALUE}).")
String baseUrl;
@Option(names = {"-s","--solve-selector"}, defaultValue = "button:has-text(\"Solve\")",
description = "Playwright selector for the Solve button (default: ${DEFAULT-VALUE}).")
String solveSelector;
@Option(names = {"--startup-timeout-seconds"}, defaultValue = "120",
description = "How long to wait for Quarkus dev to start (default: ${DEFAULT-VALUE}).")
long startupTimeoutSeconds;
@Option(names = {"--solve-timeout-seconds"}, defaultValue = "120",
description = "How long to wait for the solve to complete (default: ${DEFAULT-VALUE}).")
long solveTimeoutSeconds;
@Option(names = {"--screenshot-dir"},
description = "Directory to write PNG screenshots. If omitted, screenshots are saved next to pom.xml.")
Path screenshotDir;
@Option(names = {"--enterprise"}, defaultValue = "false",
description = "Run Quarkus dev with the enterprise edition flag (-Denterprise) (default: ${DEFAULT-VALUE}).")
Boolean enterprise;
@Option(names = {"--headless"}, defaultValue = "true",
description = "Run browser headless (default: ${DEFAULT-VALUE}).")
Boolean headless;
@Option(names = {"--record-video"}, defaultValue = "false",
description = "Enable video recording for visual validation (default: ${DEFAULT-VALUE}).")
Boolean recordVideo;
@Option(names = {"--video-dir"},
description = "Directory to save video recordings (default: same as screenshot-dir or project dir).")
Path videoDir;
private static final Pattern STARTED_PATTERN = Pattern.compile(
"(?i)(listening on: http://|installed features|dev services|dev mode starting in|quarkus .* started in .*\\.)");
public static void main(String[] args) {
int exit = new CommandLine(new App()).execute(args);
System.exit(exit);
}
@Override public void run() {
requireDir(javaFolder);
if(Objects.nonNull(screenshotDir)) {
try {
Files.createDirectories(screenshotDir);
} catch (IOException e) {
throw new RuntimeException("Cannot create screenshot dir: " + screenshotDir, e);
}
}
if(recordVideo && Objects.nonNull(videoDir)) {
try {
Files.createDirectories(videoDir);
} catch (IOException e) {
throw new RuntimeException("Cannot create video dir: " + videoDir, e);
}
}
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium()
.launch(new BrowserType.LaunchOptions().setHeadless(headless));
var contextOptions = new Browser.NewContextOptions().setViewportSize(1500, 750);
// Configure video recording if enabled
if (recordVideo) {
Path videoDirToUse = videoDir != null ? videoDir :
screenshotDir != null ? screenshotDir : javaFolder;
contextOptions.setRecordVideoDir(videoDirToUse)
.setRecordVideoSize(1500, 750);
System.out.println("Video recording enabled. Videos will be saved to: " + videoDirToUse.toAbsolutePath());
}
BrowserContext ctx = browser.newContext(contextOptions);
try (Stream<Path> children = Files.list(javaFolder)) {
List<Path> dirs = children
.filter(Files::isDirectory)
.sorted()
.toList();
for (Path dir : dirs) {
Path pom = dir.resolve("pom.xml");
if (!Files.exists(pom)) {
System.out.println("Skipping (no pom.xml): " + dir);
continue;
}
// Check if pom.xml mentions "quarkus" (dependency, plugin, etc.)
boolean isQuarkusProject = false;
try (Stream<String> lines = Files.lines(pom)) {
isQuarkusProject = lines.anyMatch(l -> l.toLowerCase().contains("quarkus"));
} catch (IOException e) {
System.err.println("Could not read pom.xml for " + dir + ": " + e.getMessage());
}
if (!isQuarkusProject) {
System.out.println("Skipping (no Quarkus reference found): " + dir);
continue;
}
System.out.println("\n=== " + dir.getFileName() + " ===");
ProcessWrapper quarkus = null;
Page page = null;
try {
quarkus = startQuarkusDev(dir);
waitForQuarkusStarted(quarkus);
page = ctx.newPage();
System.out.println("Opening: " + baseUrl);
page.navigate(baseUrl, new Page.NavigateOptions().setWaitUntil(WaitUntilState.NETWORKIDLE));
// Click the Solve button
System.out.println("Clicking Solve (" + solveSelector + ")");
page.locator(solveSelector).first().click(new Locator.ClickOptions().setTimeout(ms(15)));
waitForSolve(page);
// Screenshot
String fileSafe = dir.getFileName().toString().replaceAll("[^a-zA-Z0-9._-]", "_");
Path shot = null;
if(screenshotDir != null) {
shot = screenshotDir.resolve(fileSafe + ".png");
} else {
// saving in original dir next to the pom.xml file.
shot = dir.resolve(fileSafe + "-screenshot.png");
}
page.screenshot(new Page.ScreenshotOptions()
.setFullPage(false)
.setPath(shot));
System.out.println("Saved screenshot: " + shot.toAbsolutePath());
} catch (Exception e) {
System.err.println("Error while processing " + dir.getFileName() + ": " + e.getMessage());
e.printStackTrace(System.err);
} finally {
if (page != null && !page.isClosed()) {
if (recordVideo) {
// Close page to finalize video recording
page.close();
// Get the video path and rename it to match project name
Path video = page.video().path();
if (video != null && Files.exists(video)) {
String fileSafe = dir.getFileName().toString().replaceAll("[^a-zA-Z0-9._-]", "_");
Path targetVideo = video.getParent().resolve(fileSafe + ".webm");
try {
Files.move(video, targetVideo, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Saved video: " + targetVideo.toAbsolutePath());
} catch (IOException e) {
System.err.println("Failed to rename video: " + e.getMessage());
}
}
} else {
page.close();
}
}
if (quarkus != null) stopQuarkus(quarkus);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private void waitForSolve(Page page) {
// Strategy 2: a 'Solve' text appears on the solve button again after solving
try {
Thread.sleep(5000); //wait 5 seconds so solver is definitely started.
page.waitForSelector("text=/\\bSolve\\b/i",
new Page.WaitForSelectorOptions().setState(WaitForSelectorState.VISIBLE).setTimeout(ms(solveTimeoutSeconds)));
} catch (Exception e) {
// If we still didn't get it, just continue; we’ll still take a screenshot of the current state.
System.out.println("Solve might not have signaled completion explicitly; proceeding to screenshot.");
}
}
private ProcessWrapper startQuarkusDev(Path dir) throws IOException {
List<String> command = new java.util.ArrayList<>(List.of("mvn", "-q", "quarkus:dev"));
if (enterprise) command.add("-Denterprise");
ProcessBuilder pb = new ProcessBuilder()
.directory(dir.toFile())
.command(command);
pb.environment().putIfAbsent("JAVA_TOOL_OPTIONS", "-Dfile.encoding=UTF-8");
pb.redirectErrorStream(true);
Process p = pb.start();
return new ProcessWrapper(p, dir.getFileName().toString());
}
private void waitForQuarkusStarted(ProcessWrapper pw) throws Exception {
System.out.println("Starting mvn quarkus:dev ...");
var latch = new CountDownLatch(1);
// Drain output asynchronously and look for startup tokens
Thread t = new Thread(() -> {
try (BufferedReader br = new BufferedReader(new InputStreamReader(pw.process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println("[" + pw.name + "] " + line);
if (STARTED_PATTERN.matcher(line).find() || line.toLowerCase().contains("listening on: http")) {
latch.countDown();
}
}
} catch (IOException ignored) {}
}, "quarkus-out-" + pw.name);
t.setDaemon(true);
t.start();
boolean ok = latch.await(startupTimeoutSeconds, TimeUnit.SECONDS);
if (!ok) {
throw new TimeoutException("Quarkus did not start within " + startupTimeoutSeconds + "s.");
}
System.out.println("Quarkus reported it is listening.");
}
private void stopQuarkus(ProcessWrapper pw) {
try {
// Quarkus dev accepts 'q' to quit
OutputStream os = pw.process.getOutputStream();
os.write('q');
os.write('\n');
os.flush();
} catch (IOException ignored) {}
try {
if (!pw.process.waitFor(10, TimeUnit.SECONDS)) {
pw.process.destroy();
if (!pw.process.waitFor(5, TimeUnit.SECONDS)) {
pw.process.destroyForcibly();
}
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
return;
}
System.out.println("Stopped: " + pw.name);
}
private static long ms(long seconds) {
return Duration.ofSeconds(seconds).toMillis();
}
private static void requireDir(Path dir) {
Objects.requireNonNull(dir, "dir");
if (!Files.isDirectory(dir)) {
throw new CommandLine.ParameterException(new CommandLine(new App()),
"Not a directory: " + dir.toAbsolutePath());
}
}
private record ProcessWrapper(Process process, String name) {}
}