Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class XmlParser {
- // this is the global state...
- private static com.example.proto.classpath.Handler cpHandler;
- static {
- cpHandler = new com.example.proto.classpath.Handler();
- URL.setURLStreamHandlerFactory(p -> proto.equalsIgnoreCase("example") ? cpHandler : null);
- }
- public static interface ResourceLocator extends Function<String, URL> {};
- public org.w3c.dom.Element parse(InputStream doc, ResourceLocator locator) {
- ResourceLocator old = cpHandler.setResourceLocator(locator);
- try {
- // do the actual parsing, not relevant here
- return doc.getDocumentElement();
- } finally {
- cpHandler.setResourceLocator(old);
- }
- }
- }
- public class Handler {
- private ThreadLocal<ResourceLocator> loc;
- @Override
- protected URLConnection openConnection(URL url) throws IOException {
- return loc.get().apply(url.getPath()).openConnection();
- }
- public ResourceLocator setResourceLocator(ResourceLocator loc) {
- ResourceLocator old = this.loc.get();
- this.loc.set(loc);
- return old;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement