Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jetty helper to manually load web-fragment.xml from JARs and class folders on the classpath.
/**
* Manually load <code>web-fragment.xml</code> from JARs and class folders on the classpath.
*
* <p>Jetty can only find them automatically if the fragment is in a JAR in <code>WEB-INF/lib/</code>.
*/
protected void loadWebFragments(WebAppContext ctx) {
Map<Resource, Resource> frags = getOrCreateFragmentResources(ctx);
try {
ArrayList<URL> urls = Collections.list(getClass().getClassLoader().getResources("META-INF/web-fragment.xml"));
urls.forEach(url -> {
log.debug("Found {}", url);
Resource value = Resource.newResource(url);
Resource key = stripJarFile(url);
frags.put(key, value);
ctx.getMetaData().addWebInfJar(key);
});
} catch (IOException e) {
throw new RuntimeIOException("Error locating web fragments", e);
}
}
public Resource stripJarFile(URL url) {
String path = url.toExternalForm();
if (path.startsWith("jar:")) {
path = StringUtils.substringBefore(path, "!/");
path = StringUtils.removeStart(path, "jar:");
return newResource(path);
} else if (path.startsWith("file:")) {
path = StringUtils.substringBefore(path, "/META-INF");
return newResource(path);
}
throw new IllegalArgumentException("Unsupported URL: " + path);
}
protected Resource newResource(String path) {
Resource key;
try {
key = Resource.newResource(path);
} catch (MalformedURLException e) {
throw new ShouldNotHappenException("Unable to convert [" + path + "] to Resource", e);
}
return key;
}
protected Map<Resource, Resource> getOrCreateFragmentResources(WebAppContext ctx) {
@SuppressWarnings("unchecked")
Map<Resource, Resource> frags = (Map<Resource, Resource>) ctx.getAttribute(FragmentConfiguration.FRAGMENT_RESOURCES);
if (frags == null) {
frags = new HashMap<>();
ctx.setAttribute(FragmentConfiguration.FRAGMENT_RESOURCES, frags);
}
return frags;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment