Created
June 9, 2017 08:32
-
-
Save digulla/fb69b5df3b120f6e47b06130842d62cb to your computer and use it in GitHub Desktop.
Jetty helper to manually load web-fragment.xml from JARs and class folders on the classpath.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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