|
| 1 | +package ir.moke.module.tomcat; |
| 2 | + |
| 3 | +import ir.moke.module.tomcat.servlet.HelloServlet; |
| 4 | +import org.apache.catalina.Context; |
| 5 | +import org.apache.catalina.startup.Tomcat; |
| 6 | +import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | + |
| 10 | +import java.io.IOException; |
| 11 | +import java.nio.file.Files; |
| 12 | +import java.nio.file.Path; |
| 13 | +import java.util.Comparator; |
| 14 | +import java.util.Optional; |
| 15 | +import java.util.stream.Stream; |
| 16 | + |
| 17 | +public class HttpContainer { |
| 18 | + public static final HttpContainer instance = new HttpContainer(); |
| 19 | + private static final Logger logger = LoggerFactory.getLogger(HttpContainer.class); |
| 20 | + private static final String contextPath = "/app"; |
| 21 | + private static final String host = System.getenv("HTTP_SERVER_HOST"); |
| 22 | + private static final String port = System.getenv("HTTP_SERVER_PORT"); |
| 23 | + private static final String appBase = "/tmp/tomcat"; |
| 24 | + private static Tomcat tomcat; |
| 25 | + |
| 26 | + private HttpContainer() { |
| 27 | + createAppBaseDirectory(); |
| 28 | + TomcatURLStreamHandlerFactory.disable(); |
| 29 | + tomcat = new Tomcat(); |
| 30 | + tomcat.setHostname(Optional.ofNullable(host).orElse("0.0.0.0")); |
| 31 | + tomcat.setPort(Integer.parseInt(Optional.ofNullable(port).orElse("8080"))); |
| 32 | + tomcat.setBaseDir(appBase); |
| 33 | + |
| 34 | + Context context = tomcat.addWebapp(contextPath, appBase); |
| 35 | + |
| 36 | + tomcat.addServlet(contextPath, "hello", new HelloServlet()); |
| 37 | + context.addServletMappingDecoded("/hello", "hello"); |
| 38 | + } |
| 39 | + |
| 40 | + private static void createAppBaseDirectory() { |
| 41 | + try { |
| 42 | + Path appBasePath = Path.of(appBase); |
| 43 | + if (!Files.exists(appBasePath)) { |
| 44 | + Files.createDirectory(appBasePath); |
| 45 | + } |
| 46 | + } catch (IOException e) { |
| 47 | + throw new RuntimeException(e); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public void start() { |
| 52 | + try { |
| 53 | + tomcat.getConnector(); |
| 54 | + tomcat.start(); |
| 55 | + logger.info("Tomcat server started"); |
| 56 | + tomcat.getServer().await(); |
| 57 | + } catch (Exception e) { |
| 58 | + logger.error("Tomcat error", e); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + public void stop() { |
| 63 | + try (Stream<Path> pathStream = Files.walk(Path.of(appBase))) { |
| 64 | + pathStream.sorted(Comparator.reverseOrder()) |
| 65 | + .map(Path::toFile) |
| 66 | + .forEach(java.io.File::delete); |
| 67 | + |
| 68 | + tomcat.stop(); |
| 69 | + logger.info("Tomcat server stopped"); |
| 70 | + } catch (Exception e) { |
| 71 | + logger.error("Tomcat error", e); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments