]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/function/gpsies/GetGpsiesFunction.java
Version 9, February 2010
[GpsPrune.git] / tim / prune / function / gpsies / GetGpsiesFunction.java
1 package tim.prune.function.gpsies;
2
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.Dimension;
6 import java.awt.FlowLayout;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.awt.event.WindowAdapter;
10 import java.awt.event.WindowEvent;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.net.URL;
14 import java.util.ArrayList;
15
16 import javax.swing.BorderFactory;
17 import javax.swing.JButton;
18 import javax.swing.JDialog;
19 import javax.swing.JLabel;
20 import javax.swing.JPanel;
21 import javax.swing.JScrollPane;
22 import javax.swing.JSplitPane;
23 import javax.swing.JTable;
24 import javax.swing.JTextArea;
25 import javax.swing.event.ListSelectionEvent;
26 import javax.swing.event.ListSelectionListener;
27 import javax.xml.parsers.SAXParser;
28 import javax.xml.parsers.SAXParserFactory;
29
30 import tim.prune.App;
31 import tim.prune.GenericFunction;
32 import tim.prune.I18nManager;
33 import tim.prune.function.browser.BrowserLauncher;
34 import tim.prune.load.xml.XmlFileLoader;
35 import tim.prune.load.xml.ZipFileLoader;
36
37 /**
38  * Function to load track information from Gpsies.com
39  * according to the currently viewed area
40  */
41 public class GetGpsiesFunction extends GenericFunction implements Runnable
42 {
43         /** Dialog object */
44         private JDialog _dialog = null;
45         /** list model */
46         private TrackListModel _trackListModel = null;
47         /** track table */
48         private JTable _trackTable = null;
49         /** Cancelled flag */
50         private boolean _cancelled = false;
51         /** Status label */
52         private JLabel _statusLabel = null;
53         /** Description box */
54         private JTextArea _descriptionBox = null;
55         /** Load button */
56         private JButton _loadButton = null;
57         /** Show button */
58         private JButton _showButton = null;
59         /** Number of results per page */
60         private static final int RESULTS_PER_PAGE = 20;
61         /** Maximum number of results to get */
62         private static final int MAX_RESULTS = 60;
63
64
65         /**
66          * Constructor
67          * @param inApp App object
68          */
69         public GetGpsiesFunction(App inApp)
70         {
71                 super(inApp);
72         }
73
74         /**
75          * @return name key
76          */
77         public String getNameKey() {
78                 return "function.getgpsies";
79         }
80
81         /**
82          * Begin the function
83          */
84         public void begin()
85         {
86                 // Initialise dialog, show empty list
87                 if (_dialog == null)
88                 {
89                         _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), true);
90                         _dialog.setLocationRelativeTo(_parentFrame);
91                         _dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
92                         // add closing listener
93                         _dialog.addWindowListener(new WindowAdapter() {
94                                 public void windowClosing(WindowEvent e) {
95                                         _cancelled = true;
96                                 }
97                         });
98                         _dialog.getContentPane().add(makeDialogComponents());
99                         _dialog.pack();
100                 }
101                 // Clear list
102                 _trackListModel.clear();
103                 _loadButton.setEnabled(false);
104                 _showButton.setEnabled(false);
105                 _cancelled = false;
106                 _descriptionBox.setText("");
107                 // Start new thread to load list asynchronously
108                 new Thread(this).start();
109
110                 // Show dialog
111                 _dialog.setVisible(true);
112         }
113
114
115         /**
116          * Create dialog components
117          * @return Panel containing all gui elements in dialog
118          */
119         private Component makeDialogComponents()
120         {
121                 JPanel dialogPanel = new JPanel();
122                 dialogPanel.setLayout(new BorderLayout());
123
124                 // Status label
125                 _statusLabel = new JLabel(I18nManager.getText("confirm.running"));
126                 dialogPanel.add(_statusLabel, BorderLayout.NORTH);
127                 // Main panel with track list
128                 _trackListModel = new TrackListModel();
129                 _trackTable = new JTable(_trackListModel);
130                 _trackTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
131                         public void valueChanged(ListSelectionEvent e) {
132                                 if (!e.getValueIsAdjusting())
133                                 {
134                                         if (_trackTable.getSelectedRow() >= 0
135                                          && _trackTable.getSelectedRow() < _trackListModel.getRowCount())
136                                         {
137                                                 _loadButton.setEnabled(true);
138                                                 _showButton.setEnabled(true);
139                                                 setDescription(_trackListModel.getTrack(_trackTable.getSelectedRow()).getDescription());
140                                                 _descriptionBox.setCaretPosition(0);
141                                         }
142                                         else {
143                                                 _descriptionBox.setText("");
144                                         }
145                                 }
146                         }
147                 });
148                 _trackTable.getColumnModel().getColumn(0).setPreferredWidth(300);
149                 _trackTable.getColumnModel().getColumn(1).setPreferredWidth(70);
150                 JScrollPane tablePane = new JScrollPane(_trackTable);
151                 tablePane.setPreferredSize(new Dimension(450, 200));
152                 // Panel to hold description label and box
153                 JPanel descPanel = new JPanel();
154                 descPanel.setLayout(new BorderLayout());
155                 JLabel descLabel = new JLabel(I18nManager.getText("dialog.gpsies.description") + " :");
156                 descPanel.add(descLabel, BorderLayout.NORTH);
157                 _descriptionBox = new JTextArea(5, 20);
158                 _descriptionBox.setEditable(false);
159                 _descriptionBox.setLineWrap(true);
160                 _descriptionBox.setWrapStyleWord(true);
161                 JScrollPane descPane = new JScrollPane(_descriptionBox);
162                 descPane.setPreferredSize(new Dimension(400, 80));
163                 descPanel.add(descPane, BorderLayout.CENTER);
164                 // Use split pane to split table from description
165                 JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tablePane, descPanel);
166                 splitPane.setResizeWeight(1.0);
167                 dialogPanel.add(splitPane, BorderLayout.CENTER);
168
169                 // button panel at bottom
170                 JPanel buttonPanel = new JPanel();
171                 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
172                 _loadButton = new JButton(I18nManager.getText("button.load"));
173                 _loadButton.setEnabled(false);
174                 _loadButton.addActionListener(new ActionListener() {
175                         public void actionPerformed(ActionEvent e)
176                         {
177                                 loadSelectedTrack();
178                         }
179                 });
180                 buttonPanel.add(_loadButton);
181                 _showButton = new JButton(I18nManager.getText("button.showwebpage"));
182                 _showButton.setEnabled(false);
183                 _showButton.addActionListener(new ActionListener() {
184                         public void actionPerformed(ActionEvent e)
185                         {
186                                 showSelectedTrack();
187                         }
188                 });
189                 buttonPanel.add(_showButton);
190                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
191                 cancelButton.addActionListener(new ActionListener() {
192                         public void actionPerformed(ActionEvent e)
193                         {
194                                 _cancelled = true;
195                                 _dialog.dispose();
196                         }
197                 });
198                 buttonPanel.add(cancelButton);
199                 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
200                 dialogPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 15));
201                 return dialogPanel;
202         }
203
204         /**
205          * Set the description in the box
206          * @param inDesc description to set, or null for no description
207          */
208         private void setDescription(String inDesc)
209         {
210                 String text = inDesc;
211                 if (inDesc == null || inDesc.length() < 2) {
212                         text = I18nManager.getText("dialog.gpsies.nodescription");
213                 }
214                 _descriptionBox.setText(text);
215         }
216
217         /**
218          * Run method to call gpsies.com in separate thread
219          */
220         public void run()
221         {
222                 _statusLabel.setText(I18nManager.getText("confirm.running"));
223                 // Act on callback to update list and send another request if necessary
224                 double[] coords = _app.getViewport().getBounds();
225                 // Example http://www.gpsies.com/api.do?BBOX=10,51,12,53&limit=20&trackTypes=jogging&filetype=kml&device=Run.GPS
226                 int currPage = 1;
227
228                 ArrayList<GpsiesTrack> trackList = null;
229                 URL url = null;
230                 String descMessage = "";
231                 InputStream inStream = null;
232                 // Loop for each page of the results
233                 do
234                 {
235                         String urlString = "http://www.gpsies.com/api.do?BBOX=" +
236                                 coords[1] + "," + coords[0] + "," + coords[3] + "," + coords[2] +
237                                 "&limit=" + RESULTS_PER_PAGE + "&resultPage=" + currPage;
238                         // System.out.println(urlString);
239                         // Parse the returned XML with a special handler
240                         GpsiesXmlHandler xmlHandler = new GpsiesXmlHandler();
241                         try
242                         {
243                                 url = new URL(urlString);
244                                 SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
245                                 inStream = url.openStream();
246                                 saxParser.parse(inStream, xmlHandler);
247                         }
248                         catch (Exception e) {
249                                 descMessage = e.getClass().getName() + " - " + e.getMessage();
250                         }
251                         // Close stream and ignore errors
252                         try {
253                                 inStream.close();
254                         } catch (Exception e) {}
255                         // Add track list to model
256                         trackList = xmlHandler.getTrackList();
257                         _trackListModel.addTracks(trackList);
258
259                         // Compare number of results with results per page and call again if necessary
260                         currPage++;
261                 }
262                 while (trackList != null && trackList.size() == RESULTS_PER_PAGE
263                  && _trackListModel.getRowCount() < MAX_RESULTS && !_cancelled);
264                 // Set status label according to error or "none found", leave blank if ok
265                 if (descMessage.equals("") && (trackList == null || trackList.size() == 0)) {
266                         descMessage = I18nManager.getText("dialog.gpsies.nonefound");
267                 }
268                 _statusLabel.setText(descMessage);
269         }
270
271
272         /**
273          * Load the selected track
274          */
275         private void loadSelectedTrack()
276         {
277                 // Find the row selected in the table and get the corresponding track
278                 int rowNum = _trackTable.getSelectedRow();
279                 if (rowNum >= 0 && rowNum < _trackListModel.getRowCount())
280                 {
281                         String url = _trackListModel.getTrack(rowNum).getDownloadLink();
282                         XmlFileLoader xmlLoader = new XmlFileLoader(_app);
283                         ZipFileLoader loader = new ZipFileLoader(_app, xmlLoader);
284                         try
285                         {
286                                 loader.openStream(new URL(url).openStream());
287                         }
288                         catch (IOException ioe) {
289                                 System.err.println("IO Exception : " + ioe.getMessage());
290                         }
291                 }
292                 // Close the dialog
293                 _cancelled = true;
294                 _dialog.dispose();
295         }
296
297
298         /**
299          * Show the webpage for the selected track
300          */
301         private void showSelectedTrack()
302         {
303                 // Find the row selected in the table and show the corresponding url
304                 int rowNum = _trackTable.getSelectedRow();
305                 if (rowNum >= 0 && rowNum < _trackListModel.getRowCount())
306                 {
307                         String id = _trackListModel.getTrack(rowNum).getFileId();
308                         BrowserLauncher.launchBrowser("http://gpsies.com/map.do?fileId=" + id);
309                 }
310                 // Close the dialog
311                 _cancelled = true;
312                 _dialog.dispose();
313         }
314 }