File: GetWeatherForecastFunction.java

package info (click to toggle)
gpsprune 17-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,984 kB
  • ctags: 5,218
  • sloc: java: 39,403; sh: 25; makefile: 17; python: 15
file content (484 lines) | stat: -rw-r--r-- 17,076 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package tim.prune.function.weather;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import tim.prune.App;
import tim.prune.GenericFunction;
import tim.prune.GpsPrune;
import tim.prune.I18nManager;
import tim.prune.data.DataPoint;
import tim.prune.data.NumberUtils;
import tim.prune.data.Track;
import tim.prune.function.browser.BrowserLauncher;

/**
 * Function to display a weather forecast for the current location
 * using the services of openweathermap.org
 */
public class GetWeatherForecastFunction extends GenericFunction implements Runnable
{
	/** Dialog object */
	private JDialog _dialog = null;
	/** Label for location */
	private JLabel _locationLabel = null;
	/** Label for the forecast update time */
	private JLabel _updateTimeLabel = null;
	/** Label for the sunrise and sunset times */
	private JLabel _sunriseLabel = null;
	/** Radio button for selecting current weather */
	private JRadioButton _currentForecastRadio = null;
	/** Radio button for selecting daily forecasts */
	private JRadioButton _dailyForecastRadio = null;
	/** Dropdown for selecting celsius / fahrenheit */
	private JComboBox<String> _tempUnitsDropdown = null;
	/** Table to hold the forecasts */
	private JTable _forecastsTable = null;
	/** Table model */
	private WeatherTableModel _tableModel = new WeatherTableModel();
	/** Set of previously obtained results, to avoid repeating calls */
	private ResultSet _resultSet = new ResultSet();
	/** Location id obtained from current forecast */
	private String _locationId = null;
	/** Flag to show that forecast is currently running, don't start another */
	private boolean _isRunning = false;

	/** True to just simulate the calls and read files instead, false to call real API */
	private static final boolean SIMULATE_WITH_FILES = false;
	/** Unique API key for GpsPrune */
	private static final String OPENWEATHERMAP_API_KEY = "d1c5d792362f5a5c2eacf70a3b72ecd6";


	/**
	 * Inner class to pass results asynchronously to the table model
	 */
	private class ResultUpdater implements Runnable
	{
		private WeatherResults _results;
		public ResultUpdater(WeatherResults inResults) {
			_results = inResults;
		}
		public void run() {
			_tableModel.setResults(_results);
			adjustTable();
		}
	}


	/** Constructor */
	public GetWeatherForecastFunction(App inApp)
	{
		super(inApp);
	}

	/** @return name key */
	public String getNameKey() {
		return "function.getweatherforecast";
	}

	/**
	 * Begin the function
	 */
	public void begin()
	{
		// Initialise dialog, show empty list
		if (_dialog == null)
		{
			_dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), true);
			_dialog.setLocationRelativeTo(_parentFrame);
			_dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			_dialog.getContentPane().add(makeDialogComponents());
			_dialog.pack();
		}
		// Clear results
		_locationId = null;
		_tableModel.clear();
		_locationLabel.setText(I18nManager.getText("confirm.running"));
		_updateTimeLabel.setText("");
		_sunriseLabel.setText("");
		_currentForecastRadio.setSelected(true);

		// Start new thread to load list asynchronously
		new Thread(this).start();

		_dialog.setVisible(true);
	}

	/**
	 * Create dialog components
	 * @return Panel containing all gui elements in dialog
	 */
	private Component makeDialogComponents()
	{
		JPanel dialogPanel = new JPanel();
		dialogPanel.setLayout(new BorderLayout(0, 4));

		JPanel topPanel = new JPanel();
		topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
		_locationLabel = new JLabel(I18nManager.getText("confirm.running"));
		_locationLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
		topPanel.add(_locationLabel);
		_updateTimeLabel = new JLabel(" ");
		_updateTimeLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
		topPanel.add(_updateTimeLabel);
		_sunriseLabel = new JLabel(" ");
		_sunriseLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
		topPanel.add(_sunriseLabel);
		JPanel radioPanel = new JPanel();
		radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.X_AXIS));
		radioPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
		ButtonGroup forecastTypeGroup = new ButtonGroup();
		_currentForecastRadio = new JRadioButton(I18nManager.getText("dialog.weather.currentforecast"));
		_dailyForecastRadio = new JRadioButton(I18nManager.getText("dialog.weather.dailyforecast"));
		JRadioButton threeHourlyRadio = new JRadioButton(I18nManager.getText("dialog.weather.3hourlyforecast"));
		forecastTypeGroup.add(_currentForecastRadio);
		forecastTypeGroup.add(_dailyForecastRadio);
		forecastTypeGroup.add(threeHourlyRadio);
		radioPanel.add(_currentForecastRadio);
		radioPanel.add(_dailyForecastRadio);
		radioPanel.add(threeHourlyRadio);
		_currentForecastRadio.setSelected(true);
		ActionListener radioListener = new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!_isRunning) new Thread(GetWeatherForecastFunction.this).start();
			}
		};
		_currentForecastRadio.addActionListener(radioListener);
		_dailyForecastRadio.addActionListener(radioListener);
		threeHourlyRadio.addActionListener(radioListener);
		radioPanel.add(Box.createHorizontalGlue());
		radioPanel.add(Box.createHorizontalStrut(40));

		// Dropdown for temperature units
		radioPanel.add(new JLabel(I18nManager.getText("dialog.weather.temperatureunits") + ": "));
		_tempUnitsDropdown = new JComboBox<String>(new String[] {
			I18nManager.getText("units.degreescelsius"), I18nManager.getText("units.degreesfahrenheit")
		});
		_tempUnitsDropdown.setMaximumSize(_tempUnitsDropdown.getPreferredSize());
		_tempUnitsDropdown.addActionListener(radioListener);
		radioPanel.add(_tempUnitsDropdown);
		radioPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
		topPanel.add(radioPanel);
		dialogPanel.add(topPanel, BorderLayout.NORTH);

		final IconRenderer iconRenderer = new IconRenderer();
		_forecastsTable = new JTable(_tableModel)
		{
			public TableCellRenderer getCellRenderer(int row, int column) {
				if ((row == WeatherTableModel.ROW_ICON)) {
					return iconRenderer;
				}
				return super.getCellRenderer(row, column);
			}
		};
		_forecastsTable.setRowSelectionAllowed(false);
		_forecastsTable.setRowHeight(2, 55); // make just that row high enough to see icons
		_forecastsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		_forecastsTable.getTableHeader().setReorderingAllowed(false);
		_forecastsTable.setShowHorizontalLines(false);

		JScrollPane scroller = new JScrollPane(_forecastsTable);
		scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
		scroller.setPreferredSize(new Dimension(500, 210));
		scroller.getViewport().setBackground(Color.white);

		dialogPanel.add(scroller, BorderLayout.CENTER);

		// button panel at bottom
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		JButton launchButton = new JButton(I18nManager.getText("button.showwebpage"));
		launchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				BrowserLauncher.launchBrowser("http://openweathermap.org/city/" + (_locationId == null ? "" : _locationId));
			}
		});
		buttonPanel.add(launchButton);
		// close
		JButton closeButton = new JButton(I18nManager.getText("button.close"));
		closeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				_dialog.dispose();
			}
		});
		buttonPanel.add(closeButton);
		// Add a holder panel with a static label to credit openweathermap
		JPanel southPanel = new JPanel();
		southPanel.setLayout(new BoxLayout(southPanel, BoxLayout.Y_AXIS));
		southPanel.add(new JLabel(I18nManager.getText("dialog.weather.creditnotice")));
		southPanel.add(buttonPanel);
		dialogPanel.add(southPanel, BorderLayout.SOUTH);
		dialogPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 15));
		return dialogPanel;
	}

	/**
	 * Get the weather forecast in a separate thread
	 */
	public void run()
	{
		if (_isRunning) {return;} // don't run twice
		_isRunning = true;

		// Are we getting the current details, or getting a forecast?
		final boolean isCurrent = _locationId == null || _currentForecastRadio.isSelected();
		final boolean isDailyForecast = _dailyForecastRadio.isSelected() && !isCurrent;
		final boolean isHourlyForecast = !isCurrent && !isDailyForecast;
		final boolean isUsingCelsius  = _tempUnitsDropdown.getSelectedIndex() == 0;

		// Have we got these results already?  Look in store
		WeatherResults results = _resultSet.getWeather(_locationId, isCurrent, isDailyForecast, isHourlyForecast, isUsingCelsius);
		if (results == null)
		{
			if (isCurrent)
			{
				// Get the current details using either lat/long or locationId
				results = getCurrentWeather(isUsingCelsius);
				// If the current radio isn't selected, select it
				if (!_currentForecastRadio.isSelected()) {
					_currentForecastRadio.setSelected(true);
				}
			}
			else
			{
				// Get the specified forecast using the retrieved locationId
				results = getWeatherForecast(isDailyForecast, isUsingCelsius);
			}
			// If it's a valid answer, store it for later
			if (results != null)
			{
				_resultSet.setWeather(results, _locationId, isCurrent, isDailyForecast, isHourlyForecast, isUsingCelsius);
			}
		}

		// update table contents and labels
		if (results != null)
		{
			SwingUtilities.invokeLater(new ResultUpdater(results));
			_locationLabel.setText(I18nManager.getText("dialog.weather.location") + ": " + results.getLocationName());
			final String ut = results.getUpdateTime();
			_updateTimeLabel.setText(I18nManager.getText("dialog.weather.update") + ": " + (ut == null ? "" : ut));
			if (results.getSunriseTime() != null && results.getSunsetTime() != null)
			{
				_sunriseLabel.setText(I18nManager.getText("dialog.weather.sunrise") + ": " + results.getSunriseTime()
					+ ", " + I18nManager.getText("dialog.weather.sunset") + ": " + results.getSunsetTime());
			}
			else {
				_sunriseLabel.setText("");
			}
		}

		// finished running
		_isRunning = false;
	}


	/**
	 * Adjust the column widths and row heights to fit the displayed data
	 */
	private void adjustTable()
	{
		if (!_tableModel.isEmpty())
		{
			// adjust column widths for all columns
			for (int i=0; i<_forecastsTable.getColumnCount(); i++)
			{
				double maxWidth = 0.0;
				for (int j=0; j<_forecastsTable.getRowCount(); j++)
				{
					final String value = _tableModel.getValueAt(j, i).toString();
					maxWidth = Math.max(maxWidth, _forecastsTable.getCellRenderer(0, 0).getTableCellRendererComponent(
						_forecastsTable, value, false, false, 0, 0).getPreferredSize().getWidth());
				}
				_forecastsTable.getColumnModel().getColumn(i).setMinWidth((int) maxWidth + 2);
			}
			// Set minimum row heights
			final int labelHeight = (int) (_forecastsTable.getCellRenderer(0, 0).getTableCellRendererComponent(
				_forecastsTable, "M", false, false, 0, 0).getMinimumSize().getHeight() * 1.2f + 4);
			for (int i=0; i<_forecastsTable.getRowCount(); i++)
			{
				if (i == WeatherTableModel.ROW_ICON) {
					_forecastsTable.setRowHeight(i, 55);
				}
				else {
					_forecastsTable.setRowHeight(i, labelHeight);
				}
			}
		}
	}

	/**
	 * Get the current weather using the lat/long and populate _results
	 * @param inUseCelsius true for celsius, false for fahrenheit
	 * @return weather results
	 */
	private WeatherResults getCurrentWeather(boolean inUseCelsius)
	{
		final Track track = _app.getTrackInfo().getTrack();
		if (track.getNumPoints() < 1) {return null;}
		// Get coordinates to lookup
		double lat = 0.0, lon = 0.0;
		// See if a point is selected, if so use that
		DataPoint currPoint = _app.getTrackInfo().getCurrentPoint();
		if (currPoint != null)
		{
			// Use selected point
			lat = currPoint.getLatitude().getDouble();
			lon = currPoint.getLongitude().getDouble();
		}
		else
		{
			lat = track.getLatRange().getMidValue();
			lon = track.getLonRange().getMidValue();
		}

		InputStream inStream = null;
		// Build url either with coordinates or with location id if available
		final String urlString = "http://api.openweathermap.org/data/2.5/weather?"
			+ (_locationId == null ? ("lat=" + NumberUtils.formatNumberUk(lat, 5) + "&lon=" + NumberUtils.formatNumberUk(lon, 5))
				: ("id=" + _locationId))
			+ "&lang=" + I18nManager.getText("openweathermap.lang")
			+ "&mode=xml&units=" + (inUseCelsius ? "metric" : "imperial")
			+ "&APPID=" + OPENWEATHERMAP_API_KEY;
		// System.out.println(urlString);

		// Parse the returned XML with a special handler
		OWMCurrentHandler xmlHandler = new OWMCurrentHandler();
		try
		{
			URL url = new URL(urlString);
			SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
			// DEBUG: Simulate the call in case of no network connection
			if (SIMULATE_WITH_FILES)
			{
				inStream = new FileInputStream(new File("tim/prune/test/examplecurrentweather.xml"));
				try {
					Thread.sleep(2000);
				} catch (InterruptedException tie) {}
			}
			else
			{
				URLConnection conn = url.openConnection();
				conn.setRequestProperty("User-Agent", "GpsPrune v" + GpsPrune.VERSION_NUMBER);
				inStream = conn.getInputStream();
			}

			saxParser.parse(inStream, xmlHandler);
		}
		catch (Exception e)
		{
			// Show error message but don't close dialog
			_app.showErrorMessageNoLookup(getNameKey(), e.getClass().getName() + " - " + e.getMessage());
			_isRunning = false;
			return null;
		}
		// Close stream and ignore errors
		try {
			inStream.close();
		} catch (Exception e) {}

		// Save the location id
		if (xmlHandler.getLocationId() != null) {
			_locationId = xmlHandler.getLocationId();
		}
		// Get the results from the handler and return
		WeatherResults results = new WeatherResults();
		results.setForecast(xmlHandler.getCurrentWeather());
		results.setLocationName(xmlHandler.getLocationName());
		results.setUpdateTime(xmlHandler.getUpdateTime());
		results.setSunriseSunsetTimes(xmlHandler.getSunriseTime(), xmlHandler.getSunsetTime());
		results.setTempsCelsius(inUseCelsius);
		return results;
	}


	/**
	 * Get the weather forecast for the current location id and populate in _results
	 * @param inDaily true for daily, false for 3-hourly
	 * @param inCelsius true for celsius, false for fahrenheit
	 * @return weather results
	 */
	private WeatherResults getWeatherForecast(boolean inDaily, boolean inCelsius)
	{
		InputStream inStream = null;
		// Build URL
		final String forecastCount = inDaily ? "8" : "3";
		final String urlString = "http://api.openweathermap.org/data/2.5/forecast"
			+ (inDaily ? "/daily" : "") + "?id=" + _locationId + "&lang=" + I18nManager.getText("openweathermap.lang")
			+ "&mode=xml&units=" + (inCelsius ? "metric" : "imperial") + "&cnt=" + forecastCount
			+ "&APPID=" + OPENWEATHERMAP_API_KEY;
		// System.out.println(urlString);

		// Parse the returned XML with a special handler
		OWMForecastHandler xmlHandler = new OWMForecastHandler();
		try
		{
			URL url = new URL(urlString);
			SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
			// DEBUG: Simulate the call in case of no network connection
			if (SIMULATE_WITH_FILES)
			{
				inStream = new FileInputStream(new File("tim/prune/test/exampleweatherforecast.xml"));
				try {
					Thread.sleep(2000);
				} catch (InterruptedException tie) {}
			}
			else
			{
				URLConnection conn = url.openConnection();
				conn.setRequestProperty("User-Agent", "GpsPrune v" + GpsPrune.VERSION_NUMBER);
				inStream = conn.getInputStream();
			}

			saxParser.parse(inStream, xmlHandler);
		}
		catch (Exception e)
		{
			// Show error message but don't close dialog
			_app.showErrorMessageNoLookup(getNameKey(), e.getClass().getName() + " - " + e.getMessage());
			_isRunning = false;
			return null;
		}
		// Close stream and ignore errors
		try {
			inStream.close();
		} catch (Exception e) {}

		// Get results from handler, put in model
		WeatherResults results = new WeatherResults();
		results.setForecasts(xmlHandler.getForecasts());
		results.setLocationName(xmlHandler.getLocationName());
		results.setUpdateTime(xmlHandler.getUpdateTime());
		results.setTempsCelsius(inCelsius);
		return results;
	}
}