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

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

do not block start when plugin list cannot be retrieved, save the error for later display in global network errors message dialog

  • Property svn:eol-style set to native
File size: 17.0 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.BufferedReader;
9import java.io.ByteArrayInputStream;
10import java.io.File;
11import java.io.FileOutputStream;
12import java.io.FilenameFilter;
13import java.io.IOException;
14import java.io.InputStream;
15import java.io.InputStreamReader;
16import java.io.OutputStream;
17import java.io.OutputStreamWriter;
18import java.io.PrintWriter;
19import java.net.HttpURLConnection;
20import java.net.MalformedURLException;
21import java.net.URL;
22import java.util.ArrayList;
23import java.util.Arrays;
24import java.util.Collection;
25import java.util.Collections;
26import java.util.HashSet;
27import java.util.LinkedList;
28import java.util.List;
29
30import javax.swing.JLabel;
31import javax.swing.JOptionPane;
32import javax.swing.JPanel;
33import javax.swing.JScrollPane;
34
35import org.openstreetmap.josm.Main;
36import org.openstreetmap.josm.gui.PleaseWaitRunnable;
37import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
38import org.openstreetmap.josm.gui.progress.ProgressMonitor;
39import org.openstreetmap.josm.gui.util.GuiHelper;
40import org.openstreetmap.josm.gui.widgets.JosmTextArea;
41import org.openstreetmap.josm.io.OsmTransferException;
42import org.openstreetmap.josm.tools.GBC;
43import org.openstreetmap.josm.tools.ImageProvider;
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 HttpURLConnection connection;
56 private List<PluginInformation> availablePlugins;
57 private boolean displayErrMsg;
58
59 protected enum CacheType {PLUGIN_LIST, ICON_LIST}
60
61 protected void init(Collection<String> sites, boolean displayErrMsg){
62 this.sites = sites;
63 if (sites == null) {
64 this.sites = Collections.emptySet();
65 }
66 this.availablePlugins = new LinkedList<PluginInformation>();
67 this.displayErrMsg = displayErrMsg;
68 }
69 /**
70 * Creates the task
71 *
72 * @param sites the collection of download sites. Defaults to the empty collection if null.
73 */
74 public ReadRemotePluginInformationTask(Collection<String> sites) {
75 super(tr("Download plugin list..."), false /* don't ignore exceptions */);
76 init(sites, true);
77 }
78
79 /**
80 * Creates the task
81 *
82 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null
83 * @param sites the collection of download sites. Defaults to the empty collection if null.
84 * @param displayErrMsg if {@code true}, a blocking error message is displayed in case of I/O exception.
85 */
86 public ReadRemotePluginInformationTask(ProgressMonitor monitor, Collection<String> sites, boolean displayErrMsg) {
87 super(tr("Download plugin list..."), monitor == null ? NullProgressMonitor.INSTANCE: monitor, false /* don't ignore exceptions */);
88 init(sites, displayErrMsg);
89 }
90
91
92 @Override
93 protected void cancel() {
94 canceled = true;
95 synchronized(this) {
96 if (connection != null) {
97 connection.disconnect();
98 }
99 }
100 }
101
102 @Override
103 protected void finish() {}
104
105 /**
106 * Creates the file name for the cached plugin list and the icon cache
107 * file.
108 *
109 * @param site the name of the site
110 * @param type icon cache or plugin list cache
111 * @return the file name for the cache file
112 */
113 protected File createSiteCacheFile(File pluginDir, String site, CacheType type) {
114 String name;
115 try {
116 site = site.replaceAll("%<(.*)>", "");
117 URL url = new URL(site);
118 StringBuilder sb = new StringBuilder();
119 sb.append("site-");
120 sb.append(url.getHost()).append("-");
121 if (url.getPort() != -1) {
122 sb.append(url.getPort()).append("-");
123 }
124 String path = url.getPath();
125 for (int i =0;i<path.length(); i++) {
126 char c = path.charAt(i);
127 if (Character.isLetterOrDigit(c)) {
128 sb.append(c);
129 } else {
130 sb.append("_");
131 }
132 }
133 switch (type) {
134 case PLUGIN_LIST:
135 sb.append(".txt");
136 break;
137 case ICON_LIST:
138 sb.append("-icons.zip");
139 break;
140 }
141 name = sb.toString();
142 } catch(MalformedURLException e) {
143 name = "site-unknown.txt";
144 }
145 return new File(pluginDir, name);
146 }
147
148 /**
149 * Downloads the list from a remote location
150 *
151 * @param site the site URL
152 * @param monitor a progress monitor
153 * @return the downloaded list
154 */
155 protected String downloadPluginList(String site, final ProgressMonitor monitor) {
156 BufferedReader in = null;
157
158 /* replace %<x> with empty string or x=plugins (separated with comma) */
159 String pl = Utils.join(",", Main.pref.getCollection("plugins"));
160 String printsite = site.replaceAll("%<(.*)>", "");
161 if (pl != null && pl.length() != 0) {
162 site = site.replaceAll("%<(.*)>", "$1"+pl);
163 } else {
164 site = printsite;
165 }
166
167 try {
168 monitor.beginTask("");
169 monitor.indeterminateSubTask(tr("Downloading plugin list from ''{0}''", printsite));
170
171 URL url = new URL(site);
172 synchronized(this) {
173 connection = Utils.openHttpConnection(url);
174 connection.setRequestProperty("Cache-Control", "no-cache");
175 connection.setRequestProperty("Accept-Charset", "utf-8");
176 }
177 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Utils.UTF_8));
178 StringBuilder sb = new StringBuilder();
179 String line;
180 while ((line = in.readLine()) != null) {
181 sb.append(line).append("\n");
182 }
183 return sb.toString();
184 } catch (MalformedURLException e) {
185 if (canceled) return null;
186 Main.error(e);
187 return null;
188 } catch (IOException e) {
189 if (canceled) return null;
190 Main.addNetworkError(site, e);
191 handleIOException(monitor, e, tr("Plugin list download error"), tr("JOSM failed to download plugin list:"), displayErrMsg);
192 return null;
193 } finally {
194 synchronized(this) {
195 if (connection != null) {
196 connection.disconnect();
197 }
198 connection = null;
199 }
200 Utils.close(in);
201 monitor.finishTask();
202 }
203 }
204
205 private void handleIOException(final ProgressMonitor monitor, IOException e, final String title, final String firstMessage, boolean displayMsg) {
206 InputStream errStream = connection.getErrorStream();
207 StringBuilder sb = new StringBuilder();
208 if (errStream != null) {
209 BufferedReader err = null;
210 try {
211 String line;
212 err = new BufferedReader(new InputStreamReader(errStream, Utils.UTF_8));
213 while ((line = err.readLine()) != null) {
214 sb.append(line).append("\n");
215 }
216 } catch (Exception ex) {
217 Main.error(e);
218 Main.error(ex);
219 } finally {
220 Utils.close(err);
221 }
222 }
223 final String msg = e.getMessage();
224 final String details = sb.toString();
225 if (details.isEmpty()) {
226 Main.error(e.getClass().getSimpleName()+": " + msg);
227 } else {
228 Main.error(msg + " - Details:\n" + details);
229 }
230
231 if (displayMsg) {
232 displayErrorMessage(monitor, msg, details, title, firstMessage);
233 }
234 }
235
236 private void displayErrorMessage(final ProgressMonitor monitor, final String msg, final String details, final String title, final String firstMessage) {
237 GuiHelper.runInEDTAndWait(new Runnable() {
238 @Override public void run() {
239 JPanel panel = new JPanel(new GridBagLayout());
240 panel.add(new JLabel(firstMessage), GBC.eol().insets(0, 0, 0, 10));
241 StringBuilder b = new StringBuilder();
242 for (String part : msg.split("(?<=\\G.{200})")) {
243 b.append(part).append("\n");
244 }
245 panel.add(new JLabel("<html><body width=\"500\"><b>"+b.toString().trim()+"</b></body></html>"), GBC.eol().insets(0, 0, 0, 10));
246 if (!details.isEmpty()) {
247 panel.add(new JLabel(tr("Details:")), GBC.eol().insets(0, 0, 0, 10));
248 JosmTextArea area = new JosmTextArea(details);
249 area.setEditable(false);
250 area.setLineWrap(true);
251 area.setWrapStyleWord(true);
252 JScrollPane scrollPane = new JScrollPane(area);
253 scrollPane.setPreferredSize(new Dimension(500, 300));
254 panel.add(scrollPane, GBC.eol().fill());
255 }
256 JOptionPane.showMessageDialog(monitor.getWindowParent(), panel, title, JOptionPane.ERROR_MESSAGE);
257 }
258 });
259 }
260
261 /**
262 * Downloads the icon archive from a remote location
263 *
264 * @param site the site URL
265 * @param monitor a progress monitor
266 */
267 protected void downloadPluginIcons(String site, File destFile, ProgressMonitor monitor) {
268 InputStream in = null;
269 OutputStream out = null;
270 try {
271 site = site.replaceAll("%<(.*)>", "");
272
273 monitor.beginTask("");
274 monitor.indeterminateSubTask(tr("Downloading plugin list from ''{0}''", site));
275
276 URL url = new URL(site);
277 synchronized(this) {
278 connection = Utils.openHttpConnection(url);
279 connection.setRequestProperty("Cache-Control", "no-cache");
280 }
281 in = connection.getInputStream();
282 out = new FileOutputStream(destFile);
283 byte[] buffer = new byte[8192];
284 for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
285 out.write(buffer, 0, read);
286 }
287 } catch (MalformedURLException e) {
288 if (canceled) return;
289 Main.error(e);
290 return;
291 } catch (IOException e) {
292 if (canceled) return;
293 handleIOException(monitor, e, tr("Plugin icons download error"), tr("JOSM failed to download plugin icons:"), displayErrMsg);
294 return;
295 } finally {
296 Utils.close(out);
297 synchronized(this) {
298 if (connection != null) {
299 connection.disconnect();
300 }
301 connection = null;
302 }
303 Utils.close(in);
304 monitor.finishTask();
305 }
306 for (PluginInformation pi : availablePlugins) {
307 if (pi.icon == null && pi.iconPath != null) {
308 pi.icon = new ImageProvider(pi.name+".jar/"+pi.iconPath)
309 .setArchive(destFile)
310 .setMaxWidth(24)
311 .setMaxHeight(24)
312 .setOptional(true).get();
313 }
314 }
315 }
316
317 /**
318 * Writes the list of plugins to a cache file
319 *
320 * @param site the site from where the list was downloaded
321 * @param list the downloaded list
322 */
323 protected void cachePluginList(String site, String list) {
324 PrintWriter writer = null;
325 try {
326 File pluginDir = Main.pref.getPluginsDirectory();
327 if (!pluginDir.exists()) {
328 if (! pluginDir.mkdirs()) {
329 Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", pluginDir.toString(), site));
330 }
331 }
332 File cacheFile = createSiteCacheFile(pluginDir, site, CacheType.PLUGIN_LIST);
333 getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
334 writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), Utils.UTF_8));
335 writer.write(list);
336 } catch(IOException e) {
337 // just failed to write the cache file. No big deal, but log the exception anyway
338 Main.error(e);
339 } finally {
340 if (writer != null) {
341 writer.flush();
342 Utils.close(writer);
343 }
344 }
345 }
346
347 /**
348 * Filter information about deprecated plugins from the list of downloaded
349 * plugins
350 *
351 * @param plugins the plugin informations
352 * @return the plugin informations, without deprecated plugins
353 */
354 protected List<PluginInformation> filterDeprecatedPlugins(List<PluginInformation> plugins) {
355 List<PluginInformation> ret = new ArrayList<PluginInformation>(plugins.size());
356 HashSet<String> deprecatedPluginNames = new HashSet<String>();
357 for (PluginHandler.DeprecatedPlugin p : PluginHandler.DEPRECATED_PLUGINS) {
358 deprecatedPluginNames.add(p.name);
359 }
360 for (PluginInformation plugin: plugins) {
361 if (deprecatedPluginNames.contains(plugin.name)) {
362 continue;
363 }
364 ret.add(plugin);
365 }
366 return ret;
367 }
368
369 /**
370 * Parses the plugin list
371 *
372 * @param site the site from where the list was downloaded
373 * @param doc the document with the plugin list
374 */
375 protected void parsePluginListDocument(String site, String doc) {
376 try {
377 getProgressMonitor().subTask(tr("Parsing plugin list from site ''{0}''", site));
378 InputStream in = new ByteArrayInputStream(doc.getBytes(Utils.UTF_8));
379 List<PluginInformation> pis = new PluginListParser().parse(in);
380 availablePlugins.addAll(filterDeprecatedPlugins(pis));
381 } catch (PluginListParseException e) {
382 Main.error(tr("Failed to parse plugin list document from site ''{0}''. Skipping site. Exception was: {1}", site, e.toString()));
383 Main.error(e);
384 }
385 }
386
387 @Override
388 protected void realRun() throws SAXException, IOException, OsmTransferException {
389 if (sites == null) return;
390 getProgressMonitor().setTicksCount(sites.size() * 3);
391 File pluginDir = Main.pref.getPluginsDirectory();
392
393 // collect old cache files and remove if no longer in use
394 List<File> siteCacheFiles = new LinkedList<File>();
395 for (String location : PluginInformation.getPluginLocations()) {
396 File [] f = new File(location).listFiles(
397 new FilenameFilter() {
398 @Override
399 public boolean accept(File dir, String name) {
400 return name.matches("^([0-9]+-)?site.*\\.txt$") ||
401 name.matches("^([0-9]+-)?site.*-icons\\.zip$");
402 }
403 }
404 );
405 if(f != null && f.length > 0) {
406 siteCacheFiles.addAll(Arrays.asList(f));
407 }
408 }
409
410 for (String site: sites) {
411 String printsite = site.replaceAll("%<(.*)>", "");
412 getProgressMonitor().subTask(tr("Processing plugin list from site ''{0}''", printsite));
413 String list = downloadPluginList(site, getProgressMonitor().createSubTaskMonitor(0, false));
414 if (canceled) return;
415 siteCacheFiles.remove(createSiteCacheFile(pluginDir, site, CacheType.PLUGIN_LIST));
416 siteCacheFiles.remove(createSiteCacheFile(pluginDir, site, CacheType.ICON_LIST));
417 if(list != null)
418 {
419 getProgressMonitor().worked(1);
420 cachePluginList(site, list);
421 if (canceled) return;
422 getProgressMonitor().worked(1);
423 parsePluginListDocument(site, list);
424 if (canceled) return;
425 getProgressMonitor().worked(1);
426 if (canceled) return;
427 }
428 downloadPluginIcons(site+"-icons.zip", createSiteCacheFile(pluginDir, site, CacheType.ICON_LIST), getProgressMonitor().createSubTaskMonitor(0, false));
429 }
430 for (File file: siteCacheFiles) /* remove old stuff or whole update process is broken */
431 {
432 file.delete();
433 }
434 }
435
436 /**
437 * Replies true if the task was canceled
438 * @return <code>true</code> if the task was stopped by the user
439 */
440 public boolean isCanceled() {
441 return canceled;
442 }
443
444 /**
445 * Replies the list of plugins described in the downloaded plugin lists
446 *
447 * @return the list of plugins
448 * @since 5601
449 */
450 public List<PluginInformation> getAvailablePlugins() {
451 return availablePlugins;
452 }
453}
Note: See TracBrowser for help on using the repository browser.