1use crate::config::E2eConfig;
7use crate::escape::{escape_java, sanitize_filename};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, HttpFixture};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::ResolvedCrateConfig;
12use alef_core::hash::{self, CommentStyle};
13use alef_core::template_versions as tv;
14use anyhow::Result;
15use heck::{ToLowerCamelCase, ToUpperCamelCase};
16use std::path::PathBuf;
17
18use super::E2eCodegen;
19use super::client;
20
21fn is_numeric_type_hint(ty: &str) -> bool {
23 matches!(ty, "f32" | "f64" | "float" | "double" | "Float" | "Double")
24}
25
26fn is_java_builtin_type(ty: &str) -> bool {
28 matches!(
29 ty,
30 "String" | "Boolean" | "Integer" | "Long" | "Double" | "Float" | "Byte" | "Short" | "Character" | "Void"
31 )
32}
33
34pub struct JavaCodegen;
36
37impl E2eCodegen for JavaCodegen {
38 fn generate(
39 &self,
40 groups: &[FixtureGroup],
41 e2e_config: &E2eConfig,
42 config: &ResolvedCrateConfig,
43 type_defs: &[alef_core::ir::TypeDef],
44 enums: &[alef_core::ir::EnumDef],
45 ) -> Result<Vec<GeneratedFile>> {
46 let lang = self.language_name();
47 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
48
49 let mut files = Vec::new();
50
51 let call = &e2e_config.call;
53 let overrides = call.overrides.get(lang);
54 let _module_path = overrides
55 .and_then(|o| o.module.as_ref())
56 .cloned()
57 .unwrap_or_else(|| call.module.clone());
58 let function_name = overrides
59 .and_then(|o| o.function.as_ref())
60 .cloned()
61 .unwrap_or_else(|| call.function.clone());
62 let class_name = overrides
63 .and_then(|o| o.class.as_ref())
64 .cloned()
65 .unwrap_or_else(|| config.name.to_upper_camel_case());
66 let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
67 let result_var = &call.result_var;
68
69 let java_pkg = e2e_config.resolve_package("java");
71 let pkg_name = java_pkg
72 .as_ref()
73 .and_then(|p| p.name.as_ref())
74 .cloned()
75 .unwrap_or_else(|| config.name.clone());
76
77 let java_group_id = config.java_group_id();
79 let binding_pkg = config.java_package();
80 let pkg_version = config.resolved_version().unwrap_or_else(|| "0.1.0".to_string());
81
82 files.push(GeneratedFile {
84 path: output_base.join("pom.xml"),
85 content: render_pom_xml(
86 &pkg_name,
87 &java_group_id,
88 &pkg_version,
89 e2e_config.dep_mode,
90 &e2e_config.test_documents_relative_from(0),
91 ),
92 generated_header: false,
93 });
94
95 let needs_mock_server = groups
103 .iter()
104 .flat_map(|g| g.fixtures.iter())
105 .any(|f| f.needs_mock_server());
106
107 let mut test_base = output_base.join("src").join("test").join("java");
111 for segment in java_group_id.split('.') {
112 test_base = test_base.join(segment);
113 }
114 let test_base = test_base.join("e2e");
115
116 if needs_mock_server {
117 files.push(GeneratedFile {
118 path: test_base.join("MockServerListener.java"),
119 content: render_mock_server_listener(&java_group_id),
120 generated_header: true,
121 });
122 files.push(GeneratedFile {
123 path: output_base
124 .join("src")
125 .join("test")
126 .join("resources")
127 .join("META-INF")
128 .join("services")
129 .join("org.junit.platform.launcher.LauncherSessionListener"),
130 content: format!("{java_group_id}.e2e.MockServerListener\n"),
131 generated_header: false,
132 });
133 }
134
135 let sealed_display_types: std::collections::BTreeSet<String> = std::iter::once(&e2e_config.call)
140 .chain(e2e_config.calls.values())
141 .filter_map(|c| c.overrides.get(lang))
142 .flat_map(|o| o.assert_enum_fields.values().cloned())
143 .collect();
144
145 for type_name in &sealed_display_types {
146 if let Some(enum_def) = enums.iter().find(|e| &e.name == type_name) {
147 files.push(GeneratedFile {
148 path: test_base.join(format!("{type_name}Display.java")),
149 content: render_sealed_display(type_name, enum_def, type_defs, &java_group_id),
150 generated_header: true,
151 });
152 }
153 }
154
155 let options_type = overrides.and_then(|o| o.options_type.clone());
157
158 static EMPTY_ENUM_FIELDS: std::sync::LazyLock<std::collections::HashMap<String, String>> =
160 std::sync::LazyLock::new(std::collections::HashMap::new);
161 let _enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&EMPTY_ENUM_FIELDS);
162
163 let mut effective_nested_types: std::collections::HashMap<String, String> = std::collections::HashMap::new();
165 if let Some(overrides_map) = overrides.map(|o| &o.nested_types) {
166 effective_nested_types.extend(overrides_map.clone());
167 }
168
169 let nested_types_optional = overrides.map(|o| o.nested_types_optional).unwrap_or(true);
171
172 for group in groups {
173 let active: Vec<&Fixture> = group
174 .fixtures
175 .iter()
176 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
177 .collect();
178
179 if active.is_empty() {
180 continue;
181 }
182
183 let class_file_name = format!("{}Test.java", sanitize_filename(&group.category).to_upper_camel_case());
184 let content = render_test_file(
185 &group.category,
186 &active,
187 &class_name,
188 &function_name,
189 &java_group_id,
190 &binding_pkg,
191 result_var,
192 &e2e_config.call.args,
193 options_type.as_deref(),
194 result_is_simple,
195 e2e_config,
196 &effective_nested_types,
197 nested_types_optional,
198 &config.adapters,
199 );
200 files.push(GeneratedFile {
201 path: test_base.join(class_file_name),
202 content,
203 generated_header: true,
204 });
205 }
206
207 Ok(files)
208 }
209
210 fn language_name(&self) -> &'static str {
211 "java"
212 }
213}
214
215fn render_pom_xml(
220 pkg_name: &str,
221 java_group_id: &str,
222 pkg_version: &str,
223 dep_mode: crate::config::DependencyMode,
224 test_documents_path: &str,
225) -> String {
226 let (dep_group_id, dep_artifact_id) = if let Some((g, a)) = pkg_name.split_once(':') {
228 (g, a)
229 } else {
230 (java_group_id, pkg_name)
231 };
232 let artifact_id = format!("{dep_artifact_id}-e2e-java");
233 let dep_block = match dep_mode {
234 crate::config::DependencyMode::Registry => {
235 format!(
236 r#" <dependency>
237 <groupId>{dep_group_id}</groupId>
238 <artifactId>{dep_artifact_id}</artifactId>
239 <version>{pkg_version}</version>
240 </dependency>"#
241 )
242 }
243 crate::config::DependencyMode::Local => {
244 format!(
245 r#" <dependency>
246 <groupId>{dep_group_id}</groupId>
247 <artifactId>{dep_artifact_id}</artifactId>
248 <version>{pkg_version}</version>
249 <scope>system</scope>
250 <systemPath>${{project.basedir}}/../../packages/java/target/{dep_artifact_id}-{pkg_version}.jar</systemPath>
251 </dependency>"#
252 )
253 }
254 };
255 crate::template_env::render(
256 "java/pom.xml.jinja",
257 minijinja::context! {
258 artifact_id => artifact_id,
259 java_group_id => java_group_id,
260 dep_block => dep_block,
261 junit_version => tv::maven::JUNIT,
262 jackson_version => tv::maven::JACKSON_E2E,
263 build_helper_version => tv::maven::BUILD_HELPER_MAVEN_PLUGIN,
264 maven_surefire_version => tv::maven::MAVEN_SUREFIRE_PLUGIN_E2E,
265 test_documents_path => test_documents_path,
266 },
267 )
268}
269
270fn render_mock_server_listener(java_group_id: &str) -> String {
279 let header = hash::header(CommentStyle::DoubleSlash);
280 let mut out = header;
281 out.push_str(&format!("package {java_group_id}.e2e;\n\n"));
282 out.push_str("import java.io.BufferedReader;\n");
283 out.push_str("import java.io.File;\n");
284 out.push_str("import java.io.IOException;\n");
285 out.push_str("import java.io.InputStreamReader;\n");
286 out.push_str("import java.nio.charset.StandardCharsets;\n");
287 out.push_str("import java.nio.file.Path;\n");
288 out.push_str("import java.nio.file.Paths;\n");
289 out.push_str("import java.util.regex.Matcher;\n");
290 out.push_str("import java.util.regex.Pattern;\n");
291 out.push_str("import org.junit.platform.launcher.LauncherSession;\n");
292 out.push_str("import org.junit.platform.launcher.LauncherSessionListener;\n");
293 out.push('\n');
294 out.push_str("/**\n");
295 out.push_str(" * Spawns the mock-server binary once per JUnit launcher session and\n");
296 out.push_str(" * exposes its URL as the `mockServerUrl` system property. Generated\n");
297 out.push_str(" * test bodies read the property (with `MOCK_SERVER_URL` env-var\n");
298 out.push_str(" * fallback) so tests can run via plain `mvn test` without any external\n");
299 out.push_str(" * mock-server orchestration. Mirrors the Ruby spec_helper / Python\n");
300 out.push_str(" * conftest spawn pattern. Honors a pre-set MOCK_SERVER_URL by\n");
301 out.push_str(" * skipping the spawn entirely.\n");
302 out.push_str(" */\n");
303 out.push_str("public class MockServerListener implements LauncherSessionListener {\n");
304 out.push_str(" private Process mockServer;\n");
305 out.push('\n');
306 out.push_str(" @Override\n");
307 out.push_str(" public void launcherSessionOpened(LauncherSession session) {\n");
308 out.push_str(" String preset = System.getenv(\"MOCK_SERVER_URL\");\n");
309 out.push_str(" if (preset != null && !preset.isEmpty()) {\n");
310 out.push_str(" System.setProperty(\"mockServerUrl\", preset);\n");
311 out.push_str(" return;\n");
312 out.push_str(" }\n");
313 out.push_str(" Path repoRoot = locateRepoRoot();\n");
314 out.push_str(" if (repoRoot == null) {\n");
315 out.push_str(" throw new IllegalStateException(\"MockServerListener: could not locate repo root (looked for fixtures/ in ancestors of \" + System.getProperty(\"user.dir\") + \")\");\n");
316 out.push_str(" }\n");
317 out.push_str(" String binName = System.getProperty(\"os.name\", \"\").toLowerCase().contains(\"win\") ? \"mock-server.exe\" : \"mock-server\";\n");
318 out.push_str(" File bin = repoRoot.resolve(\"e2e\").resolve(\"rust\").resolve(\"target\").resolve(\"release\").resolve(binName).toFile();\n");
319 out.push_str(" File fixturesDir = repoRoot.resolve(\"fixtures\").toFile();\n");
320 out.push_str(" if (!bin.exists()) {\n");
321 out.push_str(" throw new IllegalStateException(\"MockServerListener: mock-server binary not found at \" + bin + \" — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release\");\n");
322 out.push_str(" }\n");
323 out.push_str(
324 " ProcessBuilder pb = new ProcessBuilder(bin.getAbsolutePath(), fixturesDir.getAbsolutePath())\n",
325 );
326 out.push_str(" .redirectErrorStream(false);\n");
327 out.push_str(" try {\n");
328 out.push_str(" mockServer = pb.start();\n");
329 out.push_str(" } catch (IOException e) {\n");
330 out.push_str(
331 " throw new IllegalStateException(\"MockServerListener: failed to start mock-server\", e);\n",
332 );
333 out.push_str(" }\n");
334 out.push_str(" // Read until we see MOCK_SERVER_URL= and optionally MOCK_SERVERS=.\n");
335 out.push_str(" // Cap the loop so a misbehaving mock-server cannot block indefinitely.\n");
336 out.push_str(" BufferedReader stdout = new BufferedReader(new InputStreamReader(mockServer.getInputStream(), StandardCharsets.UTF_8));\n");
337 out.push_str(" String url = null;\n");
338 out.push_str(" try {\n");
339 out.push_str(" for (int i = 0; i < 16; i++) {\n");
340 out.push_str(" String line = stdout.readLine();\n");
341 out.push_str(" if (line == null) break;\n");
342 out.push_str(" if (line.startsWith(\"MOCK_SERVER_URL=\")) {\n");
343 out.push_str(" url = line.substring(\"MOCK_SERVER_URL=\".length()).trim();\n");
344 out.push_str(" } else if (line.startsWith(\"MOCK_SERVERS=\")) {\n");
345 out.push_str(" String jsonVal = line.substring(\"MOCK_SERVERS=\".length()).trim();\n");
346 out.push_str(" System.setProperty(\"mockServers\", jsonVal);\n");
347 out.push_str(" // Parse JSON map of fixture_id -> url and expose as system properties.\n");
348 out.push_str(" Pattern p = Pattern.compile(\"\\\"([^\\\"]+)\\\":\\\"([^\\\"]+)\\\"\");\n");
349 out.push_str(" Matcher matcher = p.matcher(jsonVal);\n");
350 out.push_str(" while (matcher.find()) {\n");
351 out.push_str(" String fid = matcher.group(1);\n");
352 out.push_str(" String furl = matcher.group(2);\n");
353 out.push_str(" System.setProperty(\"mockServer.\" + fid, furl);\n");
354 out.push_str(" }\n");
355 out.push_str(" break;\n");
356 out.push_str(" } else if (url != null) {\n");
357 out.push_str(" break;\n");
358 out.push_str(" }\n");
359 out.push_str(" }\n");
360 out.push_str(" } catch (IOException e) {\n");
361 out.push_str(" mockServer.destroyForcibly();\n");
362 out.push_str(
363 " throw new IllegalStateException(\"MockServerListener: failed to read mock-server stdout\", e);\n",
364 );
365 out.push_str(" }\n");
366 out.push_str(" if (url == null || url.isEmpty()) {\n");
367 out.push_str(" mockServer.destroyForcibly();\n");
368 out.push_str(" throw new IllegalStateException(\"MockServerListener: mock-server did not emit MOCK_SERVER_URL\");\n");
369 out.push_str(" }\n");
370 out.push_str(" // TCP-readiness probe: ensure axum::serve is accepting before tests start.\n");
371 out.push_str(" // The mock-server binds the TcpListener synchronously then prints the URL\n");
372 out.push_str(" // before tokio::spawn(axum::serve(...)) is polled, so under Surefire\n");
373 out.push_str(" // parallel mode tests can race startup. Poll-connect (max 5s, 50ms backoff)\n");
374 out.push_str(" // until success.\n");
375 out.push_str(" java.net.URI healthUri = java.net.URI.create(url);\n");
376 out.push_str(" String host = healthUri.getHost();\n");
377 out.push_str(" int port = healthUri.getPort();\n");
378 out.push_str(" long deadline = System.nanoTime() + 5_000_000_000L;\n");
379 out.push_str(" while (System.nanoTime() < deadline) {\n");
380 out.push_str(" try (java.net.Socket s = new java.net.Socket()) {\n");
381 out.push_str(" s.connect(new java.net.InetSocketAddress(host, port), 100);\n");
382 out.push_str(" break;\n");
383 out.push_str(" } catch (java.io.IOException ignored) {\n");
384 out.push_str(" try { Thread.sleep(50); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); break; }\n");
385 out.push_str(" }\n");
386 out.push_str(" }\n");
387 out.push_str(" System.setProperty(\"mockServerUrl\", url);\n");
388 out.push_str(" // Drain remaining stdout/stderr in daemon threads so a full pipe\n");
389 out.push_str(" // does not block the child.\n");
390 out.push_str(" Process server = mockServer;\n");
391 out.push_str(" Thread drainOut = new Thread(() -> drain(stdout));\n");
392 out.push_str(" drainOut.setDaemon(true);\n");
393 out.push_str(" drainOut.start();\n");
394 out.push_str(" Thread drainErr = new Thread(() -> drain(new BufferedReader(new InputStreamReader(server.getErrorStream(), StandardCharsets.UTF_8))));\n");
395 out.push_str(" drainErr.setDaemon(true);\n");
396 out.push_str(" drainErr.start();\n");
397 out.push_str(" }\n");
398 out.push('\n');
399 out.push_str(" @Override\n");
400 out.push_str(" public void launcherSessionClosed(LauncherSession session) {\n");
401 out.push_str(" if (mockServer == null) return;\n");
402 out.push_str(" try { mockServer.getOutputStream().close(); } catch (IOException ignored) {}\n");
403 out.push_str(" try {\n");
404 out.push_str(" if (!mockServer.waitFor(2, java.util.concurrent.TimeUnit.SECONDS)) {\n");
405 out.push_str(" mockServer.destroyForcibly();\n");
406 out.push_str(" }\n");
407 out.push_str(" } catch (InterruptedException ignored) {\n");
408 out.push_str(" Thread.currentThread().interrupt();\n");
409 out.push_str(" mockServer.destroyForcibly();\n");
410 out.push_str(" }\n");
411 out.push_str(" }\n");
412 out.push('\n');
413 out.push_str(" private static Path locateRepoRoot() {\n");
414 out.push_str(" Path dir = Paths.get(\"\").toAbsolutePath();\n");
415 out.push_str(" while (dir != null) {\n");
416 out.push_str(" if (dir.resolve(\"fixtures\").toFile().isDirectory()\n");
417 out.push_str(" && dir.resolve(\"e2e\").toFile().isDirectory()) {\n");
418 out.push_str(" return dir;\n");
419 out.push_str(" }\n");
420 out.push_str(" dir = dir.getParent();\n");
421 out.push_str(" }\n");
422 out.push_str(" return null;\n");
423 out.push_str(" }\n");
424 out.push('\n');
425 out.push_str(" private static void drain(BufferedReader reader) {\n");
426 out.push_str(" try {\n");
427 out.push_str(" char[] buf = new char[1024];\n");
428 out.push_str(" while (reader.read(buf) >= 0) { /* drain */ }\n");
429 out.push_str(" } catch (IOException ignored) {}\n");
430 out.push_str(" }\n");
431 out.push_str("}\n");
432 out
433}
434
435fn render_sealed_display(
448 type_name: &str,
449 enum_def: &alef_core::ir::EnumDef,
450 type_defs: &[alef_core::ir::TypeDef],
451 java_group_id: &str,
452) -> String {
453 let helper_class = format!("{type_name}Display");
454 let header = hash::header(CommentStyle::DoubleSlash);
455 let mut out = header;
456 out.push_str(&format!("package {java_group_id}.e2e;\n\n"));
457 out.push_str(&format!("import {java_group_id}.{type_name};\n"));
458 out.push('\n');
459 out.push_str(&format!(
460 "/**\n * Helper class for extracting display strings from {type_name} sealed interface.\n */\n"
461 ));
462 out.push_str(&format!("class {helper_class} {{\n"));
463 out.push_str(&format!(" static String toDisplayString({type_name} value) {{\n"));
464 out.push_str(" if (value == null) return \"\";\n");
465 out.push_str(" return switch (value) {\n");
466
467 for variant in &enum_def.variants {
468 let variant_name = &variant.name;
469 let has_format_field = variant.is_tuple && variant.fields.len() == 1 && {
474 let field_type_name = match &variant.fields[0].ty {
475 alef_core::ir::TypeRef::Named(n) => Some(n.as_str()),
476 _ => None,
477 };
478 field_type_name.is_some_and(|tn| {
479 type_defs
480 .iter()
481 .find(|td| td.name == tn)
482 .is_some_and(|td| td.fields.iter().any(|f| f.name == "format"))
483 })
484 };
485
486 let display = if has_format_field {
487 "i.value().format()".to_string()
488 } else {
489 let serde_name = variant
491 .serde_rename
492 .as_deref()
493 .unwrap_or(variant_name.as_str())
494 .to_lowercase();
495 format!("\"{serde_name}\"")
496 };
497
498 let binding = if has_format_field {
499 format!("{type_name}.{variant_name} i")
500 } else {
501 format!("{type_name}.{variant_name} _")
502 };
503
504 out.push_str(&format!(" case {binding} -> {display};\n"));
505 }
506
507 out.push_str(" default -> \"unknown\";\n");
508 out.push_str(" };\n");
509 out.push_str(" }\n");
510 out.push_str("}\n");
511 out
512}
513
514#[allow(clippy::too_many_arguments)]
515fn render_test_file(
516 category: &str,
517 fixtures: &[&Fixture],
518 class_name: &str,
519 function_name: &str,
520 java_group_id: &str,
521 binding_pkg: &str,
522 result_var: &str,
523 args: &[crate::config::ArgMapping],
524 options_type: Option<&str>,
525 result_is_simple: bool,
526 e2e_config: &E2eConfig,
527 nested_types: &std::collections::HashMap<String, String>,
528 nested_types_optional: bool,
529 adapters: &[alef_core::config::extras::AdapterConfig],
530) -> String {
531 let header = hash::header(CommentStyle::DoubleSlash);
532 let test_class_name = format!("{}Test", sanitize_filename(category).to_upper_camel_case());
533
534 let (import_path, simple_class) = if class_name.contains('.') {
537 let simple = class_name.rsplit('.').next().unwrap_or(class_name);
538 (class_name, simple)
539 } else {
540 ("", class_name)
541 };
542
543 let lang_for_om = "java";
545 let needs_object_mapper_for_handle = fixtures.iter().any(|f| {
546 args.iter().filter(|a| a.arg_type == "handle").any(|a| {
547 let v = f.input.get(&a.field).unwrap_or(&serde_json::Value::Null);
548 !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
549 })
550 });
551 let has_http_fixtures = fixtures.iter().any(|f| f.http.is_some());
553 let needs_object_mapper = needs_object_mapper_for_handle || has_http_fixtures;
554
555 let mut all_options_types: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
557 if let Some(t) = options_type {
558 all_options_types.insert(t.to_string());
559 }
560 for f in fixtures.iter() {
561 let call_cfg =
562 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
563 if let Some(ov) = call_cfg.overrides.get(lang_for_om) {
564 if let Some(t) = &ov.options_type {
565 all_options_types.insert(t.clone());
566 }
567 }
568 let java_has_type = call_cfg
574 .overrides
575 .get(lang_for_om)
576 .and_then(|o| o.options_type.as_deref())
577 .is_some();
578 if !java_has_type {
579 for cand in ["csharp", "c", "go", "php", "python"] {
580 if let Some(o) = call_cfg.overrides.get(cand) {
581 if let Some(t) = &o.options_type {
582 all_options_types.insert(t.clone());
583 break;
584 }
585 }
586 }
587 }
588 for arg in &call_cfg.args {
591 if let Some(elem_type) = &arg.element_type {
592 if elem_type == "BatchBytesItem" || elem_type == "BatchFileItem" {
593 all_options_types.insert(elem_type.clone());
594 } else if arg.arg_type == "json_object"
595 && !is_numeric_type_hint(elem_type)
596 && !is_java_builtin_type(elem_type)
597 {
598 all_options_types.insert(elem_type.clone());
601 }
602 }
603 }
604 }
605
606 let mut nested_types_used: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
609 for f in fixtures.iter() {
610 let call_cfg =
611 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
612 for arg in &call_cfg.args {
613 if arg.arg_type == "json_object" {
614 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
615 if let Some(val) = f.input.get(field) {
616 if !val.is_null() && !val.is_array() {
617 if let Some(obj) = val.as_object() {
618 collect_nested_type_names(obj, nested_types, &mut nested_types_used);
619 }
620 }
621 }
622 }
623 }
624 }
625
626 let binding_pkg_for_imports: String = if !binding_pkg.is_empty() {
631 binding_pkg.to_string()
632 } else if !import_path.is_empty() {
633 import_path
634 .rsplit_once('.')
635 .map(|(p, _)| p.to_string())
636 .unwrap_or_default()
637 } else {
638 String::new()
639 };
640
641 let mut imports: Vec<String> = Vec::new();
643 imports.push("import org.junit.jupiter.api.Test;".to_string());
644 imports.push("import static org.junit.jupiter.api.Assertions.*;".to_string());
645
646 if !import_path.is_empty() {
649 imports.push(format!("import {import_path};"));
650 } else if !binding_pkg_for_imports.is_empty() && !class_name.is_empty() {
651 imports.push(format!("import {binding_pkg_for_imports}.{class_name};"));
652 }
653
654 if needs_object_mapper {
655 imports.push("import com.fasterxml.jackson.databind.ObjectMapper;".to_string());
656 imports.push("import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;".to_string());
657 }
658
659 if !all_options_types.is_empty() {
661 for opts_type in &all_options_types {
662 let qualified = if binding_pkg_for_imports.is_empty() {
663 opts_type.clone()
664 } else {
665 format!("{binding_pkg_for_imports}.{opts_type}")
666 };
667 imports.push(format!("import {qualified};"));
668 }
669 }
670
671 if !nested_types_used.is_empty() && !binding_pkg_for_imports.is_empty() {
673 for type_name in &nested_types_used {
674 imports.push(format!("import {binding_pkg_for_imports}.{type_name};"));
675 }
676 }
677
678 if needs_object_mapper_for_handle && !binding_pkg_for_imports.is_empty() {
680 imports.push(format!("import {binding_pkg_for_imports}.CrawlConfig;"));
681 }
682
683 let has_visitor_fixtures = fixtures.iter().any(|f| f.visitor.is_some());
685 if has_visitor_fixtures && !binding_pkg_for_imports.is_empty() {
686 imports.push(format!("import {binding_pkg_for_imports}.Visitor;"));
687 imports.push(format!("import {binding_pkg_for_imports}.NodeContext;"));
688 imports.push(format!("import {binding_pkg_for_imports}.VisitResult;"));
689 }
690
691 if !all_options_types.is_empty() {
695 imports.push("import java.util.Optional;".to_string());
696 if !binding_pkg_for_imports.is_empty() {
697 imports.push(format!("import {binding_pkg_for_imports}.JsonUtil;"));
698 }
699 }
700
701 let has_streaming_fixture = fixtures.iter().any(|f| {
712 let call_cfg =
713 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
714 crate::codegen::streaming_assertions::resolve_is_streaming(f, call_cfg.streaming)
715 });
716 if has_streaming_fixture && !binding_pkg_for_imports.is_empty() {
717 imports.push(format!("import {binding_pkg_for_imports}.ChatCompletionChunk;"));
718 let mut extra_streaming_imports: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
723 for adapter in adapters {
724 if !matches!(adapter.pattern, alef_core::config::extras::AdapterPattern::Streaming) {
725 continue;
726 }
727 if let Some(item) = adapter.item_type.as_deref() {
728 let simple = item.rsplit("::").next().unwrap_or(item);
729 if simple != "ChatCompletionChunk" && !simple.is_empty() {
730 extra_streaming_imports.insert(simple.to_string());
731 }
732 }
733 if let Some(req) = adapter.request_type.as_deref() {
734 let simple = req.rsplit("::").next().unwrap_or(req);
735 if !simple.is_empty() {
736 extra_streaming_imports.insert(simple.to_string());
737 }
738 }
739 }
740 for ty in extra_streaming_imports {
741 imports.push(format!("import {binding_pkg_for_imports}.{ty};"));
742 }
743 }
744
745 let mut fixtures_body = String::new();
747 for (i, fixture) in fixtures.iter().enumerate() {
748 render_test_method(
749 &mut fixtures_body,
750 fixture,
751 simple_class,
752 function_name,
753 result_var,
754 args,
755 options_type,
756 result_is_simple,
757 e2e_config,
758 nested_types,
759 nested_types_optional,
760 adapters,
761 );
762 if i + 1 < fixtures.len() {
763 fixtures_body.push('\n');
764 }
765 }
766
767 crate::template_env::render(
769 "java/test_file.jinja",
770 minijinja::context! {
771 header => header,
772 java_group_id => java_group_id,
773 test_class_name => test_class_name,
774 category => category,
775 imports => imports,
776 needs_object_mapper => needs_object_mapper,
777 fixtures_body => fixtures_body,
778 },
779 )
780}
781
782struct JavaTestClientRenderer;
790
791impl client::TestClientRenderer for JavaTestClientRenderer {
792 fn language_name(&self) -> &'static str {
793 "java"
794 }
795
796 fn sanitize_test_name(&self, id: &str) -> String {
800 id.to_upper_camel_case()
801 }
802
803 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
809 let escaped_reason = skip_reason.map(escape_java);
810 let rendered = crate::template_env::render(
811 "java/http_test_open.jinja",
812 minijinja::context! {
813 fn_name => fn_name,
814 description => description,
815 skip_reason => escaped_reason,
816 },
817 );
818 out.push_str(&rendered);
819 }
820
821 fn render_test_close(&self, out: &mut String) {
823 let rendered = crate::template_env::render("java/http_test_close.jinja", minijinja::context! {});
824 out.push_str(&rendered);
825 }
826
827 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
833 const JAVA_RESTRICTED_HEADERS: &[&str] = &["connection", "content-length", "expect", "host", "upgrade"];
835
836 let method = ctx.method.to_uppercase();
837
838 let path = if ctx.query_params.is_empty() {
840 ctx.path.to_string()
841 } else {
842 let pairs: Vec<String> = ctx
843 .query_params
844 .iter()
845 .map(|(k, v)| {
846 let val_str = match v {
847 serde_json::Value::String(s) => s.clone(),
848 other => other.to_string(),
849 };
850 format!("{}={}", k, escape_java(&val_str))
851 })
852 .collect();
853 format!("{}?{}", ctx.path, pairs.join("&"))
854 };
855
856 let body_publisher = if let Some(body) = ctx.body {
857 let json = serde_json::to_string(body).unwrap_or_default();
858 let escaped = escape_java(&json);
859 format!("java.net.http.HttpRequest.BodyPublishers.ofString(\"{escaped}\")")
860 } else {
861 "java.net.http.HttpRequest.BodyPublishers.noBody()".to_string()
862 };
863
864 let content_type = if ctx.body.is_some() {
866 let ct = ctx.content_type.unwrap_or("application/json");
867 if !ctx.headers.keys().any(|k| k.to_lowercase() == "content-type") {
869 Some(ct.to_string())
870 } else {
871 None
872 }
873 } else {
874 None
875 };
876
877 let mut headers_lines: Vec<String> = Vec::new();
879 for (name, value) in ctx.headers {
880 if JAVA_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
881 continue;
882 }
883 let escaped_name = escape_java(name);
884 let escaped_value = escape_java(value);
885 headers_lines.push(format!(
886 "builder = builder.header(\"{escaped_name}\", \"{escaped_value}\");"
887 ));
888 }
889
890 let cookies_line = if !ctx.cookies.is_empty() {
892 let cookie_str: Vec<String> = ctx.cookies.iter().map(|(k, v)| format!("{k}={v}")).collect();
893 let cookie_header = escape_java(&cookie_str.join("; "));
894 Some(format!("builder = builder.header(\"Cookie\", \"{cookie_header}\");"))
895 } else {
896 None
897 };
898
899 let rendered = crate::template_env::render(
900 "java/http_request.jinja",
901 minijinja::context! {
902 method => method,
903 path => path,
904 body_publisher => body_publisher,
905 content_type => content_type,
906 headers_lines => headers_lines,
907 cookies_line => cookies_line,
908 response_var => ctx.response_var,
909 },
910 );
911 out.push_str(&rendered);
912 }
913
914 fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
916 let rendered = crate::template_env::render(
917 "java/http_assertions.jinja",
918 minijinja::context! {
919 response_var => response_var,
920 status_code => status,
921 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
922 body_assertion => String::new(),
923 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
924 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
925 },
926 );
927 out.push_str(&rendered);
928 }
929
930 fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
934 let escaped_name = escape_java(name);
935 let assertion_code = match expected {
936 "<<present>>" => {
937 format!(
938 "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").isPresent(), \"header {escaped_name} should be present\");"
939 )
940 }
941 "<<absent>>" => {
942 format!(
943 "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").isEmpty(), \"header {escaped_name} should be absent\");"
944 )
945 }
946 "<<uuid>>" => {
947 format!(
948 "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").orElse(\"\").matches(\"[0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{12}}\"), \"header {escaped_name} should be a UUID\");"
949 )
950 }
951 literal => {
952 let escaped_value = escape_java(literal);
953 format!(
954 "assertTrue({response_var}.headers().firstValue(\"{escaped_name}\").orElse(\"\").contains(\"{escaped_value}\"), \"header {escaped_name} mismatch\");"
955 )
956 }
957 };
958
959 let mut headers = vec![std::collections::HashMap::new()];
960 headers[0].insert("assertion_code", assertion_code);
961
962 let rendered = crate::template_env::render(
963 "java/http_assertions.jinja",
964 minijinja::context! {
965 response_var => response_var,
966 status_code => 0u16,
967 headers => headers,
968 body_assertion => String::new(),
969 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
970 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
971 },
972 );
973 out.push_str(&rendered);
974 }
975
976 fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
978 let body_assertion = match expected {
979 serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
980 let json_str = serde_json::to_string(expected).unwrap_or_default();
981 let escaped = escape_java(&json_str);
982 format!(
983 "var bodyJson = MAPPER.readTree({response_var}.body());\n var expectedJson = MAPPER.readTree(\"{escaped}\");\n assertEquals(expectedJson, bodyJson, \"body mismatch\");"
984 )
985 }
986 serde_json::Value::String(s) => {
987 let escaped = escape_java(s);
988 format!("assertEquals(\"{escaped}\", {response_var}.body().trim(), \"body mismatch\");")
989 }
990 other => {
991 let escaped = escape_java(&other.to_string());
992 format!("assertEquals(\"{escaped}\", {response_var}.body().trim(), \"body mismatch\");")
993 }
994 };
995
996 let rendered = crate::template_env::render(
997 "java/http_assertions.jinja",
998 minijinja::context! {
999 response_var => response_var,
1000 status_code => 0u16,
1001 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
1002 body_assertion => body_assertion,
1003 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
1004 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
1005 },
1006 );
1007 out.push_str(&rendered);
1008 }
1009
1010 fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
1012 if let Some(obj) = expected.as_object() {
1013 let mut partial_body: Vec<std::collections::HashMap<&str, String>> = Vec::new();
1014 for (key, val) in obj {
1015 let escaped_key = escape_java(key);
1016 let json_str = serde_json::to_string(val).unwrap_or_default();
1017 let escaped_val = escape_java(&json_str);
1018 let assertion_code = format!(
1019 "assertEquals(MAPPER.readTree(\"{escaped_val}\"), partialJson.get(\"{escaped_key}\"), \"body field '{escaped_key}' mismatch\");"
1020 );
1021 let mut entry = std::collections::HashMap::new();
1022 entry.insert("assertion_code", assertion_code);
1023 partial_body.push(entry);
1024 }
1025
1026 let rendered = crate::template_env::render(
1027 "java/http_assertions.jinja",
1028 minijinja::context! {
1029 response_var => response_var,
1030 status_code => 0u16,
1031 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
1032 body_assertion => String::new(),
1033 partial_body => partial_body,
1034 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
1035 },
1036 );
1037 out.push_str(&rendered);
1038 }
1039 }
1040
1041 fn render_assert_validation_errors(
1043 &self,
1044 out: &mut String,
1045 response_var: &str,
1046 errors: &[crate::fixture::ValidationErrorExpectation],
1047 ) {
1048 let mut validation_errors: Vec<std::collections::HashMap<&str, String>> = Vec::new();
1049 for err in errors {
1050 let escaped_msg = escape_java(&err.msg);
1051 let assertion_code = format!(
1052 "assertTrue(veBody.contains(\"{escaped_msg}\"), \"expected validation error message: {escaped_msg}\");"
1053 );
1054 let mut entry = std::collections::HashMap::new();
1055 entry.insert("assertion_code", assertion_code);
1056 validation_errors.push(entry);
1057 }
1058
1059 let rendered = crate::template_env::render(
1060 "java/http_assertions.jinja",
1061 minijinja::context! {
1062 response_var => response_var,
1063 status_code => 0u16,
1064 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
1065 body_assertion => String::new(),
1066 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
1067 validation_errors => validation_errors,
1068 },
1069 );
1070 out.push_str(&rendered);
1071 }
1072}
1073
1074fn render_http_test_method(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
1081 if http.expected_response.status_code == 101 {
1084 let method_name = fixture.id.to_upper_camel_case();
1085 let description = &fixture.description;
1086 out.push_str(&crate::template_env::render(
1087 "java/http_test_skip_101.jinja",
1088 minijinja::context! {
1089 method_name => method_name,
1090 description => description,
1091 },
1092 ));
1093 return;
1094 }
1095
1096 client::http_call::render_http_test(out, &JavaTestClientRenderer, fixture);
1097}
1098
1099#[allow(clippy::too_many_arguments)]
1100fn render_test_method(
1101 out: &mut String,
1102 fixture: &Fixture,
1103 class_name: &str,
1104 _function_name: &str,
1105 _result_var: &str,
1106 _args: &[crate::config::ArgMapping],
1107 options_type: Option<&str>,
1108 result_is_simple: bool,
1109 e2e_config: &E2eConfig,
1110 nested_types: &std::collections::HashMap<String, String>,
1111 nested_types_optional: bool,
1112 adapters: &[alef_core::config::extras::AdapterConfig],
1113) {
1114 if let Some(http) = &fixture.http {
1116 render_http_test_method(out, fixture, http);
1117 return;
1118 }
1119
1120 let call_config = e2e_config.resolve_call_for_fixture(
1123 fixture.call.as_deref(),
1124 &fixture.id,
1125 &fixture.resolved_category(),
1126 &fixture.tags,
1127 &fixture.input,
1128 );
1129 let call_field_resolver = FieldResolver::new(
1132 e2e_config.effective_fields(call_config),
1133 e2e_config.effective_fields_optional(call_config),
1134 e2e_config.effective_result_fields(call_config),
1135 e2e_config.effective_fields_array(call_config),
1136 &std::collections::HashSet::new(),
1137 );
1138 let field_resolver = &call_field_resolver;
1139 let effective_enum_fields = e2e_config.effective_fields_enum(call_config);
1140 let enum_fields = effective_enum_fields;
1141 let lang = "java";
1142 let call_overrides = call_config.overrides.get(lang);
1143 let effective_function_name = call_overrides
1144 .and_then(|o| o.function.as_ref())
1145 .cloned()
1146 .unwrap_or_else(|| call_config.function.to_lower_camel_case());
1147 let effective_result_var = &call_config.result_var;
1148 let effective_args = &call_config.args;
1149 let function_name = effective_function_name.as_str();
1150 let result_var = effective_result_var.as_str();
1151 let args: &[crate::config::ArgMapping] = effective_args.as_slice();
1152
1153 let method_name = fixture.id.to_upper_camel_case();
1154 let description = &fixture.description;
1155 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
1156
1157 let effective_options_type: Option<String> = call_overrides
1163 .and_then(|o| o.options_type.clone())
1164 .or_else(|| options_type.map(|s| s.to_string()))
1165 .or_else(|| {
1166 for cand in ["csharp", "c", "go", "php", "python"] {
1170 if let Some(o) = call_config.overrides.get(cand) {
1171 if let Some(t) = &o.options_type {
1172 return Some(t.clone());
1173 }
1174 }
1175 }
1176 None
1177 });
1178 let effective_options_type = effective_options_type.as_deref();
1179 let auto_from_json = effective_options_type.is_some()
1184 && call_overrides.and_then(|o| o.options_via.as_deref()).is_none()
1185 && e2e_config
1186 .call
1187 .overrides
1188 .get(lang)
1189 .and_then(|o| o.options_via.as_deref())
1190 .is_none();
1191
1192 let client_factory: Option<String> = call_overrides.and_then(|o| o.client_factory.clone()).or_else(|| {
1194 e2e_config
1195 .call
1196 .overrides
1197 .get(lang)
1198 .and_then(|o| o.client_factory.clone())
1199 });
1200
1201 let options_via: String = call_overrides
1206 .and_then(|o| o.options_via.clone())
1207 .or_else(|| e2e_config.call.overrides.get(lang).and_then(|o| o.options_via.clone()))
1208 .unwrap_or_else(|| {
1209 if auto_from_json {
1210 "from_json".to_string()
1211 } else {
1212 "kwargs".to_string()
1213 }
1214 });
1215
1216 let effective_result_is_simple =
1218 call_overrides.is_some_and(|o| o.result_is_simple) || call_config.result_is_simple || result_is_simple;
1219 let effective_result_is_bytes = call_overrides.is_some_and(|o| o.result_is_bytes);
1220 let effective_result_is_option = call_overrides.is_some_and(|o| o.result_is_option) || call_config.result_is_option;
1226
1227 let needs_deser = effective_options_type.is_some()
1229 && args.iter().any(|arg| {
1230 if arg.arg_type != "json_object" {
1231 return false;
1232 }
1233 let val = super::resolve_field(&fixture.input, &arg.field);
1234 !val.is_null() && !val.is_array()
1235 });
1236
1237 let mut builder_expressions = String::new();
1239 if let (true, Some(opts_type)) = (needs_deser, effective_options_type) {
1240 for arg in args {
1241 if arg.arg_type == "json_object" {
1242 let val = super::resolve_field(&fixture.input, &arg.field);
1243 if !val.is_null() && !val.is_array() {
1244 if options_via == "from_json" {
1245 let normalized = super::transform_json_keys_for_language(val, "snake_case");
1250 let json_str = serde_json::to_string(&normalized).unwrap_or_default();
1251 let escaped = escape_java(&json_str);
1252 let var_name = &arg.name;
1253 builder_expressions.push_str(&format!(
1254 " var {var_name} = JsonUtil.fromJson(\"{escaped}\", {opts_type}.class);\n",
1255 ));
1256 } else if let Some(obj) = val.as_object() {
1257 let empty_path_fields: Vec<String> = Vec::new();
1259 let path_fields = call_overrides.map(|o| &o.path_fields).unwrap_or(&empty_path_fields);
1260 let builder_expr = java_builder_expression(
1261 obj,
1262 opts_type,
1263 enum_fields,
1264 nested_types,
1265 nested_types_optional,
1266 path_fields,
1267 );
1268 let var_name = &arg.name;
1269 builder_expressions.push_str(&format!(" var {} = {};\n", var_name, builder_expr));
1270 }
1271 }
1272 }
1273 }
1274 }
1275
1276 let adapter_request_type: Option<String> = adapters
1277 .iter()
1278 .find(|a| a.name == call_config.function.as_str())
1279 .and_then(|a| a.request_type.as_deref())
1280 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
1281 let (mut setup_lines, args_str) = build_args_and_setup(
1282 &fixture.input,
1283 args,
1284 class_name,
1285 effective_options_type,
1286 fixture,
1287 adapter_request_type.as_deref(),
1288 );
1289
1290 let extra_args_slice: &[String] = call_overrides.map_or(&[], |o| o.extra_args.as_slice());
1295
1296 let mut visitor_var = String::new();
1298 let mut has_visitor_fixture = false;
1299 if let Some(visitor_spec) = &fixture.visitor {
1300 visitor_var = build_java_visitor(&mut setup_lines, visitor_spec, class_name);
1301 has_visitor_fixture = true;
1302 }
1303
1304 let mut final_args = if has_visitor_fixture {
1306 if args_str.is_empty() {
1307 format!("new ConversionOptions().withVisitor({})", visitor_var)
1308 } else if args_str.contains("new ConversionOptions")
1309 || args_str.contains("ConversionOptionsBuilder")
1310 || args_str.contains(".builder()")
1311 {
1312 if args_str.contains(".build()") {
1315 let idx = args_str.rfind(".build()").unwrap();
1316 format!("{}.withVisitor({}){}", &args_str[..idx], visitor_var, &args_str[idx..])
1317 } else {
1318 format!("{}.withVisitor({})", args_str, visitor_var)
1319 }
1320 } else if args_str.ends_with(", null") {
1321 let base = &args_str[..args_str.len() - 6];
1322 format!("{}, new ConversionOptions().withVisitor({})", base, visitor_var)
1323 } else {
1324 format!("{}, new ConversionOptions().withVisitor({})", args_str, visitor_var)
1325 }
1326 } else {
1327 args_str
1328 };
1329
1330 if !extra_args_slice.is_empty() {
1331 let extra_str = extra_args_slice.join(", ");
1332 final_args = if final_args.is_empty() {
1333 extra_str
1334 } else {
1335 format!("{final_args}, {extra_str}")
1336 };
1337 }
1338
1339 let mut assertions_body = String::new();
1341
1342 let needs_source_var = fixture
1344 .assertions
1345 .iter()
1346 .any(|a| a.assertion_type == "method_result" && a.method.as_deref() == Some("run_query"));
1347 if needs_source_var {
1348 if let Some(source_arg) = args.iter().find(|a| a.field == "source_code") {
1349 let field = source_arg.field.strip_prefix("input.").unwrap_or(&source_arg.field);
1350 if let Some(val) = fixture.input.get(field) {
1351 let java_val = json_to_java(val);
1352 assertions_body.push_str(&format!(" var source = {}.getBytes();\n", java_val));
1353 }
1354 }
1355 }
1356
1357 let assert_enum_types: std::collections::HashMap<String, String> = if let Some(co) = call_overrides {
1364 co.assert_enum_fields.clone()
1365 } else {
1366 std::collections::HashMap::new()
1367 };
1368
1369 let mut effective_enum_fields: std::collections::HashSet<String> = enum_fields.clone();
1371 if let Some(co) = call_overrides {
1372 for k in co.enum_fields.keys() {
1373 effective_enum_fields.insert(k.clone());
1374 }
1375 }
1376
1377 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
1382
1383 for assertion in &fixture.assertions {
1384 render_assertion(
1385 &mut assertions_body,
1386 assertion,
1387 result_var,
1388 class_name,
1389 field_resolver,
1390 effective_result_is_simple,
1391 effective_result_is_bytes,
1392 effective_result_is_option,
1393 is_streaming,
1394 &effective_enum_fields,
1395 &assert_enum_types,
1396 );
1397 }
1398
1399 let throws_clause = " throws Exception";
1400
1401 let (client_setup_lines, call_target) = if let Some(factory) = client_factory.as_deref() {
1404 let factory_name = factory.to_lower_camel_case();
1405 let fixture_id = &fixture.id;
1406 let mut setup: Vec<String> = Vec::new();
1407 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1408 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1409 if let Some(var) = api_key_var.filter(|_| has_mock) {
1410 setup.push(format!("String apiKey = System.getenv(\"{var}\");"));
1411 setup.push(format!(
1412 "String baseUrl = (apiKey != null && !apiKey.isEmpty()) ? null : System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\";"
1413 ));
1414 setup.push(format!(
1415 "System.out.println(\"{fixture_id}: \" + (baseUrl == null ? \"using real API ({var} is set)\" : \"using mock server ({var} not set)\"));"
1416 ));
1417 setup.push(format!(
1418 "var client = {class_name}.{factory_name}(baseUrl == null ? apiKey : \"test-key\", baseUrl, null, null, null);"
1419 ));
1420 } else if has_mock {
1421 if fixture.has_host_root_route() {
1422 setup.push(format!(
1423 "String mockUrl = System.getProperty(\"mockServer.{fixture_id}\", System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\");"
1424 ));
1425 } else {
1426 setup.push(format!(
1427 "String mockUrl = System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\";"
1428 ));
1429 }
1430 setup.push(format!(
1431 "var client = {class_name}.{factory_name}(\"test-key\", mockUrl, null, null, null);"
1432 ));
1433 } else if let Some(api_key_var) = api_key_var {
1434 setup.push(format!("String apiKey = System.getenv(\"{api_key_var}\");"));
1435 setup.push(format!(
1436 "org.junit.jupiter.api.Assumptions.assumeTrue(apiKey != null && !apiKey.isEmpty(), \"{api_key_var} not set\");"
1437 ));
1438 setup.push(format!("var client = {class_name}.{factory_name}(apiKey);"));
1439 } else {
1440 setup.push(format!("var client = {class_name}.{factory_name}(\"test-key\");"));
1441 }
1442 (setup, "client".to_string())
1443 } else {
1444 (Vec::new(), class_name.to_string())
1445 };
1446
1447 let combined_setup: Vec<String> = client_setup_lines.into_iter().chain(setup_lines).collect();
1449
1450 let call_expr = format!("{call_target}.{function_name}({final_args})");
1451
1452 let collect_snippet = if is_streaming && !expects_error {
1454 crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("java", result_var, "chunks")
1455 .unwrap_or_default()
1456 } else {
1457 String::new()
1458 };
1459
1460 let rendered = crate::template_env::render(
1461 "java/test_method.jinja",
1462 minijinja::context! {
1463 method_name => method_name,
1464 description => description,
1465 builder_expressions => builder_expressions,
1466 setup_lines => combined_setup,
1467 throws_clause => throws_clause,
1468 expects_error => expects_error,
1469 call_expr => call_expr,
1470 result_var => result_var,
1471 returns_void => call_config.returns_void,
1472 collect_snippet => collect_snippet,
1473 assertions_body => assertions_body,
1474 },
1475 );
1476 out.push_str(&rendered);
1477}
1478
1479fn build_args_and_setup(
1483 input: &serde_json::Value,
1484 args: &[crate::config::ArgMapping],
1485 class_name: &str,
1486 options_type: Option<&str>,
1487 fixture: &crate::fixture::Fixture,
1488 adapter_request_type: Option<&str>,
1489) -> (Vec<String>, String) {
1490 let fixture_id = &fixture.id;
1491 if args.is_empty() {
1492 return (Vec::new(), String::new());
1493 }
1494
1495 let mut setup_lines: Vec<String> = Vec::new();
1496 let mut parts: Vec<String> = Vec::new();
1497
1498 for arg in args {
1499 if arg.arg_type == "mock_url" {
1500 if fixture.has_host_root_route() {
1501 setup_lines.push(format!(
1502 "String {} = System.getProperty(\"mockServer.{fixture_id}\", System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\");",
1503 arg.name,
1504 ));
1505 } else {
1506 setup_lines.push(format!(
1507 "String {} = System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\")) + \"/fixtures/{fixture_id}\";",
1508 arg.name,
1509 ));
1510 }
1511 if let Some(req_type) = adapter_request_type {
1512 let req_var = format!("{}Req", arg.name);
1513 setup_lines.push(format!("var {req_var} = new {req_type}({});", arg.name));
1514 parts.push(req_var);
1515 } else {
1516 parts.push(arg.name.clone());
1517 }
1518 continue;
1519 }
1520
1521 if arg.arg_type == "mock_url_list" {
1522 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1528 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1529 let val = input.get(field).unwrap_or(&serde_json::Value::Null);
1530 let paths: Vec<String> = if let Some(arr) = val.as_array() {
1531 arr.iter()
1532 .filter_map(|v| v.as_str().map(|s| format!("\"{}\"", escape_java(s))))
1533 .collect()
1534 } else {
1535 Vec::new()
1536 };
1537 let paths_literal = paths.join(", ");
1538 let name = &arg.name;
1539 setup_lines.push(format!(
1540 "String {name}Base = System.getenv().getOrDefault(\"{env_key}\", System.getenv(\"MOCK_SERVER_URL\") + \"/fixtures/{fixture_id}\");"
1541 ));
1542 setup_lines.push(format!(
1543 "java.util.List<String> {name} = java.util.Arrays.stream(new String[]{{{paths_literal}}}).map(p -> p.startsWith(\"http\") ? p : {name}Base + p).collect(java.util.stream.Collectors.toList());"
1544 ));
1545 parts.push(name.clone());
1546 continue;
1547 }
1548
1549 if arg.arg_type == "handle" {
1550 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1552 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1553 let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
1554 if config_value.is_null()
1555 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1556 {
1557 setup_lines.push(format!("var {} = {class_name}.{constructor_name}(null);", arg.name,));
1558 } else {
1559 let json_str = serde_json::to_string(config_value).unwrap_or_default();
1560 let name = &arg.name;
1561 setup_lines.push(format!(
1562 "var {name}Config = MAPPER.readValue(\"{}\", CrawlConfig.class);",
1563 escape_java(&json_str),
1564 ));
1565 setup_lines.push(format!(
1566 "var {} = {class_name}.{constructor_name}({name}Config);",
1567 arg.name,
1568 name = name,
1569 ));
1570 }
1571 parts.push(arg.name.clone());
1572 continue;
1573 }
1574
1575 let resolved = super::resolve_field(input, &arg.field);
1576 let val = if resolved.is_null() { None } else { Some(resolved) };
1577 match val {
1578 None | Some(serde_json::Value::Null) if arg.optional => {
1579 if arg.arg_type == "json_object" {
1583 if let Some(opts_type) = options_type {
1584 parts.push(format!("{opts_type}.builder().build()"));
1585 } else {
1586 parts.push("null".to_string());
1587 }
1588 } else {
1589 parts.push("null".to_string());
1590 }
1591 }
1592 None | Some(serde_json::Value::Null) => {
1593 let default_val = match arg.arg_type.as_str() {
1595 "string" | "file_path" => "\"\"".to_string(),
1596 "int" | "integer" => "0".to_string(),
1597 "float" | "number" => "0.0d".to_string(),
1598 "bool" | "boolean" => "false".to_string(),
1599 _ => "null".to_string(),
1600 };
1601 parts.push(default_val);
1602 }
1603 Some(v) => {
1604 if arg.arg_type == "json_object" {
1605 if v.is_array() {
1608 if let Some(elem_type) = &arg.element_type {
1609 if elem_type == "BatchBytesItem" || elem_type == "BatchFileItem" {
1610 parts.push(emit_java_batch_item_array(v, elem_type));
1611 continue;
1612 }
1613 if !is_numeric_type_hint(elem_type) {
1615 parts.push(emit_java_object_array(v, elem_type));
1616 continue;
1617 }
1618 }
1619 let elem_type = arg.element_type.as_deref();
1621 parts.push(json_to_java_typed(v, elem_type));
1622 continue;
1623 }
1624 if options_type.is_some() {
1626 parts.push(arg.name.clone());
1627 continue;
1628 }
1629 parts.push(json_to_java(v));
1630 continue;
1631 }
1632 if arg.arg_type == "bytes" {
1636 let val = json_to_java(v);
1637 parts.push(format!(
1638 "java.nio.file.Files.readAllBytes(java.nio.file.Path.of({val}))"
1639 ));
1640 continue;
1641 }
1642 if arg.arg_type == "file_path" {
1644 let val = json_to_java(v);
1645 parts.push(format!("java.nio.file.Path.of({val})"));
1646 continue;
1647 }
1648 parts.push(json_to_java(v));
1649 }
1650 }
1651 }
1652
1653 (setup_lines, parts.join(", "))
1654}
1655
1656#[allow(clippy::too_many_arguments)]
1657fn render_assertion(
1658 out: &mut String,
1659 assertion: &Assertion,
1660 result_var: &str,
1661 class_name: &str,
1662 field_resolver: &FieldResolver,
1663 result_is_simple: bool,
1664 result_is_bytes: bool,
1665 result_is_option: bool,
1666 is_streaming: bool,
1667 enum_fields: &std::collections::HashSet<String>,
1668 assert_enum_types: &std::collections::HashMap<String, String>,
1669) {
1670 let bare_field = assertion.field.as_deref().is_none_or(str::is_empty);
1675 if result_is_option && bare_field {
1676 match assertion.assertion_type.as_str() {
1677 "is_empty" => {
1678 out.push_str(&format!(
1679 " assertNull({result_var}, \"expected empty value\");\n"
1680 ));
1681 return;
1682 }
1683 "not_empty" => {
1684 out.push_str(&format!(
1685 " assertNotNull({result_var}, \"expected non-empty value\");\n"
1686 ));
1687 return;
1688 }
1689 _ => {}
1690 }
1691 }
1692
1693 if result_is_bytes {
1698 match assertion.assertion_type.as_str() {
1699 "not_empty" => {
1700 out.push_str(&format!(
1701 " assertTrue({result_var}.length > 0, \"expected non-empty value\");\n"
1702 ));
1703 return;
1704 }
1705 "is_empty" => {
1706 out.push_str(&format!(
1707 " assertEquals(0, {result_var}.length, \"expected empty value\");\n"
1708 ));
1709 return;
1710 }
1711 "count_equals" | "length_equals" => {
1712 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1713 out.push_str(&format!(" assertEquals({n}, {result_var}.length);\n"));
1714 }
1715 return;
1716 }
1717 "count_min" | "length_min" => {
1718 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1719 out.push_str(&format!(
1720 " assertTrue({result_var}.length >= {n}, \"expected length >= {n}\");\n"
1721 ));
1722 }
1723 return;
1724 }
1725 "not_error" => {
1726 out.push_str(&format!(
1729 " assertNotNull({result_var}, \"expected non-null byte[] response\");\n"
1730 ));
1731 return;
1732 }
1733 _ => {
1734 out.push_str(&format!(
1735 " // skipped: assertion type '{}' not supported on byte[] result\n",
1736 assertion.assertion_type
1737 ));
1738 return;
1739 }
1740 }
1741 }
1742
1743 if let Some(f) = &assertion.field {
1745 match f.as_str() {
1746 "chunks_have_content" => {
1748 let pred = format!(
1749 "java.util.Optional.ofNullable({result_var}.chunks()).orElse(java.util.List.of()).stream().allMatch(c -> c.content() != null && !c.content().isBlank())"
1750 );
1751 out.push_str(&crate::template_env::render(
1752 "java/synthetic_assertion.jinja",
1753 minijinja::context! {
1754 assertion_kind => "chunks_content",
1755 assertion_type => assertion.assertion_type.as_str(),
1756 pred => pred,
1757 field_name => f,
1758 },
1759 ));
1760 return;
1761 }
1762 "chunks_have_heading_context" => {
1763 let pred = format!(
1764 "java.util.Optional.ofNullable({result_var}.chunks()).orElse(java.util.List.of()).stream().allMatch(c -> c.metadata().headingContext() != null)"
1765 );
1766 out.push_str(&crate::template_env::render(
1767 "java/synthetic_assertion.jinja",
1768 minijinja::context! {
1769 assertion_kind => "chunks_heading_context",
1770 assertion_type => assertion.assertion_type.as_str(),
1771 pred => pred,
1772 field_name => f,
1773 },
1774 ));
1775 return;
1776 }
1777 "chunks_have_embeddings" => {
1778 let pred = format!(
1779 "java.util.Optional.ofNullable({result_var}.chunks()).orElse(java.util.List.of()).stream().allMatch(c -> c.embedding() != null && !c.embedding().isEmpty())"
1780 );
1781 out.push_str(&crate::template_env::render(
1782 "java/synthetic_assertion.jinja",
1783 minijinja::context! {
1784 assertion_kind => "chunks_embeddings",
1785 assertion_type => assertion.assertion_type.as_str(),
1786 pred => pred,
1787 field_name => f,
1788 },
1789 ));
1790 return;
1791 }
1792 "first_chunk_starts_with_heading" => {
1793 let pred = format!(
1794 "java.util.Optional.ofNullable({result_var}.chunks()).orElse(java.util.List.of()).stream().findFirst().map(c -> c.metadata().headingContext() != null).orElse(false)"
1795 );
1796 out.push_str(&crate::template_env::render(
1797 "java/synthetic_assertion.jinja",
1798 minijinja::context! {
1799 assertion_kind => "first_chunk_heading",
1800 assertion_type => assertion.assertion_type.as_str(),
1801 pred => pred,
1802 field_name => f,
1803 },
1804 ));
1805 return;
1806 }
1807 "embedding_dimensions" => {
1811 let embed_list = if result_is_simple {
1813 result_var.to_string()
1814 } else {
1815 format!("{result_var}.embeddings()")
1816 };
1817 let expr = format!("({embed_list}.isEmpty() ? 0 : {embed_list}.get(0).size())");
1818 let java_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
1819 out.push_str(&crate::template_env::render(
1820 "java/synthetic_assertion.jinja",
1821 minijinja::context! {
1822 assertion_kind => "embedding_dimensions",
1823 assertion_type => assertion.assertion_type.as_str(),
1824 expr => expr,
1825 java_val => java_val,
1826 field_name => f,
1827 },
1828 ));
1829 return;
1830 }
1831 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1832 let embed_list = if result_is_simple {
1834 result_var.to_string()
1835 } else {
1836 format!("{result_var}.embeddings()")
1837 };
1838 let pred = match f.as_str() {
1839 "embeddings_valid" => {
1840 format!("{embed_list}.stream().allMatch(e -> e != null && !e.isEmpty())")
1841 }
1842 "embeddings_finite" => {
1843 format!("{embed_list}.stream().flatMap(java.util.Collection::stream).allMatch(Float::isFinite)")
1844 }
1845 "embeddings_non_zero" => {
1846 format!("{embed_list}.stream().allMatch(e -> e.stream().anyMatch(v -> v != 0.0f))")
1847 }
1848 "embeddings_normalized" => format!(
1849 "{embed_list}.stream().allMatch(e -> {{ double n = e.stream().mapToDouble(v -> v * v).sum(); return Math.abs(n - 1.0) < 1e-3; }})"
1850 ),
1851 _ => unreachable!(),
1852 };
1853 let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1854 out.push_str(&crate::template_env::render(
1855 "java/synthetic_assertion.jinja",
1856 minijinja::context! {
1857 assertion_kind => assertion_kind,
1858 assertion_type => assertion.assertion_type.as_str(),
1859 pred => pred,
1860 field_name => f,
1861 },
1862 ));
1863 return;
1864 }
1865 "keywords" | "keywords_count" => {
1867 out.push_str(&crate::template_env::render(
1868 "java/synthetic_assertion.jinja",
1869 minijinja::context! {
1870 assertion_kind => "keywords",
1871 field_name => f,
1872 },
1873 ));
1874 return;
1875 }
1876 "metadata" => {
1879 match assertion.assertion_type.as_str() {
1880 "not_empty" | "is_empty" => {
1881 out.push_str(&crate::template_env::render(
1882 "java/synthetic_assertion.jinja",
1883 minijinja::context! {
1884 assertion_kind => "metadata",
1885 assertion_type => assertion.assertion_type.as_str(),
1886 result_var => result_var,
1887 },
1888 ));
1889 return;
1890 }
1891 _ => {} }
1893 }
1894 _ => {}
1895 }
1896 }
1897
1898 if let Some(f) = &assertion.field {
1904 if is_streaming && !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1905 if let Some(expr) =
1906 crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "java", "chunks")
1907 {
1908 let line = match assertion.assertion_type.as_str() {
1909 "count_min" => {
1910 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1911 format!(" assertTrue({expr}.size() >= {n}, \"expected >= {n} chunks\");\n")
1912 } else {
1913 String::new()
1914 }
1915 }
1916 "count_equals" => {
1917 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1918 format!(" assertEquals({n}, {expr}.size());\n")
1919 } else {
1920 String::new()
1921 }
1922 }
1923 "equals" => {
1924 if let Some(serde_json::Value::String(s)) = &assertion.value {
1925 let escaped = crate::escape::escape_java(s);
1926 format!(" assertEquals(\"{escaped}\", {expr});\n")
1927 } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1928 format!(" assertEquals({n}, {expr});\n")
1929 } else {
1930 String::new()
1931 }
1932 }
1933 "not_empty" => format!(" assertFalse({expr}.isEmpty(), \"expected non-empty\");\n"),
1934 "is_empty" => format!(" assertTrue({expr}.isEmpty(), \"expected empty\");\n"),
1935 "is_true" => format!(" assertTrue({expr}, \"expected true\");\n"),
1936 "is_false" => format!(" assertFalse({expr}, \"expected false\");\n"),
1937 "greater_than" => {
1938 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1939 format!(" assertTrue({expr} > {n}, \"expected > {n}\");\n")
1940 } else {
1941 String::new()
1942 }
1943 }
1944 "greater_than_or_equal" => {
1945 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1946 format!(" assertTrue({expr} >= {n}, \"expected >= {n}\");\n")
1947 } else {
1948 String::new()
1949 }
1950 }
1951 "contains" => {
1952 if let Some(serde_json::Value::String(s)) = &assertion.value {
1953 let escaped = crate::escape::escape_java(s);
1954 format!(
1955 " assertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\");\n"
1956 )
1957 } else {
1958 String::new()
1959 }
1960 }
1961 _ => format!(
1962 " // streaming field '{f}': assertion type '{}' not rendered\n",
1963 assertion.assertion_type
1964 ),
1965 };
1966 if !line.is_empty() {
1967 out.push_str(&line);
1968 }
1969 }
1970 return;
1971 }
1972 }
1973
1974 if let Some(f) = &assertion.field {
1976 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1977 out.push_str(&crate::template_env::render(
1978 "java/synthetic_assertion.jinja",
1979 minijinja::context! {
1980 assertion_kind => "skipped",
1981 field_name => f,
1982 },
1983 ));
1984 return;
1985 }
1986 }
1987
1988 let sealed_display_type: Option<String> = assertion.field.as_deref().and_then(|f| {
1993 let resolved = field_resolver.resolve(f);
1994 assert_enum_types
1995 .get(f)
1996 .or_else(|| assert_enum_types.get(resolved))
1997 .cloned()
1998 });
1999 let is_sealed_display_field = sealed_display_type.is_some();
2000
2001 let field_is_enum = assertion.field.as_deref().is_some_and(|f| {
2008 let resolved = field_resolver.resolve(f);
2009 let in_enum_fields = enum_fields.get(f).is_some() || enum_fields.get(resolved).is_some();
2010 in_enum_fields && !is_sealed_display_field
2011 });
2012
2013 let field_is_array = assertion
2017 .field
2018 .as_deref()
2019 .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
2020
2021 let field_expr = if result_is_simple {
2022 result_var.to_string()
2023 } else {
2024 match &assertion.field {
2025 Some(f) if !f.is_empty() => {
2026 let accessor = field_resolver.accessor(f, "java", result_var);
2027 let resolved = field_resolver.resolve(f);
2028 if field_resolver.is_optional(resolved) && !field_resolver.has_map_access(f) {
2035 let optional_expr = format!("java.util.Optional.ofNullable({accessor})");
2038 if field_is_enum {
2042 match assertion.assertion_type.as_str() {
2043 "not_empty" | "is_empty" => optional_expr,
2044 _ => {
2045 format!("{optional_expr}.map(v -> v.getValue()).orElse(\"\")")
2049 }
2050 }
2051 } else {
2052 match assertion.assertion_type.as_str() {
2053 "not_empty" | "is_empty" => optional_expr,
2056 "count_min" | "count_equals" => {
2058 format!("{optional_expr}.orElse(java.util.List.of())")
2059 }
2060 "greater_than" | "less_than" | "greater_than_or_equal" | "less_than_or_equal" => {
2067 if field_resolver.is_array(resolved) {
2068 format!("{optional_expr}.orElse(java.util.List.of())")
2069 } else {
2070 format!("{optional_expr}.map(Number::longValue).orElse(0L)")
2071 }
2072 }
2073 "equals" => {
2079 if is_sealed_display_field {
2080 optional_expr
2082 } else if let Some(expected) = &assertion.value {
2083 if expected.is_number() {
2084 format!("{optional_expr}.map(Number::longValue).orElse(0L)")
2085 } else {
2086 format!("{optional_expr}.orElse(\"\")")
2087 }
2088 } else {
2089 format!("{optional_expr}.orElse(\"\")")
2090 }
2091 }
2092 _ if field_resolver.is_array(resolved) => {
2093 format!("{optional_expr}.orElse(java.util.List.of())")
2094 }
2095 _ => format!("{optional_expr}.orElse(\"\")"),
2096 }
2097 }
2098 } else {
2099 accessor
2100 }
2101 }
2102 _ => result_var.to_string(),
2103 }
2104 };
2105
2106 let string_expr = if field_is_enum && !field_expr.contains(".map(v -> v.getValue())") {
2114 format!("{field_expr}.getValue()")
2115 } else if let Some(ref stype) = sealed_display_type {
2116 let inner_expr = if field_expr.contains("Optional.ofNullable") {
2120 format!("{field_expr}.orElse(null)")
2121 } else {
2122 field_expr.clone()
2123 };
2124 format!("{stype}Display.toDisplayString({inner_expr})")
2125 } else {
2126 field_expr.clone()
2127 };
2128
2129 let assertion_type = assertion.assertion_type.as_str();
2131 let java_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
2132 let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
2133 let is_numeric_val = assertion.value.as_ref().is_some_and(|v| v.is_number());
2134
2135 let values_java: Vec<String> = assertion
2139 .values
2140 .as_ref()
2141 .map(|values| values.iter().map(json_to_java).collect::<Vec<_>>())
2142 .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_java(v)]))
2143 .unwrap_or_default();
2144
2145 let contains_any_expr = if !values_java.is_empty() {
2146 values_java
2147 .iter()
2148 .map(|v| format!("{string_expr}.contains({v})"))
2149 .collect::<Vec<_>>()
2150 .join(" || ")
2151 } else {
2152 String::new()
2153 };
2154
2155 let length_expr = if result_is_bytes {
2156 format!("{field_expr}.length")
2157 } else {
2158 format!("{field_expr}.length()")
2159 };
2160
2161 let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
2162
2163 let call_expr = if let Some(method_name) = &assertion.method {
2164 build_java_method_call(result_var, method_name, assertion.args.as_ref(), class_name)
2165 } else {
2166 String::new()
2167 };
2168
2169 let check = assertion.check.as_deref().unwrap_or("is_true");
2170
2171 let java_check_val = assertion.value.as_ref().map(json_to_java).unwrap_or_default();
2172
2173 let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
2174
2175 let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
2176 let bool_is_true = assertion.value.as_ref().is_some_and(|v| v.as_bool() == Some(true));
2177
2178 let method_returns_collection = assertion
2179 .method
2180 .as_ref()
2181 .is_some_and(|m| matches!(m.as_str(), "find_nodes_by_type" | "findNodesByType"));
2182
2183 let rendered = crate::template_env::render(
2184 "java/assertion.jinja",
2185 minijinja::context! {
2186 assertion_type,
2187 java_val,
2188 string_expr,
2189 field_expr,
2190 field_is_enum,
2191 field_is_array,
2192 is_string_val,
2193 is_numeric_val,
2194 values_java => values_java,
2195 contains_any_expr,
2196 length_expr,
2197 n,
2198 call_expr,
2199 check,
2200 java_check_val,
2201 check_n,
2202 is_bool_val,
2203 bool_is_true,
2204 method_returns_collection,
2205 },
2206 );
2207 out.push_str(&rendered);
2208}
2209
2210fn build_java_method_call(
2214 result_var: &str,
2215 method_name: &str,
2216 args: Option<&serde_json::Value>,
2217 class_name: &str,
2218) -> String {
2219 match method_name {
2220 "root_child_count" => format!("{result_var}.rootNode().childCount()"),
2221 "root_node_type" => format!("{result_var}.rootNode().kind()"),
2222 "named_children_count" => format!("{result_var}.rootNode().namedChildCount()"),
2223 "has_error_nodes" => format!("{class_name}.treeHasErrorNodes({result_var})"),
2224 "error_count" | "tree_error_count" => format!("{class_name}.treeErrorCount({result_var})"),
2225 "tree_to_sexp" => format!("{class_name}.treeToSexp({result_var})"),
2226 "contains_node_type" => {
2227 let node_type = args
2228 .and_then(|a| a.get("node_type"))
2229 .and_then(|v| v.as_str())
2230 .unwrap_or("");
2231 format!("{class_name}.treeContainsNodeType({result_var}, \"{node_type}\")")
2232 }
2233 "find_nodes_by_type" => {
2234 let node_type = args
2235 .and_then(|a| a.get("node_type"))
2236 .and_then(|v| v.as_str())
2237 .unwrap_or("");
2238 format!("{class_name}.findNodesByType({result_var}, \"{node_type}\")")
2239 }
2240 "run_query" => {
2241 let query_source = args
2242 .and_then(|a| a.get("query_source"))
2243 .and_then(|v| v.as_str())
2244 .unwrap_or("");
2245 let language = args
2246 .and_then(|a| a.get("language"))
2247 .and_then(|v| v.as_str())
2248 .unwrap_or("");
2249 let escaped_query = escape_java(query_source);
2250 format!("{class_name}.runQuery({result_var}, \"{language}\", \"{escaped_query}\", source)")
2251 }
2252 _ => {
2253 format!("{result_var}.{}()", method_name.to_lower_camel_case())
2254 }
2255 }
2256}
2257
2258fn emit_java_object_array(arr: &serde_json::Value, elem_type: &str) -> String {
2261 if let Some(items) = arr.as_array() {
2262 if items.is_empty() {
2263 return "java.util.List.of()".to_string();
2264 }
2265 let item_strs: Vec<String> = items
2266 .iter()
2267 .map(|item| {
2268 let json_str = serde_json::to_string(item).unwrap_or_default();
2269 let escaped = escape_java(&json_str);
2270 format!("JsonUtil.fromJson(\"{escaped}\", {elem_type}.class)")
2271 })
2272 .collect();
2273 format!("java.util.Arrays.asList({})", item_strs.join(", "))
2274 } else {
2275 "java.util.List.of()".to_string()
2276 }
2277}
2278
2279fn json_to_java(value: &serde_json::Value) -> String {
2281 json_to_java_typed(value, None)
2282}
2283
2284fn emit_java_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
2288 if let Some(items) = arr.as_array() {
2289 let item_strs: Vec<String> = items
2290 .iter()
2291 .filter_map(|item| {
2292 if let Some(obj) = item.as_object() {
2293 match elem_type {
2294 "BatchBytesItem" => {
2295 let content = obj.get("content").and_then(|v| v.as_array());
2296 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
2297 let content_code = if let Some(arr) = content {
2298 let bytes: Vec<String> = arr
2299 .iter()
2300 .filter_map(|v| v.as_u64().map(|n| format!("(byte) {}", n)))
2301 .collect();
2302 format!("new byte[] {{{}}}", bytes.join(", "))
2303 } else {
2304 "new byte[] {}".to_string()
2305 };
2306 Some(format!("new {}({}, \"{}\", null)", elem_type, content_code, mime_type))
2307 }
2308 "BatchFileItem" => {
2309 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
2310 Some(format!(
2311 "new {}(java.nio.file.Paths.get(\"{}\"), null)",
2312 elem_type, path
2313 ))
2314 }
2315 _ => None,
2316 }
2317 } else {
2318 None
2319 }
2320 })
2321 .collect();
2322 format!("java.util.Arrays.asList({})", item_strs.join(", "))
2323 } else {
2324 "java.util.List.of()".to_string()
2325 }
2326}
2327
2328fn json_to_java_typed(value: &serde_json::Value, element_type: Option<&str>) -> String {
2329 match value {
2330 serde_json::Value::String(s) => format!("\"{}\"", escape_java(s)),
2331 serde_json::Value::Bool(b) => b.to_string(),
2332 serde_json::Value::Number(n) => {
2333 if n.is_f64() {
2334 match element_type {
2335 Some("f32" | "float" | "Float") => format!("{}f", n),
2336 _ => format!("{}d", n),
2337 }
2338 } else {
2339 n.to_string()
2340 }
2341 }
2342 serde_json::Value::Null => "null".to_string(),
2343 serde_json::Value::Array(arr) => {
2344 let items: Vec<String> = arr.iter().map(|v| json_to_java_typed(v, element_type)).collect();
2345 format!("java.util.List.of({})", items.join(", "))
2346 }
2347 serde_json::Value::Object(_) => {
2348 let json_str = serde_json::to_string(value).unwrap_or_default();
2349 format!("\"{}\"", escape_java(&json_str))
2350 }
2351 }
2352}
2353
2354fn java_builder_expression(
2365 obj: &serde_json::Map<String, serde_json::Value>,
2366 type_name: &str,
2367 enum_fields: &std::collections::HashSet<String>,
2368 nested_types: &std::collections::HashMap<String, String>,
2369 nested_types_optional: bool,
2370 path_fields: &[String],
2371) -> String {
2372 let mut expr = format!("{}.builder()", type_name);
2373 for (key, val) in obj {
2374 let camel_key = key.to_lower_camel_case();
2376 let method_name = format!("with{}", camel_key.to_upper_camel_case());
2377
2378 let java_val = match val {
2379 serde_json::Value::String(s) => {
2380 if enum_fields.contains(&camel_key) {
2383 let enum_type_name = camel_key.to_upper_camel_case();
2385 let variant_name = s.to_upper_camel_case();
2386 format!("{}.{}", enum_type_name, variant_name)
2387 } else if camel_key == "preset" && type_name == "PreprocessingOptions" {
2388 let variant_name = s.to_upper_camel_case();
2390 format!("PreprocessingPreset.{}", variant_name)
2391 } else if path_fields.contains(key) {
2392 format!("Optional.of(java.nio.file.Path.of(\"{}\"))", escape_java(s))
2394 } else {
2395 format!("\"{}\"", escape_java(s))
2397 }
2398 }
2399 serde_json::Value::Bool(b) => b.to_string(),
2400 serde_json::Value::Null => "null".to_string(),
2401 serde_json::Value::Number(n) => {
2402 let camel_key = key.to_lower_camel_case();
2410 let is_plain_field = matches!(camel_key.as_str(), "listIndentWidth" | "wrapWidth");
2411 let is_primitive_builder = matches!(type_name, "SecurityLimits" | "SecurityLimitsBuilder");
2414
2415 if is_plain_field || is_primitive_builder {
2416 if n.is_f64() {
2418 format!("{}d", n)
2419 } else {
2420 format!("{}L", n)
2421 }
2422 } else {
2423 if n.is_f64() {
2425 format!("Optional.of({}d)", n)
2426 } else {
2427 format!("Optional.of({}L)", n)
2428 }
2429 }
2430 }
2431 serde_json::Value::Array(arr) => {
2432 let items: Vec<String> = arr.iter().map(|v| json_to_java_typed(v, None)).collect();
2433 format!("java.util.List.of({})", items.join(", "))
2434 }
2435 serde_json::Value::Object(nested) => {
2436 let nested_type = nested_types
2438 .get(key.as_str())
2439 .cloned()
2440 .unwrap_or_else(|| format!("{}Options", key.to_upper_camel_case()));
2441 let inner = java_builder_expression(
2442 nested,
2443 &nested_type,
2444 enum_fields,
2445 nested_types,
2446 nested_types_optional,
2447 &[],
2448 );
2449 let is_primitive_builder = matches!(type_name, "SecurityLimits" | "SecurityLimitsBuilder");
2453 if is_primitive_builder || !nested_types_optional {
2454 inner
2455 } else {
2456 format!("Optional.of({inner})")
2457 }
2458 }
2459 };
2460 expr.push_str(&format!(".{}({})", method_name, java_val));
2461 }
2462 expr.push_str(".build()");
2463 expr
2464}
2465
2466#[allow(dead_code)]
2473fn collect_enum_and_nested_types(
2474 obj: &serde_json::Map<String, serde_json::Value>,
2475 enum_fields: &std::collections::HashMap<String, String>,
2476 types_out: &mut std::collections::BTreeSet<String>,
2477) {
2478 for (key, val) in obj {
2479 let camel_key = key.to_lower_camel_case();
2481 if let Some(enum_type) = enum_fields.get(&camel_key) {
2482 types_out.insert(enum_type.clone());
2484 } else if camel_key == "preset" {
2485 types_out.insert("PreprocessingPreset".to_string());
2487 }
2488 if let Some(nested) = val.as_object() {
2490 collect_enum_and_nested_types(nested, enum_fields, types_out);
2491 }
2492 }
2493}
2494
2495fn collect_nested_type_names(
2496 obj: &serde_json::Map<String, serde_json::Value>,
2497 nested_types: &std::collections::HashMap<String, String>,
2498 types_out: &mut std::collections::BTreeSet<String>,
2499) {
2500 for (key, val) in obj {
2501 if let Some(type_name) = nested_types.get(key.as_str()) {
2502 types_out.insert(type_name.clone());
2503 }
2504 if let Some(nested) = val.as_object() {
2505 collect_nested_type_names(nested, nested_types, types_out);
2506 }
2507 }
2508}
2509
2510fn build_java_visitor(
2516 setup_lines: &mut Vec<String>,
2517 visitor_spec: &crate::fixture::VisitorSpec,
2518 class_name: &str,
2519) -> String {
2520 setup_lines.push("class _TestVisitor implements Visitor {".to_string());
2521 for (method_name, action) in &visitor_spec.callbacks {
2522 emit_java_visitor_method(setup_lines, method_name, action, class_name);
2523 }
2524 setup_lines.push("}".to_string());
2525 setup_lines.push("var visitor = new _TestVisitor();".to_string());
2526 "visitor".to_string()
2527}
2528
2529fn emit_java_visitor_method(
2531 setup_lines: &mut Vec<String>,
2532 method_name: &str,
2533 action: &CallbackAction,
2534 _class_name: &str,
2535) {
2536 let camel_method = method_to_camel(method_name);
2537 let params = match method_name {
2538 "visit_link" => "NodeContext ctx, String href, String text, String title",
2539 "visit_image" => "NodeContext ctx, String src, String alt, String title",
2540 "visit_heading" => "NodeContext ctx, int level, String text, String id",
2541 "visit_code_block" => "NodeContext ctx, String lang, String code",
2542 "visit_code_inline"
2543 | "visit_strong"
2544 | "visit_emphasis"
2545 | "visit_strikethrough"
2546 | "visit_underline"
2547 | "visit_subscript"
2548 | "visit_superscript"
2549 | "visit_mark"
2550 | "visit_button"
2551 | "visit_summary"
2552 | "visit_figcaption"
2553 | "visit_definition_term"
2554 | "visit_definition_description" => "NodeContext ctx, String text",
2555 "visit_text" => "NodeContext ctx, String text",
2556 "visit_list_item" => "NodeContext ctx, boolean ordered, String marker, String text",
2557 "visit_blockquote" => "NodeContext ctx, String content, long depth",
2558 "visit_table_row" => "NodeContext ctx, java.util.List<String> cells, boolean isHeader",
2559 "visit_custom_element" => "NodeContext ctx, String tagName, String html",
2560 "visit_form" => "NodeContext ctx, String actionUrl, String method",
2561 "visit_input" => "NodeContext ctx, String inputType, String name, String value",
2562 "visit_audio" | "visit_video" | "visit_iframe" => "NodeContext ctx, String src",
2563 "visit_details" => "NodeContext ctx, boolean isOpen",
2564 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
2565 "NodeContext ctx, String output"
2566 }
2567 "visit_list_start" => "NodeContext ctx, boolean ordered",
2568 "visit_list_end" => "NodeContext ctx, boolean ordered, String output",
2569 _ => "NodeContext ctx",
2570 };
2571
2572 let (action_type, action_value, format_args) = match action {
2574 CallbackAction::Skip => ("skip", String::new(), Vec::new()),
2575 CallbackAction::Continue => ("continue", String::new(), Vec::new()),
2576 CallbackAction::PreserveHtml => ("preserve_html", String::new(), Vec::new()),
2577 CallbackAction::Custom { output } => ("custom_literal", escape_java(output), Vec::new()),
2578 CallbackAction::CustomTemplate { template, .. } => {
2579 let mut format_str = String::with_capacity(template.len());
2581 let mut format_args: Vec<String> = Vec::new();
2582 let mut chars = template.chars().peekable();
2583 while let Some(ch) = chars.next() {
2584 if ch == '{' {
2585 let mut name = String::new();
2587 let mut closed = false;
2588 for inner in chars.by_ref() {
2589 if inner == '}' {
2590 closed = true;
2591 break;
2592 }
2593 name.push(inner);
2594 }
2595 if closed && !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
2596 let camel_name = name.as_str().to_lower_camel_case();
2597 format_args.push(camel_name);
2598 format_str.push_str("%s");
2599 } else {
2600 format_str.push('{');
2602 format_str.push_str(&name);
2603 if closed {
2604 format_str.push('}');
2605 }
2606 }
2607 } else {
2608 format_str.push(ch);
2609 }
2610 }
2611 let escaped = escape_java(&format_str);
2612 if format_args.is_empty() {
2613 ("custom_literal", escaped, Vec::new())
2614 } else {
2615 ("custom_formatted", escaped, format_args)
2616 }
2617 }
2618 };
2619
2620 let params = params.to_string();
2621
2622 let rendered = crate::template_env::render(
2623 "java/visitor_method.jinja",
2624 minijinja::context! {
2625 camel_method,
2626 params,
2627 action_type,
2628 action_value,
2629 format_args => format_args,
2630 },
2631 );
2632 setup_lines.push(rendered);
2633}
2634
2635fn method_to_camel(snake: &str) -> String {
2637 snake.to_lower_camel_case()
2638}
2639
2640#[cfg(test)]
2641mod tests {
2642 use crate::config::{CallConfig, E2eConfig, SelectWhen};
2643 use crate::fixture::Fixture;
2644 use std::collections::HashMap;
2645
2646 fn make_fixture_with_input(id: &str, input: serde_json::Value) -> Fixture {
2647 Fixture {
2648 id: id.to_string(),
2649 category: None,
2650 description: "test fixture".to_string(),
2651 tags: vec![],
2652 skip: None,
2653 env: None,
2654 call: None,
2655 input,
2656 mock_response: None,
2657 source: String::new(),
2658 http: None,
2659 assertions: vec![],
2660 visitor: None,
2661 }
2662 }
2663
2664 #[test]
2667 fn test_java_select_when_routes_to_batch_scrape() {
2668 let mut calls = HashMap::new();
2669 calls.insert(
2670 "batch_scrape".to_string(),
2671 CallConfig {
2672 function: "batchScrape".to_string(),
2673 module: "com.example.kreuzcrawl".to_string(),
2674 select_when: Some(SelectWhen {
2675 input_has: Some("batch_urls".to_string()),
2676 ..Default::default()
2677 }),
2678 ..CallConfig::default()
2679 },
2680 );
2681
2682 let e2e_config = E2eConfig {
2683 call: CallConfig {
2684 function: "scrape".to_string(),
2685 module: "com.example.kreuzcrawl".to_string(),
2686 ..CallConfig::default()
2687 },
2688 calls,
2689 ..E2eConfig::default()
2690 };
2691
2692 let fixture = make_fixture_with_input("batch_empty_urls", serde_json::json!({ "batch_urls": [] }));
2694
2695 let resolved_call = e2e_config.resolve_call_for_fixture(
2696 fixture.call.as_deref(),
2697 &fixture.id,
2698 &fixture.resolved_category(),
2699 &fixture.tags,
2700 &fixture.input,
2701 );
2702 assert_eq!(resolved_call.function, "batchScrape");
2703
2704 let fixture_no_batch =
2706 make_fixture_with_input("simple_scrape", serde_json::json!({ "url": "https://example.com" }));
2707 let resolved_default = e2e_config.resolve_call_for_fixture(
2708 fixture_no_batch.call.as_deref(),
2709 &fixture_no_batch.id,
2710 &fixture_no_batch.resolved_category(),
2711 &fixture_no_batch.tags,
2712 &fixture_no_batch.input,
2713 );
2714 assert_eq!(resolved_default.function, "scrape");
2715 }
2716}