|
6 | 6 | import java.net.URL;
|
7 | 7 | import java.util.List;
|
8 | 8 | import java.util.Optional;
|
| 9 | +import java.util.concurrent.atomic.AtomicReference; |
9 | 10 | import java.util.function.BiConsumer;
|
10 | 11 | import java.util.stream.Collectors;
|
11 | 12 |
|
@@ -59,22 +60,33 @@ public Optional<String> findExistingPage(List<String> pages)
|
59 | 60 | );
|
60 | 61 | final Document document = getDocument(url);
|
61 | 62 | final XPath xPath = XPathFactory.newInstance().newXPath();
|
62 |
| - for (String page : distinctPages) { |
63 |
| - String normalized = xPath.evaluate("/api/query/normalized/n[@from='" + page + "']/@to", document); |
64 |
| - if (Utils.isEmpty(normalized)) { |
65 |
| - normalized = page; |
| 63 | + AtomicReference<String> normalized = new AtomicReference<>(); |
| 64 | + AtomicReference<String> page = new AtomicReference<>(); |
| 65 | + xPath.setXPathVariableResolver(v -> { |
| 66 | + if ("page".equals(v.getLocalPart())) { |
| 67 | + return page.get(); |
| 68 | + } else if ("normalized".equals(v.getLocalPart())) { |
| 69 | + return normalized.get(); |
66 | 70 | }
|
67 |
| - final Node node = (Node) xPath.evaluate("/api/query/pages/page[@title='" + normalized + "']", document, XPathConstants.NODE); |
| 71 | + throw new IllegalArgumentException(); |
| 72 | + }); |
| 73 | + for (String p : distinctPages) { |
| 74 | + page.set(p); |
| 75 | + normalized.set(xPath.evaluate("/api/query/normalized/n[@from=$page]/@to", document)); |
| 76 | + if (Utils.isEmpty(normalized.get())) { |
| 77 | + normalized.set(page.get()); |
| 78 | + } |
| 79 | + final Node node = (Node) xPath.evaluate("/api/query/pages/page[@title=$normalized]", document, XPathConstants.NODE); |
68 | 80 | if (node != null
|
69 | 81 | && node.getAttributes().getNamedItem("missing") == null
|
70 | 82 | && node.getAttributes().getNamedItem("invalid") == null) {
|
71 |
| - return Optional.of(page); |
| 83 | + return Optional.of(page.get()); |
72 | 84 | }
|
73 | 85 | }
|
74 | 86 | return Optional.empty();
|
75 | 87 | }
|
76 | 88 |
|
77 |
| - private Document getDocument(URL url) throws IOException, ParserConfigurationException, SAXException { |
| 89 | + private static Document getDocument(URL url) throws IOException, ParserConfigurationException, SAXException { |
78 | 90 | final HttpClient.Response conn = HttpClient.create(url).connect();
|
79 | 91 | try (InputStream content = conn.getContent()) {
|
80 | 92 | return XmlUtils.parseSafeDOM(content);
|
|
0 commit comments