01: /*
02: * jGnash, a personal finance application
03: * Copyright (C) 2001-2008 Craig Cavanaugh
04: *
05: * This program is free software: you can redistribute it and/or modify
06: * it under the terms of the GNU General Public License as published by
07: * the Free Software Foundation, either version 3 of the License, or
08: * (at your option) any later version.
09: *
10: * This program is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13: * GNU General Public License for more details.
14: *
15: * You should have received a copy of the GNU General Public License
16: * along with this program. If not, see <http://www.gnu.org/licenses/>.
17: */
18: package jgnash.net.currency;
19:
20: import java.math.BigDecimal;
21: import java.util.ArrayList;
22: import java.util.List;
23: import java.util.prefs.Preferences;
24:
25: import javax.swing.SwingWorker;
26:
27: import jgnash.engine.CurrencyNode;
28: import jgnash.engine.EngineFactory;
29:
30: /** Fetches latest exchange rates in the background
31: *
32: * @author Craig Cavanaugh
33: *
34: * $Id: CurrencyUpdateFactory.java 197 2008-01-01 08:13:35Z ccavanaugh $
35: */
36: public class CurrencyUpdateFactory {
37:
38: private static final String UPDATE_ON_STARTUP = "updateOnStartup";
39:
40: public static void setUpdateOnStartup(boolean update) {
41: Preferences pref = Preferences
42: .userNodeForPackage(CurrencyUpdateFactory.class);
43: pref.putBoolean(UPDATE_ON_STARTUP, update);
44: }
45:
46: public static boolean getUpdateOnStartup() {
47: Preferences pref = Preferences
48: .userNodeForPackage(CurrencyUpdateFactory.class);
49: return pref.getBoolean(UPDATE_ON_STARTUP, false);
50: }
51:
52: public static ExchangeRateUpdateWorker getUpdateWorker() {
53: return new ExchangeRateUpdateWorker();
54: }
55:
56: public static class ExchangeRateUpdateWorker extends
57: SwingWorker<Void, Void> {
58:
59: @Override
60: protected Void doInBackground() throws Exception {
61:
62: List<CurrencyNode> list = new ArrayList<CurrencyNode>(
63: EngineFactory.getEngine().getCurrencies());
64:
65: int lengthOfTask = (list.size() * list.size() - list.size()) / 2;
66:
67: int count = 0;
68:
69: for (CurrencyNode i : list) {
70: String source = i.getSymbol();
71: for (CurrencyNode j : list) {
72: String target = j.getSymbol();
73:
74: if (!source.equals(target)
75: && (source.compareToIgnoreCase(target) > 0)
76: && !isCancelled()) {
77: CurrencyParser parser = new YahooParser();
78:
79: if (parser.parse(source, target)) {
80: BigDecimal conv = parser.getConversion();
81:
82: if (conv != null
83: && conv.compareTo(BigDecimal.ZERO) != 0) {
84: EngineFactory.getEngine()
85: .setExchangeRate(source,
86: target, conv);
87: }
88: }
89:
90: count++;
91:
92: setProgress((int) (((float) count / (float) lengthOfTask) * 100f));
93: }
94: }
95: }
96: return null;
97: }
98: }
99: }
|