Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. public class XmlParser {
  2. // this is the global state...
  3. private static com.example.proto.classpath.Handler cpHandler;
  4. static {
  5. cpHandler = new com.example.proto.classpath.Handler();
  6. URL.setURLStreamHandlerFactory(p -> proto.equalsIgnoreCase("example") ? cpHandler : null);
  7. }
  8. public static interface ResourceLocator extends Function<String, URL> {};
  9. public org.w3c.dom.Element parse(InputStream doc, ResourceLocator locator) {
  10. ResourceLocator old = cpHandler.setResourceLocator(locator);
  11. try {
  12. // do the actual parsing, not relevant here
  13. return doc.getDocumentElement();
  14. } finally {
  15. cpHandler.setResourceLocator(old);
  16. }
  17. }
  18. }
  19.  
  20. public class Handler {
  21. private ThreadLocal<ResourceLocator> loc;
  22.  
  23. @Override
  24. protected URLConnection openConnection(URL url) throws IOException {
  25. return loc.get().apply(url.getPath()).openConnection();
  26. }
  27.  
  28. public ResourceLocator setResourceLocator(ResourceLocator loc) {
  29. ResourceLocator old = this.loc.get();
  30. this.loc.set(loc);
  31. return old;
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement