source: josm/trunk/src/org/openstreetmap/josm/tools/Mediawiki.java@ 15121

Last change on this file since 15121 was 14641, checked in by simon04, 6 years ago

Extract Mediawiki class

File size: 2.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.io.IOException;
5import java.io.InputStream;
6import java.net.URL;
7import java.util.List;
8import java.util.Optional;
9import java.util.stream.Collectors;
10
11import javax.xml.parsers.ParserConfigurationException;
12import javax.xml.xpath.XPath;
13import javax.xml.xpath.XPathConstants;
14import javax.xml.xpath.XPathExpressionException;
15import javax.xml.xpath.XPathFactory;
16
17import org.w3c.dom.Document;
18import org.w3c.dom.Node;
19import org.xml.sax.SAXException;
20
21/**
22 * Interaction with Mediawiki instances, such as the OSM wiki.
23 * @since 14641
24 */
25public class Mediawiki {
26
27 private final String baseUrl;
28
29 /**
30 * Constructs a new {@code Mediawiki} for the given base URL.
31 * @param baseUrl The wiki base URL
32 */
33 public Mediawiki(String baseUrl) {
34 this.baseUrl = baseUrl;
35 }
36
37 /**
38 * Determines which page exists on the Mediawiki instance.
39 * @param pages the pages to check
40 * @return the first existing page
41 * @throws IOException if any I/O error occurs
42 * @throws ParserConfigurationException if a parser cannot be created
43 * @throws SAXException if any XML error occurs
44 * @throws XPathExpressionException if any error in an XPath expression occurs
45 */
46 public Optional<String> findExistingPage(List<String> pages)
47 throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
48 // find a page that actually exists in the wiki
49 // API documentation: https://wiki.openstreetmap.org/w/api.php?action=help&modules=query
50 final URL url = new URL(baseUrl + "/w/api.php?action=query&format=xml&titles=" + pages.stream()
51 .map(Utils::encodeUrl)
52 .collect(Collectors.joining("|"))
53 );
54 final HttpClient.Response conn = HttpClient.create(url).connect();
55 final Document document;
56 try (InputStream content = conn.getContent()) {
57 document = XmlUtils.parseSafeDOM(content);
58 }
59 conn.disconnect();
60 final XPath xPath = XPathFactory.newInstance().newXPath();
61 for (String page : pages) {
62 String normalized = xPath.evaluate("/api/query/normalized/n[@from='" + page + "']/@to", document);
63 if (normalized == null || normalized.isEmpty()) {
64 normalized = page;
65 }
66 final Node node = (Node) xPath.evaluate("/api/query/pages/page[@title='" + normalized + "']", document, XPathConstants.NODE);
67 if (node != null
68 && node.getAttributes().getNamedItem("missing") == null
69 && node.getAttributes().getNamedItem("invalid") == null) {
70 return Optional.of(page);
71 }
72 }
73 return Optional.empty();
74 }
75}
Note: See TracBrowser for help on using the repository browser.