-
Notifications
You must be signed in to change notification settings - Fork 3
/
CurrencyServiceBean.java
70 lines (56 loc) · 2.1 KB
/
CurrencyServiceBean.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
package com.company.customdatasource.service;
import com.company.customdatasource.entity.CurrencyEnum;
import com.company.customdatasource.entity.CurrencyRate;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;
@Service(CurrencyService.NAME)
public class CurrencyServiceBean implements CurrencyService {
@Override
public Set<CurrencyRate> getRates(CurrencyEnum baseCurrency){
Set<CurrencyRate> result = new HashSet<>();
String req = "http://api.fixer.io/latest?base=" + baseCurrency.getId();
StringBuilder json = new StringBuilder();
try {
URL url = new URL(req);
URLConnection connection = url.openConnection();
try (InputStream in = connection.getInputStream()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
json.append(line).append("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
return result;
}
JSONObject response = new JSONObject(json.toString());
JSONObject rates = response.getJSONObject("rates");
for (CurrencyEnum cur : CurrencyEnum.values()) {
Object rate;
try {
rate = rates.get(cur.getId());
} catch (JSONException e) {
rate = null;
}
if (rate != null) {
CurrencyRate cr = new CurrencyRate();
cr.setCurrencyFrom(CurrencyEnum.fromId(response.get("base").toString()));
cr.setCurrencyTo(cur);
cr.setConversionRate(new BigDecimal(rate.toString()));
result.add(cr);
}
}
return result;
}
}