forked from modelcontextprotocol/java-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTomcatTestUtil.java
More file actions
64 lines (49 loc) · 1.91 KB
/
TomcatTestUtil.java
File metadata and controls
64 lines (49 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* Copyright 2025 - 2025 the original author or authors.
*/
package io.modelcontextprotocol.server;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* @author Christian Tzolov
*/
public class TomcatTestUtil {
TomcatTestUtil() {
// Prevent instantiation
}
public record TomcatServer(Tomcat tomcat, AnnotationConfigWebApplicationContext appContext) {
}
public static TomcatServer createTomcatServer(String contextPath, int port, Class<?> componentClass) {
// Set up Tomcat first
var tomcat = new Tomcat();
tomcat.setPort(port);
// Set Tomcat base directory to java.io.tmpdir to avoid permission issues
String baseDir = System.getProperty("java.io.tmpdir");
tomcat.setBaseDir(baseDir);
// Use the same directory for document base
Context context = tomcat.addContext(contextPath, baseDir);
// Create and configure Spring WebMvc context
var appContext = new AnnotationConfigWebApplicationContext();
appContext.register(componentClass);
appContext.setServletContext(context.getServletContext());
appContext.refresh();
// Create DispatcherServlet with our Spring context
DispatcherServlet dispatcherServlet = new DispatcherServlet(appContext);
// Add servlet to Tomcat and get the wrapper
var wrapper = Tomcat.addServlet(context, "dispatcherServlet", dispatcherServlet);
wrapper.setLoadOnStartup(1);
wrapper.setAsyncSupported(true);
context.addServletMappingDecoded("/*", "dispatcherServlet");
try {
// Configure and start the connector with async support
var connector = tomcat.getConnector();
connector.setAsyncTimeout(3000); // 3 seconds timeout for async requests
}
catch (Exception e) {
throw new RuntimeException("Failed to start Tomcat", e);
}
return new TomcatServer(tomcat, appContext);
}
}