Changeset 35648 in osm


Ignore:
Timestamp:
2020-11-16T18:12:43+01:00 (3 years ago)
Author:
Don-vip
Message:

code cleanup in filters download

File:
1 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/rasterfilters/src/org/openstreetmap/josm/plugins/rasterfilters/preferences/FiltersDownloader.java

    r34550 r35648  
    33import java.awt.event.ActionEvent;
    44import java.awt.event.ActionListener;
    5 import java.io.BufferedInputStream;
    6 import java.io.BufferedOutputStream;
    75import java.io.BufferedReader;
    86import java.io.BufferedWriter;
    97import java.io.File;
    10 import java.io.FileOutputStream;
    118import java.io.IOException;
     9import java.io.InputStream;
    1210import java.io.StringReader;
    13 import java.net.HttpURLConnection;
    1411import java.net.MalformedURLException;
    1512import java.net.URL;
    1613import java.net.URLClassLoader;
    17 import java.net.URLConnection;
    1814import java.nio.charset.StandardCharsets;
    1915import java.nio.file.Files;
     16import java.nio.file.StandardCopyOption;
    2017import java.util.ArrayList;
    2118import java.util.HashMap;
     
    3734import org.jsoup.nodes.Element;
    3835import org.jsoup.select.Elements;
     36import org.openstreetmap.josm.gui.help.HelpUtil;
    3937import org.openstreetmap.josm.spi.preferences.Config;
     38import org.openstreetmap.josm.tools.HttpClient;
    4039import org.openstreetmap.josm.tools.Logging;
    4140
     
    6160
    6261    public static List<FilterInfo> downloadFiltersInfoList() {
    63 
    64 //        JsonObject jsonRequest = Json
    65 //                .createObjectBuilder()
    66 //                .add("id", new Random().nextInt())
    67 //                .add("method", "wiki.getPageHTML")
    68 //                .add("params",
    69 //                        Json.createArrayBuilder().add("ImageFilters").build())
    70 //                .build();
    71 
    72 //        String jsonRequestString = jsonRequest.toString();
    73 
    74 //        URL wikiApi;
    75 //        HttpURLConnection wikiConnection;
    7662        try {
    77 //            wikiApi = new URL("https://josm.openstreetmap.de/wiki/ImageFilters");
    78 //            wikiConnection = (HttpURLConnection) wikiApi.openConnection();
    79 //            wikiConnection.setDoOutput(true);
    80 //            wikiConnection.setDoInput(true);
    81 //
    82 //            wikiConnection.setRequestProperty("Content-Type",
    83 //                    "application/json");
    84 //            wikiConnection.setRequestProperty("Method", "POST");
    85 //            wikiConnection.connect();
    86 
    87 //            OutputStream os = wikiConnection.getOutputStream();
    88 //            os.write(jsonRequestString.getBytes("UTF-8"));
    89 //            os.close();
    90 
    91 //            int HttpResult = wikiConnection.getResponseCode();
    92 //            if (HttpResult == HttpURLConnection.HTTP_OK) {
    93 
    94 //                JsonReader jsonStream = Json
    95 //                        .createReader(new InputStreamReader(wikiConnection
    96 //                                .getInputStream(), "utf-8"));
    97 
    98 //                BufferedReader inReader = new BufferedReader(new InputStreamReader(wikiConnection.getInputStream()));
    99 
    100 //                JsonObject jsonResponse = jsonStream.readObject();
    101 //                jsonStream.close();
    102             Document doc = Jsoup.connect("https://josm.openstreetmap.de/wiki/ImageFilters").get();
    103             Elements trTagElems = doc.getElementsByTag("tr");
    104 
    105 //                Elements trTagElems = Jsoup.parse(
    106 //                        jsonResponse.getString("result"))
    107 //                        .getElementsByTag("tr");
    108             for (Element element : trTagElems) {
    109 
     63            Document doc = Jsoup.connect(HelpUtil.getWikiBaseHelpUrl() + "/ImageFilters").get();
     64            for (Element element : doc.getElementsByTag("tr")) {
    11065                Elements elems = element.getElementsByTag("td");
    11166                if (!elems.isEmpty()) {
     
    11368                    String owner = elems.get(1).text();
    11469                    String description = elems.get(2).text();
    115 
    116                     String link = elems.get(0).getElementsByTag("a")
    117                             .attr("href");
     70                    String link = elems.get(0).getElementsByTag("a").attr("href");
    11871
    11972                    JsonObject meta = loadMeta(link);
    120 
    12173                    if (meta != null) {
    122                         String paramName = "rasterfilters."
    123                                 + meta.getString("name");
    124 
    125                         boolean needToLoad = Config.getPref().getBoolean(paramName);
    126 
     74                        boolean needToLoad = Config.getPref().getBoolean("rasterfilters." + meta.getString("name"));
    12775                        if (needToLoad) {
    12876                            JsonArray binaries = meta.getJsonArray("binaries");
     
    13381                            }
    13482                        }
    135                         FilterInfo newFilterInfo = new FilterInfo(name,
    136                                 description, meta, needToLoad);
     83                        FilterInfo newFilterInfo = new FilterInfo(name, description, meta, needToLoad);
    13784                        newFilterInfo.setOwner(owner);
    13885
     
    14390                }
    14491            }
    145 
    146 //            } else {
    147 //                Main.debug("Error happenned while requesting for the list of filters");
    148 //            }
    149         } catch (IOException e1) {
    150             Logging.error(e1);
     92        } catch (IOException e) {
     93            Logging.error(e);
    15194        }
    15295
     
    165108        }
    166109
    167 //        JsonObject jsonRequest = Json.createObjectBuilder()
    168 //                .add("id", new Random().nextInt())
    169 //                .add("method", "wiki.getPageHTML")
    170 //                .add("params", Json.createArrayBuilder().add(link).build())
    171 //                .build();
    172 
    173 //        String jsonStringRequest = jsonRequest.toString();
    174 
    175         URL wikiApi;
    176         HttpURLConnection wikiConnection;
    177110        JsonObject meta = null;
    178111
    179112        try {
    180 //            wikiApi = new URL("https://josm.openstreetmap.de/jsonrpc");
    181 //            wikiConnection = (HttpURLConnection) wikiApi.openConnection();
    182 //            wikiConnection.setDoOutput(true);
    183 //            wikiConnection.setDoInput(true);
    184 //
    185 //            wikiConnection.setRequestProperty("Content-Type",
    186 //                    "application/json");
    187 //            wikiConnection.setRequestProperty("Method", "POST");
    188 //            wikiConnection.connect();
    189 //
    190 //            OutputStream os = wikiConnection.getOutputStream();
    191 //            os.write(jsonStringRequest.getBytes("UTF-8"));
    192 //            os.close();
    193 //
    194 //            int HttpResult = wikiConnection.getResponseCode();
    195 //            if (HttpResult == HttpURLConnection.HTTP_OK) {
    196 
    197 //            JsonReader jsonStream = Json
    198 //                    .createReader(new InputStreamReader(wikiConnection
    199 //                            .getInputStream(), "UTF-8"));
    200 
    201 //            JsonObject jsonResponse = jsonStream.readObject();
    202 //            jsonStream.close();
    203 
    204 //            String jsonPage = jsonResponse.getString("result");
    205 
    206             Document doc = Jsoup.connect("https://josm.openstreetmap.de/wiki/" + link).get();
    207             String json = doc.getElementsByTag("pre").first().text();
    208 
    209             JsonReader reader = Json.createReader(new StringReader(json));
    210             meta = reader.readObject();
    211             reader.close();
    212 
    213 //            } else {
    214 //                Main.debug(wikiConnection.getResponseMessage());
    215 //            }
    216         } catch (IOException e1) {
    217             Logging.error(e1);
    218         }
    219 
    220         filtersMeta.add(meta);
     113            Document doc = Jsoup.connect(HelpUtil.getWikiBaseHelpUrl() + "/" + link).get();
     114            try (JsonReader reader = Json.createReader(new StringReader(doc.getElementsByTag("pre").first().text()))) {
     115                meta = reader.readObject();
     116            }
     117        } catch (IOException e) {
     118            Logging.error(e);
     119        }
     120
     121        if (meta != null) {
     122            filtersMeta.add(meta);
     123        }
    221124
    222125        return meta;
     
    224127
    225128    public static void initFilters() {
    226         File file = new File(pluginDir, "urls.map");
    227         Logging.debug("EXIST FILE? " + file.exists());
    228 
    229         try (BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
     129        try (BufferedReader br = Files.newBufferedReader(new File(pluginDir, "urls.map").toPath(), StandardCharsets.UTF_8)) {
    230130            String temp;
    231 
    232131            while ((temp = br.readLine()) != null) {
    233132                String[] mapEntry = temp.split("\\t");
    234133                File fileUrl = new File(mapEntry[1]);
    235134                if (fileUrl.exists()) {
    236                     URL url;
    237135                    try {
    238                         url = new URL("jar", "", fileUrl.toURI().toURL() + "!/");
     136                        URL url = new URL("jar", "", fileUrl.toURI().toURL() + "!/");
    239137                        Logging.debug("binaryUrl: " + url.toString());
    240138                        binariesLocalUrls.add(url);
    241139                    } catch (MalformedURLException e) {
    242                         Logging.debug("Initializing filters with unknown protocol. \n"
    243                                 + e.getMessage());
     140                        Logging.debug("Initializing filters with unknown protocol. \n" + e.getMessage());
    244141                    }
    245142                }
     
    248145            Logging.error(e);
    249146        }
    250 
    251         Logging.debug("BinariesLocal : " + binariesLocalUrls.toString());
    252147
    253148        loader = new URLClassLoader(
     
    264159    @Override
    265160    public void actionPerformed(ActionEvent e) {
    266 
    267161        for (FilterInfo temp : filtersInfoList) {
    268162            if (temp.isNeedToDownload()) {
    269 
    270                 if (!filtersMetaToLoad.contains(temp.getMeta())) {
    271                     filtersMetaToLoad.add(temp.getMeta());
    272                 }
    273 
     163                filtersMetaToLoad.add(temp.getMeta());
    274164                filterTitles.add(temp.getMeta().getString("title"));
    275165            } else {
     
    279169
    280170        loadBinariesFromMeta(filtersMetaToLoad);
    281 
    282171        filtersMetaToLoad.clear();
    283172    }
    284173
    285174    public static void loadBinariesFromMeta(Set<JsonObject> metaList) {
    286 
    287175        File file = new File(pluginDir, "urls.map");
    288         Logging.debug("pluginDir and urls map" + file.getAbsoluteFile());
    289 
    290176        try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
    291177            for (JsonObject temp : metaList) {
    292178                JsonArray binaries = temp.getJsonArray("binaries");
    293 
    294179                for (int i = 0; i < binaries.size(); i++) {
    295 
    296180                    String localFile = loadBinaryToFile(binaries.getString(i));
    297 
    298181                    try {
    299182                        writer.append(binaries.getString(i));
     
    316199
    317200    public static String loadBinaryToFile(String fromUrl) {
    318 
    319         // Logging.debug("Need to load binary from " + fromUrl);
    320 
    321         URL url = null;
    322         URLConnection con = null;
    323 
    324201        Pattern p = Pattern.compile("\\w.*/");
    325202        Matcher m = p.matcher(fromUrl);
    326203
    327204        String localFile = null;
    328         File plugin = pluginDir;
    329         Logging.debug("plugin dir" + plugin.getAbsolutePath());
    330 
    331         if (m.find()) {
    332             if (plugin.exists()) {
    333                 localFile = fromUrl.substring(m.end());
    334                 Logging.debug("localFile: " + localFile);
    335             }
     205        if (m.find() && pluginDir.exists()) {
     206            localFile = fromUrl.substring(m.end());
    336207        }
    337208
    338209        try {
    339             url = new URL(fromUrl);
    340             con = url.openConnection();
    341             String plugDir = plugin.getAbsolutePath();
    342             File file = new File(plugDir, localFile);
    343             Logging.debug("Binary file: " + file.getAbsolutePath());
    344 
     210            File file = new File(pluginDir.getAbsolutePath(), localFile);
    345211            if (file.exists()) {
    346                 Logging.debug("File " + localFile + " already exists");
    347 
    348212                return file.getAbsolutePath();
    349213            } else {
    350 
    351                 BufferedInputStream in = new BufferedInputStream(
    352                         con.getInputStream());
    353                 BufferedOutputStream out = new BufferedOutputStream(
    354                         new FileOutputStream(file));
    355                 int i;
    356 
    357                 while ((i = in.read()) != -1) {
    358                     out.write(i);
    359                 }
    360 
    361                 out.flush();
    362                 out.close();
    363                 in.close();
    364 
     214                try (InputStream in = HttpClient.create(new URL(fromUrl)).connect().getContent()) {
     215                    Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
     216                }
    365217                return localFile;
    366218            }
    367         } catch (IOException e1) {
    368             Logging.error(e1);
     219        } catch (IOException e) {
     220            Logging.error(e);
    369221        }
    370222
    371223        return null;
    372224    }
    373 
    374225}
Note: See TracChangeset for help on using the changeset viewer.