source: josm/trunk/src/org/openstreetmap/josm/actions/OpenLocationAction.java@ 10292

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

sonar - squid:S2221 - "Exception" should not be caught when not required by called methods

  • Property svn:eol-style set to native
File size: 10.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.GridBagConstraints;
8import java.awt.GridBagLayout;
9import java.awt.GridLayout;
10import java.awt.event.ActionEvent;
11import java.awt.event.KeyEvent;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.concurrent.Future;
18
19import javax.swing.JCheckBox;
20import javax.swing.JLabel;
21import javax.swing.JList;
22import javax.swing.JOptionPane;
23import javax.swing.JPanel;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
27import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesTask;
28import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlBoundsTask;
29import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlIdTask;
30import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeCompressedTask;
31import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeTask;
32import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmCompressedTask;
33import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmIdTask;
34import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
35import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmUrlTask;
36import org.openstreetmap.josm.actions.downloadtasks.DownloadSessionTask;
37import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
38import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
39import org.openstreetmap.josm.gui.ExtendedDialog;
40import org.openstreetmap.josm.gui.HelpAwareOptionPane;
41import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
42import org.openstreetmap.josm.gui.widgets.HistoryComboBox;
43import org.openstreetmap.josm.tools.Shortcut;
44import org.openstreetmap.josm.tools.Utils;
45
46/**
47 * Open an URL input dialog and load data from the given URL.
48 *
49 * @author imi
50 */
51public class OpenLocationAction extends JosmAction {
52
53 protected final transient List<Class<? extends DownloadTask>> downloadTasks;
54
55 /**
56 * Create an open action. The name is "Open a file".
57 */
58 public OpenLocationAction() {
59 /* I18N: Command to download a specific location/URL */
60 super(tr("Open Location..."), "openlocation", tr("Open an URL."),
61 Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")),
62 KeyEvent.VK_L, Shortcut.CTRL), true);
63 putValue("help", ht("/Action/OpenLocation"));
64 this.downloadTasks = new ArrayList<>();
65 addDownloadTaskClass(DownloadOsmTask.class);
66 addDownloadTaskClass(DownloadGpsTask.class);
67 addDownloadTaskClass(DownloadNotesTask.class);
68 addDownloadTaskClass(DownloadOsmChangeTask.class);
69 addDownloadTaskClass(DownloadOsmUrlTask.class);
70 addDownloadTaskClass(DownloadOsmIdTask.class);
71 addDownloadTaskClass(DownloadOsmCompressedTask.class);
72 addDownloadTaskClass(DownloadOsmChangeCompressedTask.class);
73 addDownloadTaskClass(DownloadSessionTask.class);
74 addDownloadTaskClass(DownloadNotesUrlBoundsTask.class);
75 addDownloadTaskClass(DownloadNotesUrlIdTask.class);
76 }
77
78 /**
79 * Restore the current history from the preferences
80 *
81 * @param cbHistory the history combo box
82 */
83 protected void restoreUploadAddressHistory(HistoryComboBox cbHistory) {
84 List<String> cmtHistory = new LinkedList<>(Main.pref.getCollection(getClass().getName() + ".uploadAddressHistory",
85 new LinkedList<String>()));
86 // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement()
87 //
88 Collections.reverse(cmtHistory);
89 cbHistory.setPossibleItems(cmtHistory);
90 }
91
92 /**
93 * Remind the current history in the preferences
94 * @param cbHistory the history combo box
95 */
96 protected void remindUploadAddressHistory(HistoryComboBox cbHistory) {
97 cbHistory.addCurrentItemToHistory();
98 Main.pref.putCollection(getClass().getName() + ".uploadAddressHistory", cbHistory.getHistory());
99 }
100
101 @Override
102 public void actionPerformed(ActionEvent e) {
103
104 JCheckBox layer = new JCheckBox(tr("Separate Layer"));
105 layer.setToolTipText(tr("Select if the data should be downloaded into a new layer"));
106 layer.setSelected(Main.pref.getBoolean("download.newlayer"));
107 JPanel all = new JPanel(new GridBagLayout());
108 GridBagConstraints gc = new GridBagConstraints();
109 gc.fill = GridBagConstraints.HORIZONTAL;
110 gc.weightx = 1.0;
111 gc.anchor = GridBagConstraints.FIRST_LINE_START;
112 all.add(new JLabel(tr("Enter URL to download:")), gc);
113 HistoryComboBox uploadAddresses = new HistoryComboBox();
114 uploadAddresses.setToolTipText(tr("Enter an URL from where data should be downloaded"));
115 restoreUploadAddressHistory(uploadAddresses);
116 gc.gridy = 1;
117 all.add(uploadAddresses, gc);
118 gc.gridy = 2;
119 gc.fill = GridBagConstraints.BOTH;
120 gc.weighty = 1.0;
121 all.add(layer, gc);
122 ExtendedDialog dialog = new ExtendedDialog(Main.parent,
123 tr("Download Location"),
124 new String[] {tr("Download URL"), tr("Cancel")}
125 );
126 dialog.setContent(all, false /* don't embedded content in JScrollpane */);
127 dialog.setButtonIcons(new String[] {"download", "cancel"});
128 dialog.setToolTipTexts(new String[] {
129 tr("Start downloading data"),
130 tr("Close dialog and cancel downloading")
131 });
132 dialog.configureContextsensitiveHelp("/Action/OpenLocation", true /* show help button */);
133 dialog.showDialog();
134 if (dialog.getValue() != 1) return;
135 remindUploadAddressHistory(uploadAddresses);
136 openUrl(layer.isSelected(), Utils.strip(uploadAddresses.getText()));
137 }
138
139 /**
140 * Replies the list of download tasks accepting the given url.
141 * @param url The URL to open
142 * @param isRemotecontrol True if download request comes from remotecontrol.
143 * @return The list of download tasks accepting the given url.
144 * @since 5691
145 */
146 public Collection<DownloadTask> findDownloadTasks(final String url, boolean isRemotecontrol) {
147 List<DownloadTask> result = new ArrayList<>();
148 for (Class<? extends DownloadTask> taskClass : downloadTasks) {
149 if (taskClass != null) {
150 try {
151 DownloadTask task = taskClass.getConstructor().newInstance();
152 if (task.acceptsUrl(url, isRemotecontrol)) {
153 result.add(task);
154 }
155 } catch (ReflectiveOperationException e) {
156 Main.error(e);
157 }
158 }
159 }
160 return result;
161 }
162
163 /**
164 * Summarizes acceptable urls for error message purposes.
165 * @return The HTML message to be displayed
166 * @since 6031
167 */
168 public String findSummaryDocumentation() {
169 StringBuilder result = new StringBuilder("<table>");
170 for (Class<? extends DownloadTask> taskClass : downloadTasks) {
171 if (taskClass != null) {
172 try {
173 DownloadTask task = taskClass.getConstructor().newInstance();
174 result.append(task.acceptsDocumentationSummary());
175 } catch (ReflectiveOperationException e) {
176 Main.error(e);
177 }
178 }
179 }
180 result.append("</table>");
181 return result.toString();
182 }
183
184 /**
185 * Open the given URL.
186 * @param newLayer true if the URL needs to be opened in a new layer, false otherwise
187 * @param url The URL to open
188 */
189 public void openUrl(boolean newLayer, final String url) {
190 Collection<DownloadTask> tasks = findDownloadTasks(url, false);
191
192 if (tasks.size() > 1) {
193 tasks = askWhichTasksToLoad(tasks);
194 } else if (tasks.isEmpty()) {
195 warnNoSuitableTasks(url);
196 return;
197 }
198
199 PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Download Data"));
200
201 for (final DownloadTask task : tasks) {
202 try {
203 Future<?> future = task.loadUrl(newLayer, url, monitor);
204 Main.worker.submit(new PostDownloadHandler(task, future));
205 } catch (IllegalArgumentException e) {
206 Main.error(e);
207 }
208 }
209 }
210
211 /**
212 * Asks the user which of the possible tasks to perform.
213 * @param tasks a list of possible tasks
214 * @return the selected tasks from the user or an empty list if the dialog has been canceled
215 */
216 Collection<DownloadTask> askWhichTasksToLoad(final Collection<DownloadTask> tasks) {
217 final JList<DownloadTask> list = new JList<>(tasks.toArray(new DownloadTask[tasks.size()]));
218 list.addSelectionInterval(0, tasks.size() - 1);
219 final ExtendedDialog dialog = new ExtendedDialog(Main.parent,
220 tr("Which tasks to perform?"), new String[]{tr("Ok"), tr("Cancel")}, true) { {
221 setButtonIcons(new String[]{"ok", "cancel"});
222 final JPanel pane = new JPanel(new GridLayout(2, 1));
223 pane.add(new JLabel(tr("Which tasks to perform?")));
224 pane.add(list);
225 setContent(pane);
226 } };
227 dialog.showDialog();
228 return dialog.getValue() == 1 ? list.getSelectedValuesList() : Collections.<DownloadTask>emptyList();
229 }
230
231 /**
232 * Displays an error message dialog that no suitable tasks have been found for the given url.
233 * @param url the given url
234 */
235 void warnNoSuitableTasks(final String url) {
236 final String details = findSummaryDocumentation(); // Explain what patterns are supported
237 HelpAwareOptionPane.showMessageDialogInEDT(Main.parent, "<html><p>" + tr(
238 "Cannot open URL ''{0}''<br>The following download tasks accept the URL patterns shown:<br>{1}",
239 url, details) + "</p></html>", tr("Download Location"), JOptionPane.ERROR_MESSAGE, ht("/Action/OpenLocation"));
240 }
241
242 /**
243 * Adds a new download task to the supported ones.
244 * @param taskClass The new download task to add
245 * @return <tt>true</tt> (as specified by {@link Collection#add})
246 */
247 public final boolean addDownloadTaskClass(Class<? extends DownloadTask> taskClass) {
248 return this.downloadTasks.add(taskClass);
249 }
250}
Note: See TracBrowser for help on using the repository browser.