source: josm/trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java@ 14149

Last change on this file since 14149 was 14149, checked in by Don-vip, 6 years ago

see #15229 - deprecate Main.pref

  • Property svn:eol-style set to native
File size: 13.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.plugins;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Dimension;
7import java.awt.GridBagLayout;
8import java.io.ByteArrayInputStream;
9import java.io.File;
10import java.io.FilenameFilter;
11import java.io.IOException;
12import java.io.InputStream;
13import java.io.InputStreamReader;
14import java.io.PrintWriter;
15import java.net.MalformedURLException;
16import java.net.URL;
17import java.nio.charset.StandardCharsets;
18import java.util.ArrayList;
19import java.util.Arrays;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashSet;
23import java.util.LinkedList;
24import java.util.List;
25import java.util.Optional;
26import java.util.Set;
27
28import javax.swing.JLabel;
29import javax.swing.JOptionPane;
30import javax.swing.JPanel;
31import javax.swing.JScrollPane;
32
33import org.openstreetmap.josm.data.Preferences;
34import org.openstreetmap.josm.gui.PleaseWaitRunnable;
35import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
36import org.openstreetmap.josm.gui.progress.ProgressMonitor;
37import org.openstreetmap.josm.gui.util.GuiHelper;
38import org.openstreetmap.josm.gui.widgets.JosmTextArea;
39import org.openstreetmap.josm.io.OsmTransferException;
40import org.openstreetmap.josm.spi.preferences.Config;
41import org.openstreetmap.josm.tools.GBC;
42import org.openstreetmap.josm.tools.HttpClient;
43import org.openstreetmap.josm.tools.Logging;
44import org.openstreetmap.josm.tools.Utils;
45import org.xml.sax.SAXException;
46
47/**
48 * An asynchronous task for downloading plugin lists from the configured plugin download sites.
49 * @since 2817
50 */
51public class ReadRemotePluginInformationTask extends PleaseWaitRunnable {
52
53 private Collection<String> sites;
54 private boolean canceled;
55 private HttpClient connection;
56 private List<PluginInformation> availablePlugins;
57 private boolean displayErrMsg;
58
59 protected final void init(Collection<String> sites, boolean displayErrMsg) {
60 this.sites = Optional.ofNullable(sites).orElseGet(Collections::emptySet);
61 this.availablePlugins = new LinkedList<>();
62 this.displayErrMsg = displayErrMsg;
63 }
64
65 /**
66 * Constructs a new {@code ReadRemotePluginInformationTask}.
67 *
68 * @param sites the collection of download sites. Defaults to the empty collection if null.
69 */
70 public ReadRemotePluginInformationTask(Collection<String> sites) {
71 super(tr("Download plugin list..."), false /* don't ignore exceptions */);
72 init(sites, true);
73 }
74
75 /**
76 * Constructs a new {@code ReadRemotePluginInformationTask}.
77 *
78 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null
79 * @param sites the collection of download sites. Defaults to the empty collection if null.
80 * @param displayErrMsg if {@code true}, a blocking error message is displayed in case of I/O exception.
81 */
82 public ReadRemotePluginInformationTask(ProgressMonitor monitor, Collection<String> sites, boolean displayErrMsg) {
83 super(tr("Download plugin list..."), monitor == null ? NullProgressMonitor.INSTANCE : monitor, false /* don't ignore exceptions */);
84 init(sites, displayErrMsg);
85 }
86
87 @Override
88 protected void cancel() {
89 canceled = true;
90 synchronized (this) {
91 if (connection != null) {
92 connection.disconnect();
93 }
94 }
95 }
96
97 @Override
98 protected void finish() {
99 // Do nothing
100 }
101
102 /**
103 * Creates the file name for the cached plugin list and the icon cache file.
104 *
105 * @param pluginDir directory of plugin for data storage
106 * @param site the name of the site
107 * @return the file name for the cache file
108 */
109 protected File createSiteCacheFile(File pluginDir, String site) {
110 String name;
111 try {
112 site = site.replaceAll("%<(.*)>", "");
113 URL url = new URL(site);
114 StringBuilder sb = new StringBuilder();
115 sb.append("site-")
116 .append(url.getHost()).append('-');
117 if (url.getPort() != -1) {
118 sb.append(url.getPort()).append('-');
119 }
120 String path = url.getPath();
121 for (int i = 0; i < path.length(); i++) {
122 char c = path.charAt(i);
123 if (Character.isLetterOrDigit(c)) {
124 sb.append(c);
125 } else {
126 sb.append('_');
127 }
128 }
129 sb.append(".txt");
130 name = sb.toString();
131 } catch (MalformedURLException e) {
132 name = "site-unknown.txt";
133 }
134 return new File(pluginDir, name);
135 }
136
137 /**
138 * Downloads the list from a remote location
139 *
140 * @param site the site URL
141 * @param monitor a progress monitor
142 * @return the downloaded list
143 */
144 protected String downloadPluginList(String site, final ProgressMonitor monitor) {
145 /* replace %<x> with empty string or x=plugins (separated with comma) */
146 String pl = Utils.join(",", Config.getPref().getList("plugins"));
147 String printsite = site.replaceAll("%<(.*)>", "");
148 if (pl != null && !pl.isEmpty()) {
149 site = site.replaceAll("%<(.*)>", "$1"+pl);
150 } else {
151 site = printsite;
152 }
153
154 String content = null;
155 try {
156 monitor.beginTask("");
157 monitor.indeterminateSubTask(tr("Downloading plugin list from ''{0}''", printsite));
158
159 final URL url = new URL(site);
160 if ("https".equals(url.getProtocol()) || "http".equals(url.getProtocol())) {
161 connection = HttpClient.create(url).useCache(false);
162 final HttpClient.Response response = connection.connect();
163 content = response.fetchContent();
164 if (response.getResponseCode() != 200) {
165 throw new IOException(tr("Unsuccessful HTTP request"));
166 }
167 return content;
168 } else {
169 // e.g. when downloading from a file:// URL, we can't use HttpClient
170 try (InputStreamReader in = new InputStreamReader(url.openConnection().getInputStream(), StandardCharsets.UTF_8)) {
171 final StringBuilder sb = new StringBuilder();
172 final char[] buffer = new char[8192];
173 int numChars;
174 while ((numChars = in.read(buffer)) >= 0) {
175 sb.append(buffer, 0, numChars);
176 if (canceled) {
177 return null;
178 }
179 }
180 return sb.toString();
181 }
182 }
183
184 } catch (MalformedURLException e) {
185 if (canceled) return null;
186 Logging.error(e);
187 return null;
188 } catch (IOException e) {
189 if (canceled) return null;
190 handleIOException(monitor, e, content);
191 return null;
192 } finally {
193 synchronized (this) {
194 if (connection != null) {
195 connection.disconnect();
196 }
197 connection = null;
198 }
199 monitor.finishTask();
200 }
201 }
202
203 private void handleIOException(final ProgressMonitor monitor, IOException e, String details) {
204 final String msg = e.getMessage();
205 if (details == null || details.isEmpty()) {
206 Logging.error(e.getClass().getSimpleName()+": " + msg);
207 } else {
208 Logging.error(msg + " - Details:\n" + details);
209 }
210
211 if (displayErrMsg) {
212 displayErrorMessage(monitor, msg, details, tr("Plugin list download error"), tr("JOSM failed to download plugin list:"));
213 }
214 }
215
216 private static void displayErrorMessage(final ProgressMonitor monitor, final String msg, final String details, final String title,
217 final String firstMessage) {
218 GuiHelper.runInEDTAndWait(() -> {
219 JPanel panel = new JPanel(new GridBagLayout());
220 panel.add(new JLabel(firstMessage), GBC.eol().insets(0, 0, 0, 10));
221 StringBuilder b = new StringBuilder();
222 for (String part : msg.split("(?<=\\G.{200})")) {
223 b.append(part).append('\n');
224 }
225 panel.add(new JLabel("<html><body width=\"500\"><b>"+b.toString().trim()+"</b></body></html>"), GBC.eol().insets(0, 0, 0, 10));
226 if (details != null && !details.isEmpty()) {
227 panel.add(new JLabel(tr("Details:")), GBC.eol().insets(0, 0, 0, 10));
228 JosmTextArea area = new JosmTextArea(details);
229 area.setEditable(false);
230 area.setLineWrap(true);
231 area.setWrapStyleWord(true);
232 JScrollPane scrollPane = new JScrollPane(area);
233 scrollPane.setPreferredSize(new Dimension(500, 300));
234 panel.add(scrollPane, GBC.eol().fill());
235 }
236 JOptionPane.showMessageDialog(monitor.getWindowParent(), panel, title, JOptionPane.ERROR_MESSAGE);
237 });
238 }
239
240 /**
241 * Writes the list of plugins to a cache file
242 *
243 * @param site the site from where the list was downloaded
244 * @param list the downloaded list
245 */
246 protected void cachePluginList(String site, String list) {
247 File pluginDir = Preferences.main().getPluginsDirectory();
248 if (!pluginDir.exists() && !pluginDir.mkdirs()) {
249 Logging.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.",
250 pluginDir.toString(), site));
251 }
252 File cacheFile = createSiteCacheFile(pluginDir, site);
253 getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
254 try (PrintWriter writer = new PrintWriter(cacheFile, StandardCharsets.UTF_8.name())) {
255 writer.write(list);
256 writer.flush();
257 } catch (IOException e) {
258 // just failed to write the cache file. No big deal, but log the exception anyway
259 Logging.error(e);
260 }
261 }
262
263 /**
264 * Filter information about deprecated plugins from the list of downloaded
265 * plugins
266 *
267 * @param plugins the plugin informations
268 * @return the plugin informations, without deprecated plugins
269 */
270 protected List<PluginInformation> filterDeprecatedPlugins(List<PluginInformation> plugins) {
271 List<PluginInformation> ret = new ArrayList<>(plugins.size());
272 Set<String> deprecatedPluginNames = new HashSet<>();
273 for (PluginHandler.DeprecatedPlugin p : PluginHandler.DEPRECATED_PLUGINS) {
274 deprecatedPluginNames.add(p.name);
275 }
276 for (PluginInformation plugin: plugins) {
277 if (deprecatedPluginNames.contains(plugin.name)) {
278 continue;
279 }
280 ret.add(plugin);
281 }
282 return ret;
283 }
284
285 /**
286 * Parses the plugin list
287 *
288 * @param site the site from where the list was downloaded
289 * @param doc the document with the plugin list
290 */
291 protected void parsePluginListDocument(String site, String doc) {
292 try {
293 getProgressMonitor().subTask(tr("Parsing plugin list from site ''{0}''", site));
294 InputStream in = new ByteArrayInputStream(doc.getBytes(StandardCharsets.UTF_8));
295 List<PluginInformation> pis = new PluginListParser().parse(in);
296 availablePlugins.addAll(filterDeprecatedPlugins(pis));
297 } catch (PluginListParseException e) {
298 Logging.error(tr("Failed to parse plugin list document from site ''{0}''. Skipping site. Exception was: {1}", site, e.toString()));
299 Logging.error(e);
300 }
301 }
302
303 @Override
304 protected void realRun() throws SAXException, IOException, OsmTransferException {
305 if (sites == null) return;
306 getProgressMonitor().setTicksCount(sites.size() * 3);
307
308 // collect old cache files and remove if no longer in use
309 List<File> siteCacheFiles = new LinkedList<>();
310 for (String location : PluginInformation.getPluginLocations()) {
311 File[] f = new File(location).listFiles(
312 (FilenameFilter) (dir, name) -> name.matches("^([0-9]+-)?site.*\\.txt$") ||
313 name.matches("^([0-9]+-)?site.*-icons\\.zip$")
314 );
315 if (f != null && f.length > 0) {
316 siteCacheFiles.addAll(Arrays.asList(f));
317 }
318 }
319
320 File pluginDir = Preferences.main().getPluginsDirectory();
321 for (String site: sites) {
322 String printsite = site.replaceAll("%<(.*)>", "");
323 getProgressMonitor().subTask(tr("Processing plugin list from site ''{0}''", printsite));
324 String list = downloadPluginList(site, getProgressMonitor().createSubTaskMonitor(0, false));
325 if (canceled) return;
326 siteCacheFiles.remove(createSiteCacheFile(pluginDir, site));
327 if (list != null) {
328 getProgressMonitor().worked(1);
329 cachePluginList(site, list);
330 if (canceled) return;
331 getProgressMonitor().worked(1);
332 parsePluginListDocument(site, list);
333 if (canceled) return;
334 getProgressMonitor().worked(1);
335 if (canceled) return;
336 }
337 }
338 // remove old stuff or whole update process is broken
339 for (File file: siteCacheFiles) {
340 Utils.deleteFile(file);
341 }
342 }
343
344 /**
345 * Replies true if the task was canceled
346 * @return <code>true</code> if the task was stopped by the user
347 */
348 public boolean isCanceled() {
349 return canceled;
350 }
351
352 /**
353 * Replies the list of plugins described in the downloaded plugin lists
354 *
355 * @return the list of plugins
356 * @since 5601
357 */
358 public List<PluginInformation> getAvailablePlugins() {
359 return availablePlugins;
360 }
361}
Note: See TracBrowser for help on using the repository browser.