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

Last change on this file since 12346 was 12279, checked in by Don-vip, 7 years ago

sonar - squid:S3878 - Arrays should not be created for varargs parameters

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