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

Last change on this file since 9171 was 9171, checked in by simon04, 8 years ago

see #12231 - Use HttpClient instead of some Utils.openHttpConnection usages

  • Property svn:eol-style set to native
File size: 13.1 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.Response 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
101 /**
102 * Creates the file name for the cached plugin list and the icon cache file.
103 *
104 * @param pluginDir directory of plugin for data storage
105 * @param site the name of the site
106 * @return the file name for the cache file
107 */
108 protected File createSiteCacheFile(File pluginDir, String site) {
109 String name;
110 try {
111 site = site.replaceAll("%<(.*)>", "");
112 URL url = new URL(site);
113 StringBuilder sb = new StringBuilder();
114 sb.append("site-")
115 .append(url.getHost()).append('-');
116 if (url.getPort() != -1) {
117 sb.append(url.getPort()).append('-');
118 }
119 String path = url.getPath();
120 for (int i = 0; i < path.length(); i++) {
121 char c = path.charAt(i);
122 if (Character.isLetterOrDigit(c)) {
123 sb.append(c);
124 } else {
125 sb.append('_');
126 }
127 }
128 sb.append(".txt");
129 name = sb.toString();
130 } catch (MalformedURLException e) {
131 name = "site-unknown.txt";
132 }
133 return new File(pluginDir, name);
134 }
135
136 /**
137 * Downloads the list from a remote location
138 *
139 * @param site the site URL
140 * @param monitor a progress monitor
141 * @return the downloaded list
142 */
143 protected String downloadPluginList(String site, final ProgressMonitor monitor) {
144 /* replace %<x> with empty string or x=plugins (separated with comma) */
145 String pl = Utils.join(",", Main.pref.getCollection("plugins"));
146 String printsite = site.replaceAll("%<(.*)>", "");
147 if (pl != null && !pl.isEmpty()) {
148 site = site.replaceAll("%<(.*)>", "$1"+pl);
149 } else {
150 site = printsite;
151 }
152
153 String content = null;
154 try {
155 monitor.beginTask("");
156 monitor.indeterminateSubTask(tr("Downloading plugin list from ''{0}''", printsite));
157
158 URL url = new URL(site);
159 connection = HttpClient.create(url).useCache(false).connect();
160 content = connection.fetchContent();
161 if (connection.getResponseCode() != 200) {
162 throw new IOException(tr("Unsuccessful HTTP request"));
163 }
164 return content;
165 } catch (MalformedURLException e) {
166 if (canceled) return null;
167 Main.error(e);
168 return null;
169 } catch (IOException e) {
170 if (canceled) return null;
171 handleIOException(monitor, e, content);
172 return null;
173 } finally {
174 synchronized (this) {
175 if (connection != null) {
176 connection.disconnect();
177 }
178 connection = null;
179 }
180 monitor.finishTask();
181 }
182 }
183
184 private void handleIOException(final ProgressMonitor monitor, IOException e, String details) {
185 final String msg = e.getMessage();
186 if (details.isEmpty()) {
187 Main.error(e.getClass().getSimpleName()+": " + msg);
188 } else {
189 Main.error(msg + " - Details:\n" + details);
190 }
191
192 if (displayErrMsg) {
193 displayErrorMessage(monitor, msg, details, tr("Plugin list download error"), tr("JOSM failed to download plugin list:"));
194 }
195 }
196
197 private void displayErrorMessage(final ProgressMonitor monitor, final String msg, final String details, final String title,
198 final String firstMessage) {
199 GuiHelper.runInEDTAndWait(new Runnable() {
200 @Override public void run() {
201 JPanel panel = new JPanel(new GridBagLayout());
202 panel.add(new JLabel(firstMessage), GBC.eol().insets(0, 0, 0, 10));
203 StringBuilder b = new StringBuilder();
204 for (String part : msg.split("(?<=\\G.{200})")) {
205 b.append(part).append('\n');
206 }
207 panel.add(new JLabel("<html><body width=\"500\"><b>"+b.toString().trim()+"</b></body></html>"), GBC.eol().insets(0, 0, 0, 10));
208 if (!details.isEmpty()) {
209 panel.add(new JLabel(tr("Details:")), GBC.eol().insets(0, 0, 0, 10));
210 JosmTextArea area = new JosmTextArea(details);
211 area.setEditable(false);
212 area.setLineWrap(true);
213 area.setWrapStyleWord(true);
214 JScrollPane scrollPane = new JScrollPane(area);
215 scrollPane.setPreferredSize(new Dimension(500, 300));
216 panel.add(scrollPane, GBC.eol().fill());
217 }
218 JOptionPane.showMessageDialog(monitor.getWindowParent(), panel, title, JOptionPane.ERROR_MESSAGE);
219 }
220 });
221 }
222
223 /**
224 * Writes the list of plugins to a cache file
225 *
226 * @param site the site from where the list was downloaded
227 * @param list the downloaded list
228 */
229 protected void cachePluginList(String site, String list) {
230 File pluginDir = Main.pref.getPluginsDirectory();
231 if (!pluginDir.exists() && !pluginDir.mkdirs()) {
232 Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.",
233 pluginDir.toString(), site));
234 }
235 File cacheFile = createSiteCacheFile(pluginDir, site);
236 getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
237 try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), StandardCharsets.UTF_8))) {
238 writer.write(list);
239 writer.flush();
240 } catch (IOException e) {
241 // just failed to write the cache file. No big deal, but log the exception anyway
242 Main.error(e);
243 }
244 }
245
246 /**
247 * Filter information about deprecated plugins from the list of downloaded
248 * plugins
249 *
250 * @param plugins the plugin informations
251 * @return the plugin informations, without deprecated plugins
252 */
253 protected List<PluginInformation> filterDeprecatedPlugins(List<PluginInformation> plugins) {
254 List<PluginInformation> ret = new ArrayList<>(plugins.size());
255 Set<String> deprecatedPluginNames = new HashSet<>();
256 for (PluginHandler.DeprecatedPlugin p : PluginHandler.DEPRECATED_PLUGINS) {
257 deprecatedPluginNames.add(p.name);
258 }
259 for (PluginInformation plugin: plugins) {
260 if (deprecatedPluginNames.contains(plugin.name)) {
261 continue;
262 }
263 ret.add(plugin);
264 }
265 return ret;
266 }
267
268 /**
269 * Parses the plugin list
270 *
271 * @param site the site from where the list was downloaded
272 * @param doc the document with the plugin list
273 */
274 protected void parsePluginListDocument(String site, String doc) {
275 try {
276 getProgressMonitor().subTask(tr("Parsing plugin list from site ''{0}''", site));
277 InputStream in = new ByteArrayInputStream(doc.getBytes(StandardCharsets.UTF_8));
278 List<PluginInformation> pis = new PluginListParser().parse(in);
279 availablePlugins.addAll(filterDeprecatedPlugins(pis));
280 } catch (PluginListParseException e) {
281 Main.error(tr("Failed to parse plugin list document from site ''{0}''. Skipping site. Exception was: {1}", site, e.toString()));
282 Main.error(e);
283 }
284 }
285
286 @Override
287 protected void realRun() throws SAXException, IOException, OsmTransferException {
288 if (sites == null) return;
289 getProgressMonitor().setTicksCount(sites.size() * 3);
290
291 // collect old cache files and remove if no longer in use
292 List<File> siteCacheFiles = new LinkedList<>();
293 for (String location : PluginInformation.getPluginLocations()) {
294 File[] f = new File(location).listFiles(
295 new FilenameFilter() {
296 @Override
297 public boolean accept(File dir, String name) {
298 return name.matches("^([0-9]+-)?site.*\\.txt$") ||
299 name.matches("^([0-9]+-)?site.*-icons\\.zip$");
300 }
301 }
302 );
303 if (f != null && f.length > 0) {
304 siteCacheFiles.addAll(Arrays.asList(f));
305 }
306 }
307
308 File pluginDir = Main.pref.getPluginsDirectory();
309 for (String site: sites) {
310 String printsite = site.replaceAll("%<(.*)>", "");
311 getProgressMonitor().subTask(tr("Processing plugin list from site ''{0}''", printsite));
312 String list = downloadPluginList(site, getProgressMonitor().createSubTaskMonitor(0, false));
313 if (canceled) return;
314 siteCacheFiles.remove(createSiteCacheFile(pluginDir, site));
315 if (list != null) {
316 getProgressMonitor().worked(1);
317 cachePluginList(site, list);
318 if (canceled) return;
319 getProgressMonitor().worked(1);
320 parsePluginListDocument(site, list);
321 if (canceled) return;
322 getProgressMonitor().worked(1);
323 if (canceled) return;
324 }
325 }
326 // remove old stuff or whole update process is broken
327 for (File file: siteCacheFiles) {
328 file.delete();
329 }
330 }
331
332 /**
333 * Replies true if the task was canceled
334 * @return <code>true</code> if the task was stopped by the user
335 */
336 public boolean isCanceled() {
337 return canceled;
338 }
339
340 /**
341 * Replies the list of plugins described in the downloaded plugin lists
342 *
343 * @return the list of plugins
344 * @since 5601
345 */
346 public List<PluginInformation> getAvailablePlugins() {
347 return availablePlugins;
348 }
349}
Note: See TracBrowser for help on using the repository browser.