Ignore:
Timestamp:
2015-12-28T11:57:17+01:00 (9 years ago)
Author:
simon04
Message:

JOSM/wikipedia: use new HttpClient

Location:
applications/editors/josm/plugins/wikipedia
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/wikipedia/build.xml

    r31857 r31881  
    55    <property name="commit.message" value="Commit message"/>
    66    <!-- enter the *lowest* JOSM version this plugin is currently compatible with -->
    7     <property name="plugin.main.version" value="9149"/>
     7    <property name="plugin.main.version" value="9179"/>
    88    <property name="plugin.canloadatruntime" value="true"/>
    99
  • applications/editors/josm/plugins/wikipedia/src/org/wikipedia/WikipediaApp.java

    r31861 r31881  
    44import java.io.IOException;
    55import java.io.InputStream;
    6 import java.io.OutputStreamWriter;
    7 import java.net.HttpURLConnection;
    86import java.net.URL;
     7import java.nio.charset.StandardCharsets;
    98import java.util.AbstractList;
    109import java.util.ArrayList;
     
    2019import java.util.regex.Pattern;
    2120
     21import javax.xml.parsers.DocumentBuilder;
    2222import javax.xml.parsers.DocumentBuilderFactory;
     23import javax.xml.parsers.ParserConfigurationException;
     24import javax.xml.xpath.XPath;
    2325import javax.xml.xpath.XPathConstants;
    2426import javax.xml.xpath.XPathExpression;
     
    3032import org.openstreetmap.josm.data.osm.Tag;
    3133import org.openstreetmap.josm.tools.CheckParameterUtil;
     34import org.openstreetmap.josm.tools.HttpClient;
    3235import org.openstreetmap.josm.tools.Predicate;
    3336import org.openstreetmap.josm.tools.Utils;
     
    4043
    4144    public static Pattern WIKIDATA_PATTERN = Pattern.compile("Q\\d+");
     45    private static final DocumentBuilder DOCUMENT_BUILDER = newDocumentBuilder();
     46    private static final XPath X_PATH = XPathFactory.newInstance().newXPath();
    4247
    4348    private WikipediaApp() {
     
    5055            final String url = "https://tools.wmflabs.org/wp-world/marks.php?"
    5156                    + "bbox=" + bbox + "&LANG=" + wikipediaLang;
    52             Main.info("Wikipedia: GET " + url);
    5357            // parse XML document
    54             final XPathExpression xpathPlacemark = XPathFactory.newInstance().newXPath().compile("//Placemark");
    55             final XPathExpression xpathName = XPathFactory.newInstance().newXPath().compile("name/text()");
    56             final XPathExpression xpathCoord = XPathFactory.newInstance().newXPath().compile("Point/coordinates/text()");
    57             final XPathExpression xpathDescr = XPathFactory.newInstance().newXPath().compile("description");
    58             try (final InputStream in = Utils.openURL(new URL(url))) {
    59                 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
     58            final XPathExpression xpathPlacemark = X_PATH.compile("//Placemark");
     59            final XPathExpression xpathName = X_PATH.compile("name/text()");
     60            final XPathExpression xpathCoord = X_PATH.compile("Point/coordinates/text()");
     61            final XPathExpression xpathDescr = X_PATH.compile("description");
     62            try (final InputStream in = HttpClient.create(new URL(url)).setReasonForRequest("Wikipedia").connect().getContent()) {
     63                Document doc = DOCUMENT_BUILDER.parse(in);
    6064                NodeList nodes = (NodeList) xpathPlacemark.evaluate(doc, XPathConstants.NODESET);
    6165                // construct WikipediaEntry for each XML element
     
    8488                    + "&depth=" + depth
    8589                    + "&cat=" + Utils.encodeUrl(category);
    86             Main.info("Wikipedia: GET " + url);
    87             try (final InputStream in = Utils.openURL(new URL(url));
    88                  final Scanner scanner = new Scanner(in, "UTF-8").useDelimiter("\n")) {
     90
     91            try (final Scanner scanner = new Scanner(
     92                    HttpClient.create(new URL(url)).setReasonForRequest("Wikipedia").connect().getContentReader())
     93                    .useDelimiter("\n")) {
    8994                final List<WikipediaEntry> entries = new ArrayList<>();
    9095                while (scanner.hasNext()) {
     
    119124            final String url = "https://tools.wmflabs.org/wiwosm/osmjson/getGeoJSON.php?action=check"
    120125                    + "&lang=" + wikipediaLang;
    121             Main.info("Wikipedia: POST " + url + " " + articleNames);
    122126
    123127            try {
    124                 final HttpURLConnection connection = Utils.openHttpConnection(new URL(url));
    125                 connection.setDoOutput(true);
    126 
    127                 try (final OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
    128                     out.write("articles=" + Utils.encodeUrl(Utils.join(",", articleNames)));
    129                 }
    130 
    131                 try (final Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\n")) {
     128                final String requestBody = "articles=" + Utils.encodeUrl(Utils.join(",", articleNames));
     129                try (final Scanner scanner = new Scanner(
     130                        HttpClient.create(new URL(url), "PUT").setReasonForRequest("Wikipedia")
     131                                .setRequestBody(requestBody.getBytes(StandardCharsets.UTF_8))
     132                                .connect().getContentReader())
     133                        .useDelimiter("\n")) {
    132134                    while (scanner.hasNext()) {
    133135                        //[article]\t[0|1]
     
    186188                }
    187189            }));
    188             Main.info("Wikipedia: GET " + url);
    189190            final Map<String, String> r = new TreeMap<>();
    190             try (final InputStream in = Utils.openURL(new URL(url))) {
    191                 final Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
    192                 final NodeList nodes = (NodeList) XPathFactory.newInstance().newXPath().compile("//entity").evaluate(xml, XPathConstants.NODESET);
     191            try (final InputStream in = HttpClient.create(new URL(url)).setReasonForRequest("Wikipedia").connect().getContent()) {
     192                final Document xml = DOCUMENT_BUILDER.parse(in);
     193                final NodeList nodes = (NodeList) X_PATH.compile("//entity").evaluate(xml, XPathConstants.NODESET);
    193194                for (int i = 0; i < nodes.getLength(); i++) {
    194195                    final Node node = nodes.item(i);
    195                     final String wikidata = (String) XPathFactory.newInstance().newXPath().compile("./@id").evaluate(node, XPathConstants.STRING);
    196                     final String wikipedia = (String) XPathFactory.newInstance().newXPath().compile("./sitelinks/sitelink/@title").evaluate(node, XPathConstants.STRING);
     196                    final String wikidata = (String) X_PATH.compile("./@id").evaluate(node, XPathConstants.STRING);
     197                    final String wikipedia = (String) X_PATH.compile("./sitelinks/sitelink/@title").evaluate(node, XPathConstants.STRING);
    197198                    r.put(wikipedia, wikidata);
    198199                }
     
    213214                    "&format=xml" +
    214215                    (preferredLanguage != null ? "&languages=" + preferredLanguage + "&languagefallback=en" : "");
    215             Main.info("Wikipedia: GET " + url);
    216             try (final InputStream in = Utils.openURL(new URL(url))) {
    217                 final Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
    218                 final Node label = (Node) XPathFactory.newInstance().newXPath().compile("//label").evaluate(xml, XPathConstants.NODE);
     216            try (final InputStream in = HttpClient.create(new URL(url)).setReasonForRequest("Wikipedia").connect().getContent()) {
     217                final Document xml = DOCUMENT_BUILDER.parse(in);
     218                final Node label = (Node) X_PATH.compile("//label").evaluate(xml, XPathConstants.NODE);
    219219                if (label == null && preferredLanguage != null) {
    220220                    return getLabelForWikidata(wikidataId, null);
     
    222222                    return null;
    223223                } else {
    224                     return (String) XPathFactory.newInstance().newXPath().compile("./@value").evaluate(label, XPathConstants.STRING);
     224                    return (String) X_PATH.compile("./@value").evaluate(label, XPathConstants.STRING);
    225225                }
    226226            }
     
    239239                    "&lllimit=500" +
    240240                    "&format=xml";
    241             Main.info("Wikipedia: GET " + url);
    242             try (final InputStream in = Utils.openURL(new URL(url))) {
    243                 final Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
    244                 final NodeList nodes = (NodeList) XPathFactory.newInstance().newXPath().compile("//ll").evaluate(xml, XPathConstants.NODESET);
     241            try (final InputStream in = HttpClient.create(new URL(url)).setReasonForRequest("Wikipedia").connect().getContent()) {
     242                final Document xml = DOCUMENT_BUILDER.parse(in);
     243                final NodeList nodes = (NodeList) X_PATH.compile("//ll").evaluate(xml, XPathConstants.NODESET);
    245244                for (int i = 0; i < nodes.getLength(); i++) {
    246245                    final String lang = nodes.item(i).getAttributes().getNamedItem("lang").getTextContent();
     
    370369                        + "&lang=" + wikipediaLang
    371370                        + "&article=" + Utils.encodeUrl(wikipediaArticle);
    372                 Main.info("Wikipedia: GET " + url);
    373                 try (final InputStream in = Utils.openURL(new URL(url));
    374                      final Scanner scanner = new Scanner(in, "UTF-8")) {
     371                try (final Scanner scanner = new Scanner(
     372                        HttpClient.create(new URL(url)).setReasonForRequest("Wikipedia").connect().getContentReader())) {
    375373                    wiwosmStatus = scanner.hasNextInt() && scanner.nextInt() == 1;
    376374                }
     
    419417        };
    420418    }
     419
     420    private static DocumentBuilder newDocumentBuilder() {
     421        try {
     422            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
     423        } catch (ParserConfigurationException e) {
     424            Main.warn("Cannot create DocumentBuilder");
     425            Main.warn(e);
     426            throw new RuntimeException(e);
     427        }
     428    }
    421429}
Note: See TracChangeset for help on using the changeset viewer.