-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExchangeRates.java
110 lines (91 loc) · 2.89 KB
/
ExchangeRates.java
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
package com.salimov.yurii.lesson07.task02;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.List;
public final class ExchangeRates extends Thread {
private static String link = "http://query.yahooapis.com/v1/public/yql?" +
"format=xml&q=select*%20from%20yahoo.finance.xchange%20where%20pair%20in%20" +
"(\"USDEUR\",\"USDUAH\",\"EURUAH\")&env=store://datatables.org/alltableswithkeys";
private static ExchangeRates exchangeRates;
private static RateDB rateDB;
private static QueryRate query;
private static boolean started;
private static int timeout = 300000;
private ExchangeRates() {
}
public static ExchangeRates getInstance() {
if (exchangeRates == null) {
exchangeRates = new ExchangeRates();
rateDB = RateDB.getInstance();
rateDB.connect();
}
return exchangeRates;
}
@Override
public void start() {
if (!started) {
started = true;
super.setDaemon(true);
super.start();
}
}
@Override
public void run() {
try {
downloadRates();
} catch (MalformedURLException | JAXBException ex) {
ex.printStackTrace();
}
}
private void downloadRates() throws MalformedURLException, JAXBException {
final URL url = new URL(link);
final JAXBContext jaxbContext = JAXBContext.newInstance(QueryRate.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
while (!isInterrupted()) {
try {
query = (QueryRate) unmarshaller.unmarshal(url);
dataBaseUpdate();
Thread.sleep(timeout);
} catch (InterruptedException ex) {
ex.printStackTrace();
break;
} catch (Exception ex) {
ex.printStackTrace();
}
}
rateDB.disconnect();
}
private static void dataBaseUpdate() {
final Collection<Rate> list = query.getRateList();
for (Rate rate : list) {
rateDB.add(rate);
}
}
public static Rate getRate(final String id) {
return query.getRate(id);
}
public Collection<Rate> getRateList() {
return query.getRateList();
}
public static void setLink(final String link) {
ExchangeRates.link = link;
}
public static String getLink() {
return link;
}
public static void setTimeout(final int millisecond) {
if (millisecond > 0) {
ExchangeRates.timeout = millisecond;
}
}
public static int getTimeout() {
return timeout;
}
public static boolean isStarted() {
return started;
}
}