mirror of
https://github.com/elicpeter/nyx.git
synced 2026-06-09 19:45:13 +02:00
[pitboss] phase 14: Track L.12 — Spring / Quarkus / Micronaut / Jakarta Servlet adapters
This commit is contained in:
parent
67685947ab
commit
78023ccf38
47 changed files with 1711 additions and 21 deletions
171
src/dynamic/framework/adapters/java_micronaut.rs
Normal file
171
src/dynamic/framework/adapters/java_micronaut.rs
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
//! Java Micronaut [`super::super::FrameworkAdapter`] (Phase 14 — Track L.12).
|
||||
//!
|
||||
//! Recognises Micronaut `@Controller("/path")` on a class plus a
|
||||
//! handler method annotated with `@Get("/sub")` / `@Post` / `@Put` /
|
||||
//! `@Delete` / `@Patch` / `@Head` / `@Options` (mixed-case, distinct
|
||||
//! from JAX-RS all-caps verbs). Fires only when the source carries
|
||||
//! a Micronaut import stanza so a Spring `@Controller` + Spring
|
||||
//! `@GetMapping` file does not collide with this adapter.
|
||||
|
||||
use crate::dynamic::framework::{FrameworkAdapter, FrameworkBinding, HttpMethod, RouteShape};
|
||||
use crate::evidence::EntryKind;
|
||||
use crate::summary::FuncSummary;
|
||||
use crate::symbol::Lang;
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::java_routes::{
|
||||
annotation_string_arg, bind_java_params, find_class_with_method, iter_annotations,
|
||||
join_route_path, method_formal_types, source_imports_micronaut,
|
||||
};
|
||||
|
||||
pub struct JavaMicronautAdapter;
|
||||
|
||||
const ADAPTER_NAME: &str = "java-micronaut";
|
||||
|
||||
fn verb_for(name: &str) -> Option<HttpMethod> {
|
||||
match name {
|
||||
"Get" => Some(HttpMethod::GET),
|
||||
"Post" => Some(HttpMethod::POST),
|
||||
"Put" => Some(HttpMethod::PUT),
|
||||
"Delete" => Some(HttpMethod::DELETE),
|
||||
"Patch" => Some(HttpMethod::PATCH),
|
||||
"Head" => Some(HttpMethod::HEAD),
|
||||
"Options" => Some(HttpMethod::OPTIONS),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn class_path_prefix(class: Node<'_>, bytes: &[u8]) -> Option<String> {
|
||||
let mut hit: Option<String> = None;
|
||||
iter_annotations(class, bytes, |ann, name| {
|
||||
if name == "Controller" {
|
||||
hit = Some(annotation_string_arg(ann, bytes).unwrap_or_default());
|
||||
}
|
||||
});
|
||||
hit
|
||||
}
|
||||
|
||||
fn method_verb_and_path(
|
||||
method: Node<'_>,
|
||||
bytes: &[u8],
|
||||
) -> Option<(HttpMethod, String)> {
|
||||
let mut hit: Option<(HttpMethod, String)> = None;
|
||||
iter_annotations(method, bytes, |ann, name| {
|
||||
if hit.is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(v) = verb_for(name) {
|
||||
let path = annotation_string_arg(ann, bytes).unwrap_or_default();
|
||||
hit = Some((v, path));
|
||||
}
|
||||
});
|
||||
hit
|
||||
}
|
||||
|
||||
impl FrameworkAdapter for JavaMicronautAdapter {
|
||||
fn name(&self) -> &'static str {
|
||||
ADAPTER_NAME
|
||||
}
|
||||
|
||||
fn lang(&self) -> Lang {
|
||||
Lang::Java
|
||||
}
|
||||
|
||||
fn detect(
|
||||
&self,
|
||||
summary: &FuncSummary,
|
||||
ast: Node<'_>,
|
||||
file_bytes: &[u8],
|
||||
) -> Option<FrameworkBinding> {
|
||||
if !source_imports_micronaut(file_bytes) {
|
||||
return None;
|
||||
}
|
||||
let (class, method) = find_class_with_method(ast, file_bytes, &summary.name)?;
|
||||
let class_prefix = class_path_prefix(class, file_bytes)?;
|
||||
let (http_method, method_path) = method_verb_and_path(method, file_bytes)?;
|
||||
let path = join_route_path(&class_prefix, &method_path);
|
||||
let formals = method_formal_types(method, file_bytes);
|
||||
let request_params = bind_java_params(&formals, &path);
|
||||
Some(FrameworkBinding {
|
||||
adapter: ADAPTER_NAME.to_owned(),
|
||||
kind: EntryKind::HttpRoute,
|
||||
route: Some(RouteShape {
|
||||
method: http_method,
|
||||
path,
|
||||
}),
|
||||
request_params,
|
||||
response_writer: None,
|
||||
middleware: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::dynamic::framework::ParamSource;
|
||||
|
||||
fn parse(src: &[u8]) -> tree_sitter::Tree {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let lang = tree_sitter::Language::from(tree_sitter_java::LANGUAGE);
|
||||
parser.set_language(&lang).unwrap();
|
||||
parser.parse(src, None).unwrap()
|
||||
}
|
||||
|
||||
fn summary(name: &str) -> FuncSummary {
|
||||
FuncSummary {
|
||||
name: name.into(),
|
||||
lang: "java".into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_controller_plus_get() {
|
||||
let src: &[u8] = b"import io.micronaut.http.annotation.Controller;\nimport io.micronaut.http.annotation.Get;\n@Controller(\"/api\")\npublic class V {\n @Get(\"/{id}\")\n public String show(String id) { return id; }\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaMicronautAdapter
|
||||
.detect(&summary("show"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
assert_eq!(binding.adapter, "java-micronaut");
|
||||
let route = binding.route.unwrap();
|
||||
assert_eq!(route.method, HttpMethod::GET);
|
||||
assert_eq!(route.path, "/api/{id}");
|
||||
let id_binding = binding
|
||||
.request_params
|
||||
.iter()
|
||||
.find(|p| p.name == "id")
|
||||
.unwrap();
|
||||
assert!(matches!(id_binding.source, ParamSource::PathSegment(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_post_with_empty_prefix() {
|
||||
let src: &[u8] = b"import io.micronaut.http.annotation.Controller;\nimport io.micronaut.http.annotation.Post;\n@Controller\npublic class V {\n @Post(\"/save\")\n public String save(String body) { return body; }\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaMicronautAdapter
|
||||
.detect(&summary("save"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
let route = binding.route.unwrap();
|
||||
assert_eq!(route.method, HttpMethod::POST);
|
||||
assert_eq!(route.path, "/save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_non_micronaut_file() {
|
||||
let src: &[u8] = b"@Controller\npublic class C {\n @GetMapping(\"/x\")\n public String x() { return \"\"; }\n}\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaMicronautAdapter
|
||||
.detect(&summary("x"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_method_without_micronaut_verb() {
|
||||
let src: &[u8] = b"import io.micronaut.http.annotation.Controller;\n@Controller(\"/api\")\npublic class V {\n public String helper() { return \"\"; }\n}\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaMicronautAdapter
|
||||
.detect(&summary("helper"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
175
src/dynamic/framework/adapters/java_quarkus.rs
Normal file
175
src/dynamic/framework/adapters/java_quarkus.rs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
//! Java Quarkus / Jakarta REST [`super::super::FrameworkAdapter`]
|
||||
//! (Phase 14 — Track L.12).
|
||||
//!
|
||||
//! Recognises `@Path("/path")` on a class plus a handler method
|
||||
//! annotated with `@GET` / `@POST` / `@PUT` / `@DELETE` / `@PATCH` /
|
||||
//! `@HEAD` / `@OPTIONS` (all-caps JAX-RS verb annotations, distinct
|
||||
//! from Micronaut's mixed-case `@Get` / `@Post`). Method-level
|
||||
//! `@Path("/sub")` is concatenated with the class-level prefix.
|
||||
|
||||
use crate::dynamic::framework::{FrameworkAdapter, FrameworkBinding, HttpMethod, RouteShape};
|
||||
use crate::evidence::EntryKind;
|
||||
use crate::summary::FuncSummary;
|
||||
use crate::symbol::Lang;
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::java_routes::{
|
||||
annotation_string_arg, bind_java_params, find_class_with_method, iter_annotations,
|
||||
join_route_path, method_formal_types, source_imports_quarkus,
|
||||
};
|
||||
|
||||
pub struct JavaQuarkusAdapter;
|
||||
|
||||
const ADAPTER_NAME: &str = "java-quarkus";
|
||||
|
||||
fn verb_for(name: &str) -> Option<HttpMethod> {
|
||||
match name {
|
||||
"GET" => Some(HttpMethod::GET),
|
||||
"POST" => Some(HttpMethod::POST),
|
||||
"PUT" => Some(HttpMethod::PUT),
|
||||
"DELETE" => Some(HttpMethod::DELETE),
|
||||
"PATCH" => Some(HttpMethod::PATCH),
|
||||
"HEAD" => Some(HttpMethod::HEAD),
|
||||
"OPTIONS" => Some(HttpMethod::OPTIONS),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn class_path_prefix(class: Node<'_>, bytes: &[u8]) -> String {
|
||||
let mut prefix = String::new();
|
||||
iter_annotations(class, bytes, |ann, name| {
|
||||
if name == "Path" {
|
||||
if let Some(p) = annotation_string_arg(ann, bytes) {
|
||||
prefix = p;
|
||||
}
|
||||
}
|
||||
});
|
||||
prefix
|
||||
}
|
||||
|
||||
fn method_verb_and_path(
|
||||
method: Node<'_>,
|
||||
bytes: &[u8],
|
||||
) -> Option<(HttpMethod, String)> {
|
||||
let mut verb: Option<HttpMethod> = None;
|
||||
let mut path = String::new();
|
||||
iter_annotations(method, bytes, |ann, name| {
|
||||
if let Some(v) = verb_for(name) {
|
||||
verb = Some(v);
|
||||
}
|
||||
if name == "Path" {
|
||||
if let Some(p) = annotation_string_arg(ann, bytes) {
|
||||
path = p;
|
||||
}
|
||||
}
|
||||
});
|
||||
Some((verb?, path))
|
||||
}
|
||||
|
||||
impl FrameworkAdapter for JavaQuarkusAdapter {
|
||||
fn name(&self) -> &'static str {
|
||||
ADAPTER_NAME
|
||||
}
|
||||
|
||||
fn lang(&self) -> Lang {
|
||||
Lang::Java
|
||||
}
|
||||
|
||||
fn detect(
|
||||
&self,
|
||||
summary: &FuncSummary,
|
||||
ast: Node<'_>,
|
||||
file_bytes: &[u8],
|
||||
) -> Option<FrameworkBinding> {
|
||||
if !source_imports_quarkus(file_bytes) {
|
||||
return None;
|
||||
}
|
||||
let (class, method) = find_class_with_method(ast, file_bytes, &summary.name)?;
|
||||
let (http_method, method_path) = method_verb_and_path(method, file_bytes)?;
|
||||
let class_prefix = class_path_prefix(class, file_bytes);
|
||||
let path = join_route_path(&class_prefix, &method_path);
|
||||
let formals = method_formal_types(method, file_bytes);
|
||||
let request_params = bind_java_params(&formals, &path);
|
||||
Some(FrameworkBinding {
|
||||
adapter: ADAPTER_NAME.to_owned(),
|
||||
kind: EntryKind::HttpRoute,
|
||||
route: Some(RouteShape {
|
||||
method: http_method,
|
||||
path,
|
||||
}),
|
||||
request_params,
|
||||
response_writer: None,
|
||||
middleware: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::dynamic::framework::ParamSource;
|
||||
|
||||
fn parse(src: &[u8]) -> tree_sitter::Tree {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let lang = tree_sitter::Language::from(tree_sitter_java::LANGUAGE);
|
||||
parser.set_language(&lang).unwrap();
|
||||
parser.parse(src, None).unwrap()
|
||||
}
|
||||
|
||||
fn summary(name: &str) -> FuncSummary {
|
||||
FuncSummary {
|
||||
name: name.into(),
|
||||
lang: "java".into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_class_path_plus_method_get() {
|
||||
let src: &[u8] = b"import jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\n@Path(\"/api\")\npublic class V {\n @GET\n @Path(\"/{id}\")\n public String show(String id) { return id; }\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaQuarkusAdapter
|
||||
.detect(&summary("show"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
assert_eq!(binding.adapter, "java-quarkus");
|
||||
let route = binding.route.unwrap();
|
||||
assert_eq!(route.method, HttpMethod::GET);
|
||||
assert_eq!(route.path, "/api/{id}");
|
||||
let id_binding = binding
|
||||
.request_params
|
||||
.iter()
|
||||
.find(|p| p.name == "id")
|
||||
.unwrap();
|
||||
assert!(matches!(id_binding.source, ParamSource::PathSegment(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_post_without_class_prefix() {
|
||||
let src: &[u8] = b"import io.quarkus.runtime.Quarkus;\nimport jakarta.ws.rs.POST;\n@Path(\"/save\")\npublic class V {\n @POST\n public String save(String body) { return body; }\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaQuarkusAdapter
|
||||
.detect(&summary("save"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
let route = binding.route.unwrap();
|
||||
assert_eq!(route.method, HttpMethod::POST);
|
||||
assert_eq!(route.path, "/save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_non_quarkus_file() {
|
||||
let src: &[u8] = b"@RestController\npublic class C {\n @GetMapping(\"/x\")\n public String x() { return \"\"; }\n}\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaQuarkusAdapter
|
||||
.detect(&summary("x"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_method_without_verb_annotation() {
|
||||
let src: &[u8] = b"import jakarta.ws.rs.Path;\n@Path(\"/api\")\npublic class V {\n public String helper() { return \"\"; }\n}\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaQuarkusAdapter
|
||||
.detect(&summary("helper"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
455
src/dynamic/framework/adapters/java_routes.rs
Normal file
455
src/dynamic/framework/adapters/java_routes.rs
Normal file
|
|
@ -0,0 +1,455 @@
|
|||
//! Shared Java-route adapter helpers (Phase 14 — Track L.12).
|
||||
//!
|
||||
//! The Spring / Quarkus / Micronaut / Servlet adapters all share the
|
||||
//! same handful of tree-sitter helpers: locate a `class_declaration`
|
||||
//! containing a `method_declaration` whose name matches the target,
|
||||
//! walk the class- and method-level annotation lists, pull a string
|
||||
//! argument from an annotation, classify the path placeholders, and
|
||||
//! bind formals to request slots. Centralising the helpers keeps the
|
||||
//! four adapters terse and makes the placeholder-binding semantics
|
||||
//! identical across frameworks.
|
||||
|
||||
use crate::dynamic::framework::{HttpMethod, ParamBinding, ParamSource};
|
||||
use tree_sitter::Node;
|
||||
|
||||
/// True when `bytes` carries any of the well-known Spring import
|
||||
/// stanzas or the bare `@RestController` / `@RequestMapping` /
|
||||
/// `@GetMapping` / `@PostMapping` annotations (the synthetic-import
|
||||
/// fixture path used by the Phase 14 corpus).
|
||||
pub fn source_imports_spring(bytes: &[u8]) -> bool {
|
||||
contains_any(
|
||||
bytes,
|
||||
&[
|
||||
b"org.springframework",
|
||||
b"@RestController",
|
||||
b"@Controller(",
|
||||
b"@Controller\n",
|
||||
b"@Controller\r",
|
||||
b"@RequestMapping",
|
||||
b"@GetMapping",
|
||||
b"@PostMapping",
|
||||
b"@PutMapping",
|
||||
b"@PatchMapping",
|
||||
b"@DeleteMapping",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// True when `bytes` carries a Quarkus or JAX-RS / Jakarta REST
|
||||
/// stanza. Distinct from `source_imports_spring` so the Spring
|
||||
/// adapter does not collide on a Quarkus file that happens to use
|
||||
/// the bare `@Path` annotation.
|
||||
pub fn source_imports_quarkus(bytes: &[u8]) -> bool {
|
||||
contains_any(
|
||||
bytes,
|
||||
&[
|
||||
b"io.quarkus",
|
||||
b"jakarta.ws.rs",
|
||||
b"javax.ws.rs",
|
||||
b"@QuarkusTest",
|
||||
b"@Path(",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// True when `bytes` carries a Micronaut import stanza. Micronaut
|
||||
/// reuses `@Controller` as a class-level marker but pairs it with
|
||||
/// `@Get` / `@Post` / `@Put` / `@Delete` (mixed-case, distinct from
|
||||
/// the all-caps JAX-RS verb annotations Quarkus picks up).
|
||||
pub fn source_imports_micronaut(bytes: &[u8]) -> bool {
|
||||
contains_any(
|
||||
bytes,
|
||||
&[
|
||||
b"io.micronaut",
|
||||
b"@MicronautTest",
|
||||
b"micronaut.http.annotation",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// True when `bytes` carries any of the well-known Java Servlet API
|
||||
/// import stanzas or a class extending `HttpServlet`. The bare
|
||||
/// `HttpServletRequest` / `HttpServletResponse` stub-class names also
|
||||
/// fire so the Phase 14 default-package fixture path lights up the
|
||||
/// adapter without a Jakarta servlet jar.
|
||||
pub fn source_imports_servlet(bytes: &[u8]) -> bool {
|
||||
contains_any(
|
||||
bytes,
|
||||
&[
|
||||
b"javax.servlet",
|
||||
b"jakarta.servlet",
|
||||
b"HttpServletRequest",
|
||||
b"HttpServletResponse",
|
||||
b"extends HttpServlet",
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn contains_any(haystack: &[u8], needles: &[&[u8]]) -> bool {
|
||||
needles
|
||||
.iter()
|
||||
.any(|n| haystack.windows(n.len()).any(|w| w == *n))
|
||||
}
|
||||
|
||||
/// Locate the (class_decl, method_decl) pair whose method's name
|
||||
/// equals `target`. Returns the outermost matching class so the
|
||||
/// caller can read class-level annotations (route prefix, auth
|
||||
/// markers) without re-walking.
|
||||
pub fn find_class_with_method<'a>(
|
||||
root: Node<'a>,
|
||||
bytes: &[u8],
|
||||
target: &str,
|
||||
) -> Option<(Node<'a>, Node<'a>)> {
|
||||
let mut hit: Option<(Node<'a>, Node<'a>)> = None;
|
||||
walk(root, bytes, target, &mut hit);
|
||||
hit
|
||||
}
|
||||
|
||||
fn walk<'a>(
|
||||
node: Node<'a>,
|
||||
bytes: &[u8],
|
||||
target: &str,
|
||||
out: &mut Option<(Node<'a>, Node<'a>)>,
|
||||
) {
|
||||
if out.is_some() {
|
||||
return;
|
||||
}
|
||||
if node.kind() == "class_declaration" {
|
||||
if let Some(body) = node
|
||||
.child_by_field_name("body")
|
||||
.or_else(|| named_child_of_kind(node, "class_body"))
|
||||
{
|
||||
let mut cur = body.walk();
|
||||
for member in body.children(&mut cur) {
|
||||
if member.kind() != "method_declaration" {
|
||||
continue;
|
||||
}
|
||||
if let Some(name) = member
|
||||
.child_by_field_name("name")
|
||||
.and_then(|n| n.utf8_text(bytes).ok())
|
||||
{
|
||||
if name == target {
|
||||
*out = Some((node, member));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut cur = node.walk();
|
||||
for child in node.children(&mut cur) {
|
||||
walk(child, bytes, target, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn named_child_of_kind<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
|
||||
let mut cur = node.walk();
|
||||
node.named_children(&mut cur).find(|c| c.kind() == kind)
|
||||
}
|
||||
|
||||
/// True when `node` is a `marker_annotation` (`@GET`) or `annotation`
|
||||
/// (`@Path("/x")`).
|
||||
pub fn is_annotation(node: Node<'_>) -> bool {
|
||||
matches!(node.kind(), "annotation" | "marker_annotation")
|
||||
}
|
||||
|
||||
/// Read the leaf annotation name (`@a.b.GetMapping` → `"GetMapping"`).
|
||||
pub fn annotation_leaf<'a>(ann: Node<'a>, bytes: &'a [u8]) -> Option<&'a str> {
|
||||
let name = ann.child_by_field_name("name")?.utf8_text(bytes).ok()?;
|
||||
Some(name.rsplit('.').next().unwrap_or(name))
|
||||
}
|
||||
|
||||
/// Extract the first quoted string argument from an annotation node,
|
||||
/// supporting both positional (`@Path("/x")`) and `value="…"` /
|
||||
/// `path="…"` keyword forms.
|
||||
pub fn annotation_string_arg(ann: Node<'_>, bytes: &[u8]) -> Option<String> {
|
||||
let args = ann.child_by_field_name("arguments")?;
|
||||
let raw = args.utf8_text(bytes).ok()?;
|
||||
// Try `value = "…"` / `path = "…"` first so the keyword form is
|
||||
// not accidentally captured by the bare-string scan.
|
||||
for key in ["value", "path"] {
|
||||
if let Some(start) = raw.find(&format!("{key} = ")).or_else(|| raw.find(&format!("{key}="))) {
|
||||
let after = &raw[start..];
|
||||
if let Some(open) = after.find('"') {
|
||||
let rest = &after[open + 1..];
|
||||
if let Some(close) = rest.find('"') {
|
||||
return Some(rest[..close].to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let open = raw.find('"')? + 1;
|
||||
let close = raw[open..].find('"')? + open;
|
||||
Some(raw[open..close].to_owned())
|
||||
}
|
||||
|
||||
/// Iterate annotations attached to a `class_declaration` or
|
||||
/// `method_declaration` node via its `modifiers` child.
|
||||
pub fn iter_annotations<'a, F>(node: Node<'a>, bytes: &'a [u8], mut visit: F)
|
||||
where
|
||||
F: FnMut(Node<'a>, &str),
|
||||
{
|
||||
let Some(modifiers) = named_child_of_kind(node, "modifiers") else {
|
||||
return;
|
||||
};
|
||||
let mut cur = modifiers.walk();
|
||||
for ann in modifiers.children(&mut cur) {
|
||||
if !is_annotation(ann) {
|
||||
continue;
|
||||
}
|
||||
if let Some(name) = annotation_leaf(ann, bytes) {
|
||||
visit(ann, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the class declaration extends a class whose simple name
|
||||
/// matches `target`. The match strips package qualifiers so
|
||||
/// `jakarta.servlet.http.HttpServlet` and bare `HttpServlet` both
|
||||
/// trip the predicate.
|
||||
pub fn class_extends(class: Node<'_>, bytes: &[u8], target: &str) -> bool {
|
||||
let Some(superclass) = class.child_by_field_name("superclass") else {
|
||||
return false;
|
||||
};
|
||||
let Ok(text) = superclass.utf8_text(bytes) else {
|
||||
return false;
|
||||
};
|
||||
let cleaned = text.trim().trim_start_matches("extends ").trim();
|
||||
let leaf = cleaned.rsplit('.').next().unwrap_or(cleaned);
|
||||
leaf.split_whitespace()
|
||||
.next()
|
||||
.unwrap_or(leaf)
|
||||
.trim_end_matches('<')
|
||||
== target
|
||||
}
|
||||
|
||||
/// Parse `method = RequestMethod.<VERB>` (or array form) from a
|
||||
/// `@RequestMapping(...)` annotation's raw arguments text.
|
||||
pub fn request_method_from_args(ann: Node<'_>, bytes: &[u8]) -> Option<HttpMethod> {
|
||||
let args = ann.child_by_field_name("arguments")?;
|
||||
let raw = args.utf8_text(bytes).ok()?;
|
||||
for verb in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"] {
|
||||
if raw.contains(&format!("RequestMethod.{verb}")) {
|
||||
return HttpMethod::from_ident(verb);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Extract `(type_simple_name, formal_name)` pairs from a
|
||||
/// `method_declaration` node. The simple type lets adapters
|
||||
/// recognise framework-implicit slots (`HttpServletRequest` /
|
||||
/// `HttpServletResponse`) and route the remaining formals to query /
|
||||
/// body params.
|
||||
pub fn method_formal_types(method: Node<'_>, bytes: &[u8]) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
let Some(params) = method.child_by_field_name("parameters") else {
|
||||
return out;
|
||||
};
|
||||
let mut cur = params.walk();
|
||||
for fp in params.named_children(&mut cur) {
|
||||
if fp.kind() != "formal_parameter" && fp.kind() != "spread_parameter" {
|
||||
continue;
|
||||
}
|
||||
let ty = fp
|
||||
.child_by_field_name("type")
|
||||
.and_then(|t| t.utf8_text(bytes).ok())
|
||||
.unwrap_or("")
|
||||
.trim();
|
||||
let name = fp
|
||||
.child_by_field_name("name")
|
||||
.and_then(|n| n.utf8_text(bytes).ok())
|
||||
.unwrap_or("")
|
||||
.trim();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let ty_leaf = ty.rsplit('.').next().unwrap_or(ty);
|
||||
let ty_simple = ty_leaf
|
||||
.split('<')
|
||||
.next()
|
||||
.unwrap_or(ty_leaf)
|
||||
.trim()
|
||||
.to_owned();
|
||||
out.push((ty_simple, name.to_owned()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Extract placeholder names from a route path template.
|
||||
///
|
||||
/// Supports two placeholder syntaxes:
|
||||
/// - JAX-RS / Spring / Micronaut: `/users/{id}` → `id`,
|
||||
/// `/users/{id:[0-9]+}` → `id`.
|
||||
/// - Servlet-mapping `*` wildcards: ignored (no name to bind).
|
||||
pub fn extract_path_placeholders(path: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let bytes = path.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'{' {
|
||||
if let Some(end) = bytes[i + 1..].iter().position(|&b| b == b'}') {
|
||||
let inner = &path[i + 1..i + 1 + end];
|
||||
let name = inner.split(':').next().unwrap_or(inner).trim();
|
||||
if !name.is_empty() && !out.iter().any(|n| n == name) {
|
||||
out.push(name.to_owned());
|
||||
}
|
||||
i += end + 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Bind formals to request slots given a route path template.
|
||||
///
|
||||
/// `HttpServletRequest` / `HttpServletResponse` / `ServletRequest` /
|
||||
/// `ServletResponse` / `HttpRequest` / `HttpResponse` go to
|
||||
/// [`ParamSource::Implicit`]. A formal whose name matches a
|
||||
/// placeholder becomes a [`ParamSource::PathSegment`]; everything
|
||||
/// else falls back to [`ParamSource::QueryParam`].
|
||||
pub fn bind_java_params(formals: &[(String, String)], path: &str) -> Vec<ParamBinding> {
|
||||
let placeholders = extract_path_placeholders(path);
|
||||
formals
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, (ty, name))| {
|
||||
let source = if is_implicit_type(ty) {
|
||||
ParamSource::Implicit
|
||||
} else if placeholders.iter().any(|p| p == name) {
|
||||
ParamSource::PathSegment(name.clone())
|
||||
} else {
|
||||
ParamSource::QueryParam(name.clone())
|
||||
};
|
||||
ParamBinding {
|
||||
index: idx,
|
||||
name: name.clone(),
|
||||
source,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_implicit_type(ty: &str) -> bool {
|
||||
matches!(
|
||||
ty,
|
||||
"HttpServletRequest"
|
||||
| "HttpServletResponse"
|
||||
| "ServletRequest"
|
||||
| "ServletResponse"
|
||||
| "HttpRequest"
|
||||
| "HttpResponse"
|
||||
| "MultiValueMap"
|
||||
| "Model"
|
||||
)
|
||||
}
|
||||
|
||||
/// Concatenate a class-level path prefix and a method-level path
|
||||
/// suffix. Strips a trailing slash from the prefix and a leading
|
||||
/// slash from the suffix to avoid `/api//x`-style joins.
|
||||
pub fn join_route_path(class_path: &str, method_path: &str) -> String {
|
||||
if class_path.is_empty() {
|
||||
return method_path.to_owned();
|
||||
}
|
||||
if method_path.is_empty() {
|
||||
return class_path.to_owned();
|
||||
}
|
||||
format!(
|
||||
"{}/{}",
|
||||
class_path.trim_end_matches('/'),
|
||||
method_path.trim_start_matches('/')
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(src: &[u8]) -> tree_sitter::Tree {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let lang = tree_sitter::Language::from(tree_sitter_java::LANGUAGE);
|
||||
parser.set_language(&lang).unwrap();
|
||||
parser.parse(src, None).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_class_and_method() {
|
||||
let src: &[u8] = b"public class V { public String run(String x) { return x; } }\n";
|
||||
let tree = parse(src);
|
||||
let (class, method) = find_class_with_method(tree.root_node(), src, "run").unwrap();
|
||||
assert_eq!(class.kind(), "class_declaration");
|
||||
assert_eq!(method.kind(), "method_declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_brace_placeholders() {
|
||||
assert_eq!(extract_path_placeholders("/users/{id}"), vec!["id"]);
|
||||
assert_eq!(
|
||||
extract_path_placeholders("/u/{id}/posts/{slug}"),
|
||||
vec!["id", "slug"]
|
||||
);
|
||||
assert_eq!(extract_path_placeholders("/u/{id:[0-9]+}"), vec!["id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_drops_double_slash() {
|
||||
assert_eq!(join_route_path("/api", "/x"), "/api/x");
|
||||
assert_eq!(join_route_path("/api/", "/x"), "/api/x");
|
||||
assert_eq!(join_route_path("", "/x"), "/x");
|
||||
assert_eq!(join_route_path("/api", ""), "/api");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_servlet_request_as_implicit() {
|
||||
let formals = vec![
|
||||
("HttpServletRequest".to_owned(), "req".to_owned()),
|
||||
("HttpServletResponse".to_owned(), "resp".to_owned()),
|
||||
];
|
||||
let bound = bind_java_params(&formals, "/x");
|
||||
assert!(matches!(bound[0].source, ParamSource::Implicit));
|
||||
assert!(matches!(bound[1].source, ParamSource::Implicit));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_extends_detects_servlet() {
|
||||
let src: &[u8] =
|
||||
b"public class V extends HttpServlet { public void doGet() {} }\n";
|
||||
let tree = parse(src);
|
||||
let (class, _) = find_class_with_method(tree.root_node(), src, "doGet").unwrap();
|
||||
assert!(class_extends(class, src, "HttpServlet"));
|
||||
assert!(!class_extends(class, src, "Object"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annotation_string_arg_pulls_first_literal() {
|
||||
let src: &[u8] =
|
||||
b"public class V { @GetMapping(\"/users/{id}\") public String run(String id) { return id; } }\n";
|
||||
let tree = parse(src);
|
||||
let (_, method) = find_class_with_method(tree.root_node(), src, "run").unwrap();
|
||||
let mut path: Option<String> = None;
|
||||
iter_annotations(method, src, |ann, name| {
|
||||
if name == "GetMapping" {
|
||||
path = annotation_string_arg(ann, src);
|
||||
}
|
||||
});
|
||||
assert_eq!(path.as_deref(), Some("/users/{id}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn method_formal_types_strips_qualifiers() {
|
||||
let src: &[u8] =
|
||||
b"public class V { public String run(java.lang.String x, int y) { return x; } }\n";
|
||||
let tree = parse(src);
|
||||
let (_, method) = find_class_with_method(tree.root_node(), src, "run").unwrap();
|
||||
let formals = method_formal_types(method, src);
|
||||
assert_eq!(
|
||||
formals,
|
||||
vec![
|
||||
("String".to_owned(), "x".to_owned()),
|
||||
("int".to_owned(), "y".to_owned()),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
175
src/dynamic/framework/adapters/java_servlet.rs
Normal file
175
src/dynamic/framework/adapters/java_servlet.rs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
//! Java Servlet [`super::super::FrameworkAdapter`] (Phase 14 — Track L.12).
|
||||
//!
|
||||
//! Recognises a `doGet` / `doPost` / `doPut` / `doDelete` / `doHead`
|
||||
//! / `doOptions` method on a class that either extends `HttpServlet`
|
||||
//! or accepts a `(HttpServletRequest, HttpServletResponse)` pair as
|
||||
//! its formal parameters — the Phase 14 servlet fixture uses the
|
||||
//! second shape because its stubs live in the default package.
|
||||
//!
|
||||
//! The route path is sourced from a class-level `@WebServlet("/x")`
|
||||
//! annotation when present; otherwise it defaults to `"/"` so the
|
||||
//! harness has a deterministic slot to drive.
|
||||
|
||||
use crate::dynamic::framework::{FrameworkAdapter, FrameworkBinding, HttpMethod, RouteShape};
|
||||
use crate::evidence::EntryKind;
|
||||
use crate::summary::FuncSummary;
|
||||
use crate::symbol::Lang;
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::java_routes::{
|
||||
annotation_string_arg, bind_java_params, class_extends, find_class_with_method,
|
||||
iter_annotations, method_formal_types, source_imports_servlet,
|
||||
};
|
||||
|
||||
pub struct JavaServletAdapter;
|
||||
|
||||
const ADAPTER_NAME: &str = "java-servlet";
|
||||
|
||||
fn servlet_method_for(name: &str) -> Option<HttpMethod> {
|
||||
match name {
|
||||
"doGet" => Some(HttpMethod::GET),
|
||||
"doPost" => Some(HttpMethod::POST),
|
||||
"doPut" => Some(HttpMethod::PUT),
|
||||
"doDelete" => Some(HttpMethod::DELETE),
|
||||
"doHead" => Some(HttpMethod::HEAD),
|
||||
"doOptions" => Some(HttpMethod::OPTIONS),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn web_servlet_path(class: Node<'_>, bytes: &[u8]) -> Option<String> {
|
||||
let mut hit: Option<String> = None;
|
||||
iter_annotations(class, bytes, |ann, name| {
|
||||
if name == "WebServlet" {
|
||||
hit = annotation_string_arg(ann, bytes);
|
||||
}
|
||||
});
|
||||
hit
|
||||
}
|
||||
|
||||
fn formals_look_like_servlet(formals: &[(String, String)]) -> bool {
|
||||
formals
|
||||
.iter()
|
||||
.any(|(ty, _)| ty == "HttpServletRequest" || ty == "ServletRequest")
|
||||
}
|
||||
|
||||
impl FrameworkAdapter for JavaServletAdapter {
|
||||
fn name(&self) -> &'static str {
|
||||
ADAPTER_NAME
|
||||
}
|
||||
|
||||
fn lang(&self) -> Lang {
|
||||
Lang::Java
|
||||
}
|
||||
|
||||
fn detect(
|
||||
&self,
|
||||
summary: &FuncSummary,
|
||||
ast: Node<'_>,
|
||||
file_bytes: &[u8],
|
||||
) -> Option<FrameworkBinding> {
|
||||
if !source_imports_servlet(file_bytes) {
|
||||
return None;
|
||||
}
|
||||
let http_method = servlet_method_for(&summary.name)?;
|
||||
let (class, method) = find_class_with_method(ast, file_bytes, &summary.name)?;
|
||||
let formals = method_formal_types(method, file_bytes);
|
||||
let extends_servlet = class_extends(class, file_bytes, "HttpServlet")
|
||||
|| class_extends(class, file_bytes, "GenericServlet");
|
||||
if !extends_servlet && !formals_look_like_servlet(&formals) {
|
||||
return None;
|
||||
}
|
||||
let path = web_servlet_path(class, file_bytes).unwrap_or_else(|| "/".to_owned());
|
||||
let request_params = bind_java_params(&formals, &path);
|
||||
Some(FrameworkBinding {
|
||||
adapter: ADAPTER_NAME.to_owned(),
|
||||
kind: EntryKind::HttpRoute,
|
||||
route: Some(RouteShape {
|
||||
method: http_method,
|
||||
path,
|
||||
}),
|
||||
request_params,
|
||||
response_writer: None,
|
||||
middleware: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::dynamic::framework::ParamSource;
|
||||
|
||||
fn parse(src: &[u8]) -> tree_sitter::Tree {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let lang = tree_sitter::Language::from(tree_sitter_java::LANGUAGE);
|
||||
parser.set_language(&lang).unwrap();
|
||||
parser.parse(src, None).unwrap()
|
||||
}
|
||||
|
||||
fn summary(name: &str) -> FuncSummary {
|
||||
FuncSummary {
|
||||
name: name.into(),
|
||||
lang: "java".into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_extends_http_servlet_doget() {
|
||||
let src: &[u8] = b"import jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\n@WebServlet(\"/admin\")\npublic class Admin extends HttpServlet {\n public void doGet(HttpServletRequest req, HttpServletResponse resp) {}\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaServletAdapter
|
||||
.detect(&summary("doGet"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
assert_eq!(binding.adapter, "java-servlet");
|
||||
let route = binding.route.unwrap();
|
||||
assert_eq!(route.method, HttpMethod::GET);
|
||||
assert_eq!(route.path, "/admin");
|
||||
assert!(binding
|
||||
.request_params
|
||||
.iter()
|
||||
.all(|p| matches!(p.source, ParamSource::Implicit)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_dopost_with_servlet_request_param() {
|
||||
// Default-package fixture path: no `extends HttpServlet`, but
|
||||
// the method's formal parameters carry the canonical types so
|
||||
// the harness can still wire a stub.
|
||||
let src: &[u8] = b"public class V {\n public void doPost(HttpServletRequest req, HttpServletResponse resp) {}\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaServletAdapter
|
||||
.detect(&summary("doPost"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
assert_eq!(binding.route.unwrap().method, HttpMethod::POST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_path_to_slash_without_webservlet() {
|
||||
let src: &[u8] = b"public class V extends HttpServlet {\n public void doGet(HttpServletRequest req, HttpServletResponse resp) {}\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaServletAdapter
|
||||
.detect(&summary("doGet"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
assert_eq!(binding.route.unwrap().path, "/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_when_method_name_is_not_a_servlet_verb() {
|
||||
let src: &[u8] = b"public class V extends HttpServlet { public void run(HttpServletRequest req) {} }\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaServletAdapter
|
||||
.detect(&summary("run"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_when_no_servlet_signature_markers() {
|
||||
let src: &[u8] = b"public class V {\n public void doGet(String x) {}\n}\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaServletAdapter
|
||||
.detect(&summary("doGet"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
236
src/dynamic/framework/adapters/java_spring.rs
Normal file
236
src/dynamic/framework/adapters/java_spring.rs
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
//! Java Spring [`super::super::FrameworkAdapter`] (Phase 14 — Track L.12).
|
||||
//!
|
||||
//! Recognises `@RestController` / `@Controller` on a class plus a
|
||||
//! handler method annotated with `@GetMapping("/path")` /
|
||||
//! `@PostMapping` / `@PutMapping` / `@PatchMapping` / `@DeleteMapping`
|
||||
//! / `@RequestMapping(value="/path", method=RequestMethod.POST)`.
|
||||
//! Class-level `@RequestMapping(prefix)` is concatenated with the
|
||||
//! method-level path so `@RequestMapping("/api") + @GetMapping("/x")`
|
||||
//! produces `"/api/x"`.
|
||||
|
||||
use crate::dynamic::framework::{FrameworkAdapter, FrameworkBinding, HttpMethod, RouteShape};
|
||||
use crate::evidence::EntryKind;
|
||||
use crate::summary::FuncSummary;
|
||||
use crate::symbol::Lang;
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::java_routes::{
|
||||
annotation_string_arg, bind_java_params, find_class_with_method, iter_annotations,
|
||||
join_route_path, method_formal_types, request_method_from_args, source_imports_quarkus,
|
||||
source_imports_spring,
|
||||
};
|
||||
|
||||
pub struct JavaSpringAdapter;
|
||||
|
||||
const ADAPTER_NAME: &str = "java-spring";
|
||||
|
||||
fn mapping_method(name: &str) -> Option<HttpMethod> {
|
||||
match name {
|
||||
"GetMapping" => Some(HttpMethod::GET),
|
||||
"PostMapping" => Some(HttpMethod::POST),
|
||||
"PutMapping" => Some(HttpMethod::PUT),
|
||||
"PatchMapping" => Some(HttpMethod::PATCH),
|
||||
"DeleteMapping" => Some(HttpMethod::DELETE),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn class_is_controller(class: Node<'_>, bytes: &[u8]) -> bool {
|
||||
let mut hit = false;
|
||||
iter_annotations(class, bytes, |_ann, name| {
|
||||
if matches!(name, "RestController" | "Controller") {
|
||||
hit = true;
|
||||
}
|
||||
});
|
||||
hit
|
||||
}
|
||||
|
||||
fn class_route_prefix(class: Node<'_>, bytes: &[u8]) -> String {
|
||||
let mut prefix = String::new();
|
||||
iter_annotations(class, bytes, |ann, name| {
|
||||
if name == "RequestMapping" {
|
||||
if let Some(p) = annotation_string_arg(ann, bytes) {
|
||||
prefix = p;
|
||||
}
|
||||
}
|
||||
});
|
||||
prefix
|
||||
}
|
||||
|
||||
fn method_route(
|
||||
method: Node<'_>,
|
||||
bytes: &[u8],
|
||||
) -> Option<(HttpMethod, String)> {
|
||||
let mut hit: Option<(HttpMethod, String)> = None;
|
||||
iter_annotations(method, bytes, |ann, name| {
|
||||
if hit.is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(m) = mapping_method(name) {
|
||||
let path = annotation_string_arg(ann, bytes).unwrap_or_default();
|
||||
hit = Some((m, path));
|
||||
return;
|
||||
}
|
||||
if name == "RequestMapping" {
|
||||
let path = annotation_string_arg(ann, bytes).unwrap_or_default();
|
||||
let m = request_method_from_args(ann, bytes).unwrap_or(HttpMethod::GET);
|
||||
hit = Some((m, path));
|
||||
}
|
||||
});
|
||||
hit
|
||||
}
|
||||
|
||||
impl FrameworkAdapter for JavaSpringAdapter {
|
||||
fn name(&self) -> &'static str {
|
||||
ADAPTER_NAME
|
||||
}
|
||||
|
||||
fn lang(&self) -> Lang {
|
||||
Lang::Java
|
||||
}
|
||||
|
||||
fn detect(
|
||||
&self,
|
||||
summary: &FuncSummary,
|
||||
ast: Node<'_>,
|
||||
file_bytes: &[u8],
|
||||
) -> Option<FrameworkBinding> {
|
||||
if !source_imports_spring(file_bytes) {
|
||||
return None;
|
||||
}
|
||||
// Quarkus / JAX-RS files often re-use `@Path` but the brief
|
||||
// routes those through `java-quarkus`; skip when the file
|
||||
// looks like Quarkus and is not also a Spring controller.
|
||||
if source_imports_quarkus(file_bytes) && !file_bytes.windows(15).any(|w| w == b"@RestController") && !file_bytes.windows(11).any(|w| w == b"@Controller") {
|
||||
return None;
|
||||
}
|
||||
let (class, method) = find_class_with_method(ast, file_bytes, &summary.name)?;
|
||||
if !class_is_controller(class, file_bytes) {
|
||||
return None;
|
||||
}
|
||||
let class_prefix = class_route_prefix(class, file_bytes);
|
||||
// Method-level mapping wins. Falls back to (GET, "") when
|
||||
// the method has no mapping annotation but the enclosing
|
||||
// class has a `@RequestMapping(prefix)` — Spring routes the
|
||||
// public method under the class prefix. Skip the binding
|
||||
// when neither the method nor the class declares a route
|
||||
// path so a plain `@Controller` helper class does not
|
||||
// hijack the registry.
|
||||
let (http_method, method_path) = match method_route(method, file_bytes) {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
if class_prefix.is_empty() {
|
||||
return None;
|
||||
}
|
||||
(HttpMethod::GET, String::new())
|
||||
}
|
||||
};
|
||||
let path = join_route_path(&class_prefix, &method_path);
|
||||
let formals = method_formal_types(method, file_bytes);
|
||||
let request_params = bind_java_params(&formals, &path);
|
||||
|
||||
Some(FrameworkBinding {
|
||||
adapter: ADAPTER_NAME.to_owned(),
|
||||
kind: EntryKind::HttpRoute,
|
||||
route: Some(RouteShape {
|
||||
method: http_method,
|
||||
path,
|
||||
}),
|
||||
request_params,
|
||||
response_writer: None,
|
||||
middleware: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::dynamic::framework::ParamSource;
|
||||
|
||||
fn parse(src: &[u8]) -> tree_sitter::Tree {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let lang = tree_sitter::Language::from(tree_sitter_java::LANGUAGE);
|
||||
parser.set_language(&lang).unwrap();
|
||||
parser.parse(src, None).unwrap()
|
||||
}
|
||||
|
||||
fn summary(name: &str) -> FuncSummary {
|
||||
FuncSummary {
|
||||
name: name.into(),
|
||||
lang: "java".into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_get_mapping_with_class_prefix() {
|
||||
let src: &[u8] = b"@RestController\n@RequestMapping(\"/api\")\npublic class Users {\n @GetMapping(\"/{id}\")\n public String show(String id) { return id; }\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaSpringAdapter
|
||||
.detect(&summary("show"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
assert_eq!(binding.adapter, "java-spring");
|
||||
assert_eq!(binding.kind, EntryKind::HttpRoute);
|
||||
let route = binding.route.expect("route");
|
||||
assert_eq!(route.method, HttpMethod::GET);
|
||||
assert_eq!(route.path, "/api/{id}");
|
||||
let id_binding = binding
|
||||
.request_params
|
||||
.iter()
|
||||
.find(|p| p.name == "id")
|
||||
.unwrap();
|
||||
assert!(matches!(id_binding.source, ParamSource::PathSegment(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_request_mapping_with_explicit_method() {
|
||||
let src: &[u8] = b"@Controller\npublic class C {\n @RequestMapping(value=\"/save\", method=RequestMethod.POST)\n public String save(String payload) { return payload; }\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaSpringAdapter
|
||||
.detect(&summary("save"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
let route = binding.route.unwrap();
|
||||
assert_eq!(route.method, HttpMethod::POST);
|
||||
assert_eq!(route.path, "/save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_on_bare_controller_without_prefix() {
|
||||
let src: &[u8] =
|
||||
b"@RestController\npublic class C {\n @GetMapping(\"/x\")\n public String x() { return \"\"; }\n}\n";
|
||||
let tree = parse(src);
|
||||
let binding = JavaSpringAdapter
|
||||
.detect(&summary("x"), tree.root_node(), src)
|
||||
.expect("binding");
|
||||
assert_eq!(binding.route.unwrap().path, "/x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_when_class_is_not_controller() {
|
||||
let src: &[u8] =
|
||||
b"@RequestMapping(\"/api\")\npublic class C {\n @GetMapping(\"/x\")\n public String x() { return \"\"; }\n}\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaSpringAdapter
|
||||
.detect(&summary("x"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_quarkus_file() {
|
||||
let src: &[u8] = b"import io.quarkus.runtime.Quarkus;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\n@Path(\"/run\")\npublic class Q {\n @GET\n public String run() { return \"\"; }\n}\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaSpringAdapter
|
||||
.detect(&summary("run"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_plain_function() {
|
||||
let src: &[u8] = b"public class C { public int add(int a, int b) { return a + b; } }\n";
|
||||
let tree = parse(src);
|
||||
assert!(JavaSpringAdapter
|
||||
.detect(&summary("add"), tree.root_node(), src)
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,11 @@ pub mod header_python;
|
|||
pub mod header_ruby;
|
||||
pub mod header_rust;
|
||||
pub mod java_deserialize;
|
||||
pub mod java_micronaut;
|
||||
pub mod java_quarkus;
|
||||
pub mod java_routes;
|
||||
pub mod java_servlet;
|
||||
pub mod java_spring;
|
||||
pub mod java_thymeleaf;
|
||||
pub mod js_express;
|
||||
pub mod js_fastify;
|
||||
|
|
@ -68,6 +73,10 @@ pub use header_python::HeaderPythonAdapter;
|
|||
pub use header_ruby::HeaderRubyAdapter;
|
||||
pub use header_rust::HeaderRustAdapter;
|
||||
pub use java_deserialize::JavaDeserializeAdapter;
|
||||
pub use java_micronaut::JavaMicronautAdapter;
|
||||
pub use java_quarkus::JavaQuarkusAdapter;
|
||||
pub use java_servlet::JavaServletAdapter;
|
||||
pub use java_spring::JavaSpringAdapter;
|
||||
pub use java_thymeleaf::JavaThymeleafAdapter;
|
||||
pub use js_express::JsExpressAdapter;
|
||||
pub use js_fastify::JsFastifyAdapter;
|
||||
|
|
|
|||
|
|
@ -214,25 +214,30 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn registry_baseline_after_phase_13() {
|
||||
// Phase 13 (Track L.11) adds four JS framework adapters
|
||||
// (`js-express`, `js-fastify`, `js-koa`, `js-nest`) to the
|
||||
// JavaScript slice, growing it from 7 → 11; the TypeScript
|
||||
// slice gains `ts-nest`, growing it from 3 → 4. Phase 12
|
||||
// (Track L.10) baseline for Python / Java / Php / Ruby / Go /
|
||||
// Rust remains unchanged: Python 11, Java 7, Php 7, Ruby 5,
|
||||
fn registry_baseline_after_phase_14() {
|
||||
// Phase 14 (Track L.12) adds four Java framework adapters
|
||||
// (`java-micronaut`, `java-quarkus`, `java-servlet`,
|
||||
// `java-spring`) to the Java slice, growing it from 7 → 11.
|
||||
// The Phase 13 baseline for the other languages stays put:
|
||||
// Python 11, Php 7, Ruby 5, JavaScript 11, TypeScript 4,
|
||||
// Go 3, Rust 2. C / Cpp stay empty.
|
||||
for lang in [Lang::Java, Lang::Php] {
|
||||
let registered = registry::adapters_for(lang);
|
||||
assert_eq!(
|
||||
registered.len(),
|
||||
7,
|
||||
"{:?} must have the J.1+J.2+J.3+J.4+J.5+J.6+J.7 adapters",
|
||||
lang,
|
||||
);
|
||||
for adapter in registered {
|
||||
assert_eq!(adapter.lang(), lang);
|
||||
}
|
||||
let java_registered = registry::adapters_for(Lang::Java);
|
||||
assert_eq!(
|
||||
java_registered.len(),
|
||||
11,
|
||||
"Java must have J.1+J.2+J.3+J.4+J.5+J.6+J.7 (7) + L.12 Spring/Quarkus/Micronaut/Servlet (4)",
|
||||
);
|
||||
for adapter in java_registered {
|
||||
assert_eq!(adapter.lang(), Lang::Java);
|
||||
}
|
||||
let php_registered = registry::adapters_for(Lang::Php);
|
||||
assert_eq!(
|
||||
php_registered.len(),
|
||||
7,
|
||||
"Php must have the J.1+J.2+J.3+J.4+J.5+J.6+J.7 adapters",
|
||||
);
|
||||
for adapter in php_registered {
|
||||
assert_eq!(adapter.lang(), Lang::Php);
|
||||
}
|
||||
let python_registered = registry::adapters_for(Lang::Python);
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -53,6 +53,10 @@ static CPP: &[&dyn FrameworkAdapter] = &[];
|
|||
static JAVA: &[&dyn FrameworkAdapter] = &[
|
||||
&super::adapters::HeaderJavaAdapter,
|
||||
&super::adapters::JavaDeserializeAdapter,
|
||||
&super::adapters::JavaMicronautAdapter,
|
||||
&super::adapters::JavaQuarkusAdapter,
|
||||
&super::adapters::JavaServletAdapter,
|
||||
&super::adapters::JavaSpringAdapter,
|
||||
&super::adapters::JavaThymeleafAdapter,
|
||||
&super::adapters::LdapSpringAdapter,
|
||||
&super::adapters::RedirectJavaAdapter,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue