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

Last change on this file since 10781 was 10616, checked in by Don-vip, 8 years ago

see #11390 - sonar - squid:S1604 - Java 8: Anonymous inner classes containing only one method should become lambdas

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