Skip to content

Instantly share code, notes, and snippets.

@jhannes
Created January 16, 2015 14:49
Show Gist options
  • Save jhannes/e795c1828a203fc82d33 to your computer and use it in GitHub Desktop.
Save jhannes/e795c1828a203fc82d33 to your computer and use it in GitHub Desktop.
Jetty 9 embedded Servlet 3.0 annotations without war file
public class AnnotationScanner {
protected void scanForAnnotations(final String javaPackage, WebAppContext webapp) throws Exception {
Set<AnnotationParser.Handler> handlers = new HashSet<>();
handlers.add(new WebServletAnnotationHandler(webapp));
handlers.add(new WebFilterAnnotationHandler(webapp));
handlers.add(new WebListenerAnnotationHandler(webapp));
AnnotationParser annotationParser = new AnnotationParser();
for (URL url : ((URLClassLoader) getClass().getClassLoader()).getURLs()) {
if (!url.getProtocol().equals("file")) {
throw new IllegalArgumentException(url.toString());
}
final File file = new File(url.getFile());
if (file.isDirectory()) {
annotationParser.parse(handlers, url.toURI(), createFolderResolver(file, javaPackage));
} else if (file.isFile() && file.getName().endsWith(".jar")) {
annotationParser.parse(handlers, url.toURI(), createClassNameResolver(javaPackage));
} else {
throw new IllegalArgumentException(url.toString());
}
}
}
private ClassNameResolver createFolderResolver(final File file, final String javaPackage) {
String pathPrefix = file.toString() + File.separatorChar +
javaPackage.replace('.', File.separatorChar);
return createClassNameResolver(pathPrefix);
}
private ClassNameResolver createClassNameResolver(final String prefix) {
return new ClassNameResolver() {
@Override
public boolean shouldOverride(String name) {
return false;
}
@Override
public boolean isExcluded(String name) {
return !name.startsWith(prefix);
}
};
}
public void dumpServletContext(WebAppContext webAppContext) {
ServletHandler servletHandler = webAppContext.getServletHandler();
for (ServletMapping servletMapping : servletHandler.getServletMappings()) {
System.out.print(Arrays.asList(servletMapping.getPathSpecs()));
System.out.println(" " + servletHandler.getServlet(servletMapping.getServletName()).getClassName());
}
for (FilterMapping filterMapping : servletHandler.getFilterMappings()) {
System.out.print(Arrays.asList(filterMapping.getPathSpecs()));
System.out.println(" " + servletHandler.getFilter(filterMapping.getFilterName()).getClassName());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment