├── src └── main │ ├── resources │ ├── META-INF │ │ ├── services │ │ │ └── javax.servlet.ServletContainerInitializer │ │ └── resources │ │ │ ├── index.html │ │ │ └── test.jsp │ └── WEB-INF │ │ └── web.xml │ └── java │ └── io │ └── github │ └── hengyunabc │ ├── tomcat │ ├── TomcatUtil.java │ ├── WebXmlMountListener.java │ ├── EmbededContextConfig.java │ └── EmbededStandardJarScanner.java │ ├── HelloServlet.java │ ├── AnnotationServlet.java │ ├── CustomServletContainerInitializer.java │ └── Main.java ├── .gitignore ├── README.md ├── pom.xml └── LICENSE.txt /src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer: -------------------------------------------------------------------------------- 1 | io.github.hengyunabc.CustomServletContainerInitializer -------------------------------------------------------------------------------- /src/main/resources/META-INF/resources/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Home 6 | 7 | 8 |

hello, index.

9 | 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | *.sw? 3 | .#* 4 | *# 5 | *~ 6 | /build 7 | /code 8 | .classpath 9 | .project 10 | .settings 11 | .metadata 12 | .factorypath 13 | .recommenders 14 | bin 15 | build 16 | lib/ 17 | target 18 | .factorypath 19 | .springBeans 20 | interpolated*.xml 21 | dependency-reduced-pom.xml 22 | build.log 23 | _site/ 24 | .*.md.html 25 | manifest.yml 26 | MANIFEST.MF 27 | settings.xml 28 | activemq-data 29 | overridedb.* 30 | *.iml 31 | *.ipr 32 | *.iws 33 | .idea 34 | *.jar 35 | .DS_Store 36 | .factorypath 37 | -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/tomcat/TomcatUtil.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc.tomcat; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | /** 7 | * 8 | * @author hengyunabc 9 | * 10 | */ 11 | public abstract class TomcatUtil { 12 | 13 | public static File createTempDir(String prefix, int port) throws IOException { 14 | File tempDir = File.createTempFile(prefix + ".", "." + port); 15 | tempDir.delete(); 16 | tempDir.mkdir(); 17 | tempDir.deleteOnExit(); 18 | return tempDir; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/resources/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Jsp 8 | 9 | 10 | 11 | <% 12 | System.out.println("test jsp"); 13 | 14 | double number = Math.random(); 15 | %> 16 | 17 |

18 | Math.random(): 19 | <%=number%> 20 |

21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/HelloServlet.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.http.HttpServlet; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | /** 10 | * 11 | * @author hengyunabc 12 | * 13 | */ 14 | public class HelloServlet extends HttpServlet { 15 | 16 | private static final long serialVersionUID = 5701117482475493759L; 17 | 18 | @Override 19 | protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { 20 | res.getWriter().append("hello").close(); 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/resources/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | hello 8 | io.github.hengyunabc.HelloServlet 9 | 10 | 11 | hello 12 | /hello 13 | 14 | 15 | 16 | index.html 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/AnnotationServlet.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.annotation.WebServlet; 6 | import javax.servlet.http.HttpServlet; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | /** 11 | * 12 | * @author hengyunabc 13 | * 14 | */ 15 | @WebServlet(name = "annotation", urlPatterns = { "/annotation" }) 16 | public class AnnotationServlet extends HttpServlet { 17 | private static final long serialVersionUID = -7327285584754507249L; 18 | 19 | @Override 20 | protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { 21 | res.getWriter().append("aaa annotation").close(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/CustomServletContainerInitializer.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc; 2 | 3 | import java.util.Set; 4 | 5 | import javax.servlet.ServletContainerInitializer; 6 | import javax.servlet.ServletContext; 7 | import javax.servlet.ServletException; 8 | import javax.servlet.annotation.HandlesTypes; 9 | import javax.servlet.http.HttpServlet; 10 | 11 | /** 12 | * 13 | * @author hengyunabc 14 | * 15 | */ 16 | @HandlesTypes({ HttpServlet.class }) 17 | public class CustomServletContainerInitializer implements ServletContainerInitializer { 18 | 19 | @Override 20 | public void onStartup(Set> set, ServletContext ctx) throws ServletException { 21 | System.out.println("CustomServletContainerInitializer.onStartup"); 22 | if (set != null) { 23 | for (Class c : set) { 24 | System.out.println(c.getName()); 25 | } 26 | } 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/Main.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | 7 | import org.apache.catalina.Context; 8 | import org.apache.catalina.Host; 9 | import org.apache.catalina.LifecycleException; 10 | import org.apache.catalina.startup.Tomcat; 11 | 12 | import io.github.hengyunabc.tomcat.EmbededContextConfig; 13 | import io.github.hengyunabc.tomcat.EmbededStandardJarScanner; 14 | import io.github.hengyunabc.tomcat.TomcatUtil; 15 | import io.github.hengyunabc.tomcat.WebXmlMountListener; 16 | 17 | /** 18 | * 19 | * @author hengyunabc 20 | * 21 | */ 22 | public class Main { 23 | 24 | public static void main(String[] args) throws ServletException, LifecycleException, IOException { 25 | 26 | String hostName = "localhost"; 27 | int port = 8080; 28 | String contextPath = ""; 29 | 30 | String tomcatBaseDir = TomcatUtil.createTempDir("tomcat", port).getAbsolutePath(); 31 | String contextDocBase = TomcatUtil.createTempDir("tomcat-docBase", port).getAbsolutePath(); 32 | 33 | Tomcat tomcat = new Tomcat(); 34 | tomcat.setBaseDir(tomcatBaseDir); 35 | 36 | tomcat.setPort(port); 37 | tomcat.setHostname(hostName); 38 | 39 | Host host = tomcat.getHost(); 40 | Context context = tomcat.addWebapp(host, contextPath, contextDocBase, new EmbededContextConfig()); 41 | 42 | context.setJarScanner(new EmbededStandardJarScanner()); 43 | 44 | ClassLoader classLoader = Main.class.getClassLoader(); 45 | context.setParentClassLoader(classLoader); 46 | 47 | // context load WEB-INF/web.xml from classpath 48 | context.addLifecycleListener(new WebXmlMountListener()); 49 | 50 | tomcat.start(); 51 | tomcat.getServer().await(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # executable-embeded-tomcat-sample 2 | 3 | ## Features 4 | 5 | * Support web.xml 6 | 7 | spring boot is a great project, but it don't support web.xml. This project support traditional web.xml. 8 | 9 | * Support Fat jar 10 | 11 | By `spring-boot-maven-plugin`, the project can be packaged into an executable jar. 12 | 13 | You can also use `maven-assembly-plugin/jar-with-dependencies`, but `spring-boot-maven-plugin` is a better choice. 14 | 15 | * Run in IDE 16 | 17 | 18 | ## Sample 19 | 20 | Run main class `io.github.hengyunabc.Main` in your IDE, or 21 | 22 | ```bash 23 | mvn clean package 24 | 25 | java -jar target/executable-embeded-tomcat-sample-0.0.1-SNAPSHOT.jar 26 | ``` 27 | 28 | Open the following link in your browser: 29 | 30 | http://localhost:8080/test.jsp 31 | 32 | http://localhost:8080/hello 33 | 34 | http://localhost:8080/annotation 35 | 36 | ## How to migrate from a webapp project 37 | 38 | It is very simple. 39 | 40 | 1. add embeded tomcat maven dependencies into your pom.xml 41 | 42 | 1. move `src/main/webapp/WEB-INF` to `src/main/resources/WEB-INF`, move all files under `src/main/webapp` to `src/main/META-INF/resources`. 43 | 44 | > according to servlet 3.0, ServletContext can get static content from `META-INF/resource`. 45 | 46 | 1. add a main class, start your embeded tomcat. 47 | 48 | ## Others 49 | 50 | http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/basic_app_embedded_tomcat/basic_app-tomcat-embedded.html 51 | 52 | > A sample from oracle, but it do not support web.xml, and do not support run in IDE. 53 | 54 | https://github.com/kui/executable-war-sample 55 | 56 | > Another sample, **it has security problems**. people can access your .class file through http!! 57 | 58 | ## License 59 | Apache License V2 60 | -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/tomcat/WebXmlMountListener.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc.tomcat; 2 | 3 | import java.net.MalformedURLException; 4 | import java.net.URL; 5 | 6 | import org.apache.catalina.Context; 7 | import org.apache.catalina.Lifecycle; 8 | import org.apache.catalina.LifecycleEvent; 9 | import org.apache.catalina.LifecycleListener; 10 | import org.apache.catalina.WebResourceRoot; 11 | import org.apache.catalina.WebResourceRoot.ResourceSetType; 12 | import org.apache.catalina.webresources.StandardRoot; 13 | 14 | /** 15 | *
16 |  *	find "WEB-INF/web.xml" from app classpath, and mount into WebResourceRoot.
17 |  * 
18 | * 19 | * @author hengyunabc 20 | * 21 | */ 22 | public class WebXmlMountListener implements LifecycleListener { 23 | 24 | @Override 25 | public void lifecycleEvent(LifecycleEvent event) { 26 | if (event.getType().equals(Lifecycle.BEFORE_START_EVENT)) { 27 | Context context = (Context) event.getLifecycle(); 28 | WebResourceRoot resources = context.getResources(); 29 | if (resources == null) { 30 | resources = new StandardRoot(context); 31 | context.setResources(resources); 32 | } 33 | 34 | /** 35 | *
36 | 			 * when run as embeded tomcat, context.getParentClassLoader() is AppClassLoader,
37 | 			 * so it can load "WEB-INF/web.xml" from app classpath.
38 | 			 * 
39 | */ 40 | URL resource = context.getParentClassLoader().getResource("WEB-INF/web.xml"); 41 | if (resource != null) { 42 | String webXmlUrlString = resource.toString(); 43 | URL root; 44 | try { 45 | root = new URL(webXmlUrlString.substring(0, webXmlUrlString.length() - "WEB-INF/web.xml".length())); 46 | resources.createWebResourceSet(ResourceSetType.RESOURCE_JAR, "/WEB-INF", root, "/WEB-INF"); 47 | } catch (MalformedURLException e) { 48 | // ignore 49 | } 50 | } 51 | } 52 | 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/tomcat/EmbededContextConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc.tomcat; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.URISyntaxException; 6 | import java.net.URL; 7 | import java.util.Set; 8 | 9 | import org.apache.catalina.WebResourceRoot; 10 | import org.apache.catalina.startup.ContextConfig; 11 | import org.apache.juli.logging.Log; 12 | import org.apache.juli.logging.LogFactory; 13 | import org.apache.tomcat.util.descriptor.web.WebXml; 14 | import org.apache.tomcat.util.scan.Jar; 15 | import org.apache.tomcat.util.scan.JarFactory; 16 | 17 | /** 18 | *
19 |  * 
20 |  * Support jar in jar. when boot by spring boot loader, jar url will be: fat.jar!/lib/!/test.jar!/ .
21 |  * 
22 | * 23 | * @author hengyunabc 24 | * 25 | */ 26 | public class EmbededContextConfig extends ContextConfig { 27 | private static final Log log = LogFactory.getLog(ContextConfig.class); 28 | 29 | /** 30 | * Scan JARs that contain web-fragment.xml files that will be used to 31 | * configure this application to see if they also contain static resources. 32 | * If static resources are found, add them to the context. Resources are 33 | * added in web-fragment.xml priority order. 34 | */ 35 | @Override 36 | protected void processResourceJARs(Set fragments) { 37 | for (WebXml fragment : fragments) { 38 | URL url = fragment.getURL(); 39 | 40 | try { 41 | String urlString = url.toString(); 42 | if (isInsideNestedJar(urlString)) { 43 | // It's a nested jar but we now don't want the suffix 44 | // because 45 | // Tomcat 46 | // is going to try and locate it as a root URL (not the 47 | // resource 48 | // inside it) 49 | urlString = urlString.substring(0, urlString.length() - 2); 50 | } 51 | url = new URL(urlString); 52 | 53 | if ("jar".equals(url.getProtocol())) { 54 | try (Jar jar = JarFactory.newInstance(url)) { 55 | jar.nextEntry(); 56 | String entryName = jar.getEntryName(); 57 | while (entryName != null) { 58 | if (entryName.startsWith("META-INF/resources/")) { 59 | context.getResources().createWebResourceSet( 60 | WebResourceRoot.ResourceSetType.RESOURCE_JAR, "/", url, "/META-INF/resources"); 61 | break; 62 | } 63 | jar.nextEntry(); 64 | entryName = jar.getEntryName(); 65 | } 66 | } 67 | } else if ("file".equals(url.getProtocol())) { 68 | File file = new File(url.toURI()); 69 | File resources = new File(file, "META-INF/resources/"); 70 | if (resources.isDirectory()) { 71 | context.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.RESOURCE_JAR, "/", 72 | resources.getAbsolutePath(), null, "/"); 73 | } 74 | } 75 | } catch (IOException ioe) { 76 | log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); 77 | } catch (URISyntaxException e) { 78 | log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); 79 | } 80 | } 81 | } 82 | 83 | private static boolean isInsideNestedJar(String dir) { 84 | return dir.indexOf("!/") < dir.lastIndexOf("!/"); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | io.github.hengyunabc 5 | executable-embeded-tomcat-sample 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | 1.7 10 | 1.7 11 | 1.7 12 | UTF-8 13 | UTF-8 14 | 15 | 8.0.32 16 | 17 | 18 | 1.0.13 19 | 1.7.5 20 | 21 | 22 | 4.11 23 | 24 | 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-maven-plugin 31 | 1.3.3.RELEASE 32 | 33 | 34 | package 35 | 36 | repackage 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.apache.tomcat.embed 48 | tomcat-embed-core 49 | ${tomcat.version} 50 | 51 | 52 | org.apache.tomcat.embed 53 | tomcat-embed-el 54 | ${tomcat.version} 55 | 56 | 57 | org.apache.tomcat.embed 58 | tomcat-embed-logging-juli 59 | ${tomcat.version} 60 | 61 | 62 | org.apache.tomcat.embed 63 | tomcat-embed-websocket 64 | ${tomcat.version} 65 | 66 | 67 | org.apache.tomcat.embed 68 | tomcat-embed-jasper 69 | ${tomcat.version} 70 | 71 | 72 | 73 | org.slf4j 74 | slf4j-api 75 | ${slf4j.version} 76 | 77 | 78 | 79 | org.slf4j 80 | jcl-over-slf4j 81 | ${slf4j.version} 82 | test 83 | 84 | 85 | org.slf4j 86 | log4j-over-slf4j 87 | ${slf4j.version} 88 | test 89 | 90 | 91 | ch.qos.logback 92 | logback-core 93 | ${logback.version} 94 | test 95 | 96 | 97 | ch.qos.logback 98 | logback-classic 99 | ${logback.version} 100 | test 101 | 102 | 103 | 104 | 105 | junit 106 | junit 107 | ${junit.version} 108 | test 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /src/main/java/io/github/hengyunabc/tomcat/EmbededStandardJarScanner.java: -------------------------------------------------------------------------------- 1 | package io.github.hengyunabc.tomcat; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.JarURLConnection; 6 | import java.net.MalformedURLException; 7 | import java.net.URL; 8 | import java.net.URLClassLoader; 9 | import java.net.URLConnection; 10 | import java.util.HashSet; 11 | import java.util.Iterator; 12 | import java.util.Set; 13 | 14 | import javax.servlet.ServletContext; 15 | 16 | import org.apache.juli.logging.Log; 17 | import org.apache.juli.logging.LogFactory; 18 | import org.apache.tomcat.JarScanFilter; 19 | import org.apache.tomcat.JarScanType; 20 | import org.apache.tomcat.JarScanner; 21 | import org.apache.tomcat.JarScannerCallback; 22 | import org.apache.tomcat.util.ExceptionUtils; 23 | import org.apache.tomcat.util.res.StringManager; 24 | import org.apache.tomcat.util.scan.Constants; 25 | import org.apache.tomcat.util.scan.StandardJarScanFilter; 26 | 27 | /** 28 | * 29 | *
 30 |  * When boot by spring boot loader, WebappClassLoader.getParent() is LaunchedURLClassLoader,
 31 |  * Just need to scan WebappClassLoader and LaunchedURLClassLoader.
 32 |  *
 33 |  * When boot in IDE, WebappClassLoader.getParent() is AppClassLoader,
 34 |  * Just need to scan WebappClassLoader and AppClassLoader.
 35 |  * 
36 | * 37 | * @see {@link JarScanner} 38 | * 39 | * @author hengyunabc 40 | */ 41 | public class EmbededStandardJarScanner implements JarScanner { 42 | 43 | private static final Log log = LogFactory.getLog(EmbededStandardJarScanner.class); 44 | 45 | /** 46 | * The string resources for this package. 47 | */ 48 | private static final StringManager sm = StringManager.getManager(Constants.Package); 49 | 50 | /** 51 | * Controls the classpath scanning extension. 52 | */ 53 | private boolean scanClassPath = true; 54 | 55 | public boolean isScanClassPath() { 56 | return scanClassPath; 57 | } 58 | 59 | public void setScanClassPath(boolean scanClassPath) { 60 | this.scanClassPath = scanClassPath; 61 | } 62 | 63 | /** 64 | * Controls the testing all files to see of they are JAR files extension. 65 | */ 66 | private boolean scanAllFiles = false; 67 | 68 | public boolean isScanAllFiles() { 69 | return scanAllFiles; 70 | } 71 | 72 | public void setScanAllFiles(boolean scanAllFiles) { 73 | this.scanAllFiles = scanAllFiles; 74 | } 75 | 76 | /** 77 | * Controls the testing all directories to see of they are exploded JAR 78 | * files extension. 79 | */ 80 | private boolean scanAllDirectories = false; 81 | 82 | public boolean isScanAllDirectories() { 83 | return scanAllDirectories; 84 | } 85 | 86 | public void setScanAllDirectories(boolean scanAllDirectories) { 87 | this.scanAllDirectories = scanAllDirectories; 88 | } 89 | 90 | /** 91 | * Controls the testing of the bootstrap classpath which consists of the 92 | * runtime classes provided by the JVM and any installed system extensions. 93 | */ 94 | private boolean scanBootstrapClassPath = false; 95 | 96 | public boolean isScanBootstrapClassPath() { 97 | return scanBootstrapClassPath; 98 | } 99 | 100 | public void setScanBootstrapClassPath(boolean scanBootstrapClassPath) { 101 | this.scanBootstrapClassPath = scanBootstrapClassPath; 102 | } 103 | 104 | /** 105 | * Controls the filtering of the results from the scan for JARs 106 | */ 107 | private JarScanFilter jarScanFilter = new StandardJarScanFilter(); 108 | 109 | @Override 110 | public JarScanFilter getJarScanFilter() { 111 | return jarScanFilter; 112 | } 113 | 114 | @Override 115 | public void setJarScanFilter(JarScanFilter jarScanFilter) { 116 | this.jarScanFilter = jarScanFilter; 117 | } 118 | 119 | /** 120 | * Scan the provided ServletContext and class loader for JAR files. Each JAR 121 | * file found will be passed to the callback handler to be processed. 122 | * 123 | * @param scanType 124 | * The type of JAR scan to perform. This is passed to the filter 125 | * which uses it to determine how to filter the results 126 | * @param context 127 | * The ServletContext - used to locate and access WEB-INF/lib 128 | * @param callback 129 | * The handler to process any JARs found 130 | */ 131 | @Override 132 | public void scan(JarScanType scanType, ServletContext context, JarScannerCallback callback) { 133 | 134 | if (log.isTraceEnabled()) { 135 | log.trace(sm.getString("jarScan.webinflibStart")); 136 | } 137 | 138 | Set processedURLs = new HashSet<>(); 139 | 140 | // Scan WEB-INF/lib 141 | Set dirList = context.getResourcePaths(Constants.WEB_INF_LIB); 142 | if (dirList != null) { 143 | Iterator it = dirList.iterator(); 144 | while (it.hasNext()) { 145 | String path = it.next(); 146 | if (path.endsWith(Constants.JAR_EXT) 147 | && getJarScanFilter().check(scanType, path.substring(path.lastIndexOf('/') + 1))) { 148 | // Need to scan this JAR 149 | if (log.isDebugEnabled()) { 150 | log.debug(sm.getString("jarScan.webinflibJarScan", path)); 151 | } 152 | URL url = null; 153 | try { 154 | url = context.getResource(path); 155 | processedURLs.add(url); 156 | process(scanType, callback, url, path, true); 157 | } catch (IOException e) { 158 | log.warn(sm.getString("jarScan.webinflibFail", url), e); 159 | } 160 | } else { 161 | if (log.isTraceEnabled()) { 162 | log.trace(sm.getString("jarScan.webinflibJarNoScan", path)); 163 | } 164 | } 165 | } 166 | } 167 | 168 | // Scan WEB-INF/classes 169 | if (isScanAllDirectories()) { 170 | try { 171 | URL url = context.getResource("/WEB-INF/classes/META-INF"); 172 | if (url != null) { 173 | // Class path scanning will look at WEB-INF/classes since 174 | // that is the URL that Tomcat's web application class 175 | // loader returns. Therefore, it is this URL that needs to 176 | // be added to the set of processed URLs. 177 | URL webInfURL = context.getResource("/WEB-INF/classes"); 178 | if (webInfURL != null) { 179 | processedURLs.add(webInfURL); 180 | } 181 | try { 182 | callback.scanWebInfClasses(); 183 | } catch (IOException e) { 184 | log.warn(sm.getString("jarScan.webinfclassesFail"), e); 185 | } 186 | } 187 | } catch (MalformedURLException e) { 188 | // Ignore 189 | } 190 | } 191 | 192 | // Scan the classpath 193 | if (isScanClassPath()) { 194 | if (log.isTraceEnabled()) { 195 | log.trace(sm.getString("jarScan.classloaderStart")); 196 | } 197 | 198 | ClassLoader classLoader = context.getClassLoader(); 199 | 200 | ClassLoader stopLoader = null; 201 | if (classLoader.getParent() != null) { 202 | // there are two cases: 203 | // 1. boot by spring boot loader 204 | // 2. boot in IDE 205 | // in two case, just need to scan WebappClassLoader and 206 | // WebappClassLoader.getParent() 207 | stopLoader = classLoader.getParent().getParent(); 208 | } 209 | 210 | // JARs are treated as application provided until the common class 211 | // loader is reached. 212 | boolean isWebapp = true; 213 | 214 | while (classLoader != null && classLoader != stopLoader) { 215 | if (classLoader instanceof URLClassLoader) { 216 | URL[] urls = ((URLClassLoader) classLoader).getURLs(); 217 | for (int i = 0; i < urls.length; i++) { 218 | if (processedURLs.contains(urls[i])) { 219 | // Skip this URL it has already been processed 220 | continue; 221 | } 222 | 223 | ClassPathEntry cpe = new ClassPathEntry(urls[i]); 224 | 225 | // JARs are scanned unless the filter says not to. 226 | // Directories are scanned for pluggability scans or 227 | // if scanAllDirectories is enabled unless the 228 | // filter says not to. 229 | if ((cpe.isJar() || scanType == JarScanType.PLUGGABILITY || isScanAllDirectories()) 230 | && getJarScanFilter().check(scanType, cpe.getName())) { 231 | if (log.isDebugEnabled()) { 232 | log.debug(sm.getString("jarScan.classloaderJarScan", urls[i])); 233 | } 234 | try { 235 | process(scanType, callback, urls[i], null, isWebapp); 236 | } catch (IOException ioe) { 237 | log.warn(sm.getString("jarScan.classloaderFail", urls[i]), ioe); 238 | } 239 | } else { 240 | // JAR / directory has been skipped 241 | if (log.isTraceEnabled()) { 242 | log.trace(sm.getString("jarScan.classloaderJarNoScan", urls[i])); 243 | } 244 | } 245 | } 246 | } 247 | classLoader = classLoader.getParent(); 248 | } 249 | } 250 | } 251 | 252 | /* 253 | * Scan a URL for JARs with the optional extensions to look at all files and 254 | * all directories. 255 | */ 256 | private void process(JarScanType scanType, JarScannerCallback callback, URL url, String webappPath, 257 | boolean isWebapp) throws IOException { 258 | 259 | if (log.isTraceEnabled()) { 260 | log.trace(sm.getString("jarScan.jarUrlStart", url)); 261 | } 262 | 263 | URLConnection conn = url.openConnection(); 264 | if (conn instanceof JarURLConnection) { 265 | callback.scan((JarURLConnection) conn, webappPath, isWebapp); 266 | } else { 267 | String urlStr = url.toString(); 268 | if (urlStr.startsWith("file:") || urlStr.startsWith("http:") || urlStr.startsWith("https:")) { 269 | if (urlStr.endsWith(Constants.JAR_EXT)) { 270 | URL jarURL = new URL("jar:" + urlStr + "!/"); 271 | callback.scan((JarURLConnection) jarURL.openConnection(), webappPath, isWebapp); 272 | } else { 273 | File f; 274 | try { 275 | f = new File(url.toURI()); 276 | if (f.isFile() && isScanAllFiles()) { 277 | // Treat this file as a JAR 278 | URL jarURL = new URL("jar:" + urlStr + "!/"); 279 | callback.scan((JarURLConnection) jarURL.openConnection(), webappPath, isWebapp); 280 | } else if (f.isDirectory()) { 281 | if (scanType == JarScanType.PLUGGABILITY) { 282 | callback.scan(f, webappPath, isWebapp); 283 | } else { 284 | File metainf = new File(f.getAbsoluteFile() + File.separator + "META-INF"); 285 | if (metainf.isDirectory()) { 286 | callback.scan(f, webappPath, isWebapp); 287 | } 288 | } 289 | } 290 | } catch (Throwable t) { 291 | ExceptionUtils.handleThrowable(t); 292 | // Wrap the exception and re-throw 293 | IOException ioe = new IOException(); 294 | ioe.initCause(t); 295 | throw ioe; 296 | } 297 | } 298 | } 299 | } 300 | 301 | } 302 | 303 | private static class ClassPathEntry { 304 | 305 | private final boolean jar; 306 | private final String name; 307 | 308 | public ClassPathEntry(URL url) { 309 | String path = url.getPath(); 310 | int end = path.indexOf(Constants.JAR_EXT); 311 | if (end != -1) { 312 | jar = true; 313 | int start = path.lastIndexOf('/', end); 314 | name = path.substring(start + 1, end + 4); 315 | } else { 316 | jar = false; 317 | if (path.endsWith("/")) { 318 | path = path.substring(0, path.length() - 1); 319 | } 320 | int start = path.lastIndexOf('/'); 321 | name = path.substring(start + 1); 322 | } 323 | 324 | } 325 | 326 | public boolean isJar() { 327 | return jar; 328 | } 329 | 330 | public String getName() { 331 | return name; 332 | } 333 | } 334 | } -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | --------------------------------------------------------------------------------