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

Last change on this file since 8308 was 8290, checked in by Don-vip, 9 years ago

code cleanup

  • Property svn:eol-style set to native
File size: 14.2 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.OutputStreamWriter;
17import java.io.PrintWriter;
18import java.net.HttpURLConnection;
19import java.net.MalformedURLException;
20import java.net.URL;
21import java.nio.charset.StandardCharsets;
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.Utils;
44import org.xml.sax.SAXException;
45
46/**
47 * An asynchronous task for downloading plugin lists from the configured plugin download sites.
48 * @since 2817
49 */
50public class ReadRemotePluginInformationTask extends PleaseWaitRunnable {
51
52 private Collection<String> sites;
53 private boolean canceled;
54 private HttpURLConnection connection;
55 private List<PluginInformation> availablePlugins;
56 private boolean displayErrMsg;
57
58 protected final void init(Collection<String> sites, boolean displayErrMsg) {
59 this.sites = sites;
60 if (sites == null) {
61 this.sites = Collections.emptySet();
62 }
63 this.availablePlugins = new LinkedList<>();
64 this.displayErrMsg = displayErrMsg;
65 }
66
67 /**
68 * Constructs a new {@code ReadRemotePluginInformationTask}.
69 *
70 * @param sites the collection of download sites. Defaults to the empty collection if null.
71 */
72 public ReadRemotePluginInformationTask(Collection<String> sites) {
73 super(tr("Download plugin list..."), false /* don't ignore exceptions */);
74 init(sites, true);
75 }
76
77 /**
78 * Constructs a new {@code ReadRemotePluginInformationTask}.
79 *
80 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null
81 * @param sites the collection of download sites. Defaults to the empty collection if null.
82 * @param displayErrMsg if {@code true}, a blocking error message is displayed in case of I/O exception.
83 */
84 public ReadRemotePluginInformationTask(ProgressMonitor monitor, Collection<String> sites, boolean displayErrMsg) {
85 super(tr("Download plugin list..."), monitor == null ? NullProgressMonitor.INSTANCE: monitor, false /* don't ignore exceptions */);
86 init(sites, displayErrMsg);
87 }
88
89 @Override
90 protected void cancel() {
91 canceled = true;
92 synchronized(this) {
93 if (connection != null) {
94 connection.disconnect();
95 }
96 }
97 }
98
99 @Override
100 protected void finish() {}
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 sb.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(",", Main.pref.getCollection("plugins"));
147 String printsite = site.replaceAll("%<(.*)>", "");
148 if (pl != null && pl.length() != 0) {
149 site = site.replaceAll("%<(.*)>", "$1"+pl);
150 } else {
151 site = printsite;
152 }
153
154 try {
155 monitor.beginTask("");
156 monitor.indeterminateSubTask(tr("Downloading plugin list from ''{0}''", printsite));
157
158 URL url = new URL(site);
159 synchronized(this) {
160 connection = Utils.openHttpConnection(url);
161 connection.setRequestProperty("Cache-Control", "no-cache");
162 connection.setRequestProperty("Accept-Charset", "utf-8");
163 }
164 try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
165 StringBuilder sb = new StringBuilder();
166 String line;
167 while ((line = in.readLine()) != null) {
168 sb.append(line).append("\n");
169 }
170 return sb.toString();
171 }
172 } catch (MalformedURLException e) {
173 if (canceled) return null;
174 Main.error(e);
175 return null;
176 } catch (IOException e) {
177 if (canceled) return null;
178 Main.addNetworkError(site, e);
179 handleIOException(monitor, e, tr("Plugin list download error"), tr("JOSM failed to download plugin list:"), displayErrMsg);
180 return null;
181 } finally {
182 synchronized(this) {
183 if (connection != null) {
184 connection.disconnect();
185 }
186 connection = null;
187 }
188 monitor.finishTask();
189 }
190 }
191
192 private void handleIOException(final ProgressMonitor monitor, IOException e, final String title, final String firstMessage, boolean displayMsg) {
193 StringBuilder sb = new StringBuilder();
194 try (InputStream errStream = connection.getErrorStream()) {
195 if (errStream != null) {
196 try (BufferedReader err = new BufferedReader(new InputStreamReader(errStream, StandardCharsets.UTF_8))) {
197 String line;
198 while ((line = err.readLine()) != null) {
199 sb.append(line).append("\n");
200 }
201 } catch (Exception ex) {
202 Main.error(e);
203 Main.error(ex);
204 }
205 }
206 } catch (IOException ex) {
207 Main.warn(ex);
208 }
209 final String msg = e.getMessage();
210 final String details = sb.toString();
211 if (details.isEmpty()) {
212 Main.error(e.getClass().getSimpleName()+": " + msg);
213 } else {
214 Main.error(msg + " - Details:\n" + details);
215 }
216
217 if (displayMsg) {
218 displayErrorMessage(monitor, msg, details, title, firstMessage);
219 }
220 }
221
222 private void displayErrorMessage(final ProgressMonitor monitor, final String msg, final String details, final String title, final String firstMessage) {
223 GuiHelper.runInEDTAndWait(new Runnable() {
224 @Override public void run() {
225 JPanel panel = new JPanel(new GridBagLayout());
226 panel.add(new JLabel(firstMessage), GBC.eol().insets(0, 0, 0, 10));
227 StringBuilder b = new StringBuilder();
228 for (String part : msg.split("(?<=\\G.{200})")) {
229 b.append(part).append("\n");
230 }
231 panel.add(new JLabel("<html><body width=\"500\"><b>"+b.toString().trim()+"</b></body></html>"), GBC.eol().insets(0, 0, 0, 10));
232 if (!details.isEmpty()) {
233 panel.add(new JLabel(tr("Details:")), GBC.eol().insets(0, 0, 0, 10));
234 JosmTextArea area = new JosmTextArea(details);
235 area.setEditable(false);
236 area.setLineWrap(true);
237 area.setWrapStyleWord(true);
238 JScrollPane scrollPane = new JScrollPane(area);
239 scrollPane.setPreferredSize(new Dimension(500, 300));
240 panel.add(scrollPane, GBC.eol().fill());
241 }
242 JOptionPane.showMessageDialog(monitor.getWindowParent(), panel, title, JOptionPane.ERROR_MESSAGE);
243 }
244 });
245 }
246
247 /**
248 * Writes the list of plugins to a cache file
249 *
250 * @param site the site from where the list was downloaded
251 * @param list the downloaded list
252 */
253 protected void cachePluginList(String site, String list) {
254 File pluginDir = Main.pref.getPluginsDirectory();
255 if (!pluginDir.exists() && !pluginDir.mkdirs()) {
256 Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", pluginDir.toString(), site));
257 }
258 File cacheFile = createSiteCacheFile(pluginDir, site);
259 getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
260 try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), StandardCharsets.UTF_8))) {
261 writer.write(list);
262 writer.flush();
263 } catch(IOException e) {
264 // just failed to write the cache file. No big deal, but log the exception anyway
265 Main.error(e);
266 }
267 }
268
269 /**
270 * Filter information about deprecated plugins from the list of downloaded
271 * plugins
272 *
273 * @param plugins the plugin informations
274 * @return the plugin informations, without deprecated plugins
275 */
276 protected List<PluginInformation> filterDeprecatedPlugins(List<PluginInformation> plugins) {
277 List<PluginInformation> ret = new ArrayList<>(plugins.size());
278 HashSet<String> deprecatedPluginNames = new HashSet<>();
279 for (PluginHandler.DeprecatedPlugin p : PluginHandler.DEPRECATED_PLUGINS) {
280 deprecatedPluginNames.add(p.name);
281 }
282 for (PluginInformation plugin: plugins) {
283 if (deprecatedPluginNames.contains(plugin.name)) {
284 continue;
285 }
286 ret.add(plugin);
287 }
288 return ret;
289 }
290
291 /**
292 * Parses the plugin list
293 *
294 * @param site the site from where the list was downloaded
295 * @param doc the document with the plugin list
296 */
297 protected void parsePluginListDocument(String site, String doc) {
298 try {
299 getProgressMonitor().subTask(tr("Parsing plugin list from site ''{0}''", site));
300 InputStream in = new ByteArrayInputStream(doc.getBytes(StandardCharsets.UTF_8));
301 List<PluginInformation> pis = new PluginListParser().parse(in);
302 availablePlugins.addAll(filterDeprecatedPlugins(pis));
303 } catch (PluginListParseException e) {
304 Main.error(tr("Failed to parse plugin list document from site ''{0}''. Skipping site. Exception was: {1}", site, e.toString()));
305 Main.error(e);
306 }
307 }
308
309 @Override
310 protected void realRun() throws SAXException, IOException, OsmTransferException {
311 if (sites == null) return;
312 getProgressMonitor().setTicksCount(sites.size() * 3);
313 File pluginDir = Main.pref.getPluginsDirectory();
314
315 // collect old cache files and remove if no longer in use
316 List<File> siteCacheFiles = new LinkedList<>();
317 for (String location : PluginInformation.getPluginLocations()) {
318 File [] f = new File(location).listFiles(
319 new FilenameFilter() {
320 @Override
321 public boolean accept(File dir, String name) {
322 return name.matches("^([0-9]+-)?site.*\\.txt$") ||
323 name.matches("^([0-9]+-)?site.*-icons\\.zip$");
324 }
325 }
326 );
327 if(f != null && f.length > 0) {
328 siteCacheFiles.addAll(Arrays.asList(f));
329 }
330 }
331
332 for (String site: sites) {
333 String printsite = site.replaceAll("%<(.*)>", "");
334 getProgressMonitor().subTask(tr("Processing plugin list from site ''{0}''", printsite));
335 String list = downloadPluginList(site, getProgressMonitor().createSubTaskMonitor(0, false));
336 if (canceled) return;
337 siteCacheFiles.remove(createSiteCacheFile(pluginDir, site));
338 if (list != null) {
339 getProgressMonitor().worked(1);
340 cachePluginList(site, list);
341 if (canceled) return;
342 getProgressMonitor().worked(1);
343 parsePluginListDocument(site, list);
344 if (canceled) return;
345 getProgressMonitor().worked(1);
346 if (canceled) return;
347 }
348 }
349 // remove old stuff or whole update process is broken
350 for (File file: siteCacheFiles) {
351 file.delete();
352 }
353 }
354
355 /**
356 * Replies true if the task was canceled
357 * @return <code>true</code> if the task was stopped by the user
358 */
359 public boolean isCanceled() {
360 return canceled;
361 }
362
363 /**
364 * Replies the list of plugins described in the downloaded plugin lists
365 *
366 * @return the list of plugins
367 * @since 5601
368 */
369 public List<PluginInformation> getAvailablePlugins() {
370 return availablePlugins;
371 }
372}
Note: See TracBrowser for help on using the repository browser.