-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenExchangeApiClient.java
More file actions
272 lines (265 loc) · 11.4 KB
/
OpenExchangeApiClient.java
File metadata and controls
272 lines (265 loc) · 11.4 KB
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
package com.openexchangeapi;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Minimal OpenExchangeAPI Java SDK. All endpoints supported. API key is optional.
* <p>
* Usage:
* <pre>
* OpenExchangeApiClient api = new OpenExchangeApiClient("YOUR_API_KEY");
* GetLatestRatesResponse latest = api.getLatest("EUR");
* System.out.println(latest.rates.get("USD"));
* </pre>
*/
public class OpenExchangeApiClient {
private final String apiKey;
private final String baseUrl;
private final HttpClient httpClient;
private final ObjectMapper objectMapper;
public OpenExchangeApiClient() {
this(null, "https://api.openexchangeapi.com");
}
public OpenExchangeApiClient(String apiKey) {
this(apiKey, "https://api.openexchangeapi.com");
}
public OpenExchangeApiClient(String apiKey, String baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
this.httpClient = HttpClient.newHttpClient();
this.objectMapper = new ObjectMapper();
}
private <T> T get(String path, Map<String, String> params, Class<T> clazz) throws IOException, InterruptedException {
StringBuilder url = new StringBuilder(baseUrl + path);
Map<String, String> qp = new LinkedHashMap<>();
if (apiKey != null && !apiKey.isEmpty()) qp.put("app_id", apiKey);
if (params != null) qp.putAll(params);
if (!qp.isEmpty()) {
url.append("?");
url.append(qp.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).reduce((a, b) -> a + "&" + b).orElse(""));
}
HttpRequest req = HttpRequest.newBuilder(URI.create(url.toString())).GET().build();
HttpResponse<String> resp = httpClient.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() >= 400) throw new IOException(resp.body());
return objectMapper.readValue(resp.body(), clazz);
}
private <T> T get(String path, Map<String, String> params, TypeReference<T> typeRef) throws IOException, InterruptedException {
StringBuilder url = new StringBuilder(baseUrl + path);
Map<String, String> qp = new LinkedHashMap<>();
if (apiKey != null && !apiKey.isEmpty()) qp.put("app_id", apiKey);
if (params != null) qp.putAll(params);
if (!qp.isEmpty()) {
url.append("?");
url.append(qp.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).reduce((a, b) -> a + "&" + b).orElse(""));
}
HttpRequest req = HttpRequest.newBuilder(URI.create(url.toString())).GET().build();
HttpResponse<String> resp = httpClient.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() >= 400) throw new IOException(resp.body());
return objectMapper.readValue(resp.body(), typeRef);
}
// --- API Methods ---
/**
* Get latest exchange rates.
* @param base Optional base currency code (ISO 4217)
* @return Latest rates response
*/
public GetLatestRatesResponse getLatest(String base) throws IOException, InterruptedException {
Map<String, String> params = base != null ? Map.of("base", base) : null;
return get("/v1/latest", params, GetLatestRatesResponse.class);
}
/**
* Get latest exchange rates (high precision).
* @param base Optional base currency code (ISO 4217)
* @return Latest precise rates response
*/
public GetLatestPreciseRatesResponse getLatestPrecise(String base) throws IOException, InterruptedException {
Map<String, String> params = base != null ? Map.of("base", base) : null;
return get("/v1/latest-precise", params, GetLatestPreciseRatesResponse.class);
}
/**
* Get historical exchange rates.
* @param date Date in YYYY-MM-DD format
* @param base Optional base currency code (ISO 4217)
* @return Historical rates response
*/
public GetHistoricalRatesResponse getHistorical(String date, String base) throws IOException, InterruptedException {
if (date == null || date.isEmpty()) throw new IllegalArgumentException("date is required");
Map<String, String> params = base != null ? Map.of("base", base) : null;
return get("/v1/historical/" + date, params, GetHistoricalRatesResponse.class);
}
/**
* Get historical exchange rates (high precision).
* @param date Date in YYYY-MM-DD format
* @param base Optional base currency code (ISO 4217)
* @return Historical precise rates response
*/
public GetHistoricalPreciseRatesResponse getHistoricalPrecise(String date, String base) throws IOException, InterruptedException {
if (date == null || date.isEmpty()) throw new IllegalArgumentException("date is required");
Map<String, String> params = base != null ? Map.of("base", base) : null;
return get("/v1/historical-precise/" + date, params, GetHistoricalPreciseRatesResponse.class);
}
/**
* Convert currency.
* @param from Source currency code (ISO 4217)
* @param to Target currency code (ISO 4217)
* @param amount Amount to convert
* @return Conversion result
*/
public ConvertCurrencyResponse convert(String from, String to, double amount) throws IOException, InterruptedException {
if (from == null || to == null) throw new IllegalArgumentException("from and to are required");
Map<String, String> params = Map.of("from", from, "to", to, "amount", Double.toString(amount));
return get("/v1/convert", params, ConvertCurrencyResponse.class);
}
/**
* Convert currency (high precision).
* @param from Source currency code (ISO 4217)
* @param to Target currency code (ISO 4217)
* @param amount Amount to convert (string for high precision)
* @return Conversion result (high precision)
*/
public ConvertCurrencyPreciseResponse convertPrecise(String from, String to, String amount) throws IOException, InterruptedException {
if (from == null || to == null || amount == null) throw new IllegalArgumentException("from, to, and amount are required");
Map<String, String> params = Map.of("from", from, "to", to, "amount", amount);
return get("/v1/convert-precise", params, ConvertCurrencyPreciseResponse.class);
}
/**
* List all supported currencies.
* @param type Optional filter by currency type ("fiat" or "crypto")
* @return List of currencies
*/
public List<Currency> listCurrencies(String type) throws IOException, InterruptedException {
Map<String, String> params = type != null ? Map.of("type", type) : null;
return get("/v1/currencies", params, new TypeReference<List<Currency>>(){});
}
/**
* Get currency by code.
* @param code ISO 4217 currency code
* @return Currency details
*/
public GetCurrencyResponse getCurrency(String code) throws IOException, InterruptedException {
if (code == null || code.isEmpty()) throw new IllegalArgumentException("code is required");
return get("/v1/currencies/" + code, null, GetCurrencyResponse.class);
}
// --- Response Types ---
/**
* Response for /v1/latest endpoint (standard precision rates).
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class GetLatestRatesResponse {
public String base;
public String date;
public long timestamp;
public Map<String, Double> rates;
}
/**
* Response for /v1/latest-precise endpoint (high precision rates as strings).
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class GetLatestPreciseRatesResponse {
public String base;
public String date;
public long timestamp;
public Map<String, String> rates;
/**
* Returns rates as doubles (parsed from strings).
*/
public Map<String, Double> getRatesAsDouble() {
Map<String, Double> out = new HashMap<>();
if (rates != null) for (var e : rates.entrySet()) {
try { out.put(e.getKey(), Double.parseDouble(e.getValue())); } catch (Exception ignore) {}
}
return out;
}
}
/**
* Response for /v1/historical/{date} endpoint (standard precision).
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class GetHistoricalRatesResponse {
public String base;
public String date;
public long timestamp;
public Map<String, Double> rates;
}
/**
* Response for /v1/historical-precise/{date} endpoint (high precision rates as strings).
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class GetHistoricalPreciseRatesResponse {
public String base;
public String date;
public long timestamp;
public Map<String, String> rates;
/**
* Returns rates as doubles (parsed from strings).
*/
public Map<String, Double> getRatesAsDouble() {
Map<String, Double> out = new HashMap<>();
if (rates != null) for (var e : rates.entrySet()) {
try { out.put(e.getKey(), Double.parseDouble(e.getValue())); } catch (Exception ignore) {}
}
return out;
}
}
/**
* Response for /v1/convert endpoint (standard precision).
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ConvertCurrencyResponse {
@JsonAlias("from") public String from;
public String to;
public double amount;
public double rate;
public double result;
}
/**
* Response for /v1/convert-precise endpoint (high precision as strings).
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ConvertCurrencyPreciseResponse {
@JsonAlias("from") public String from;
public String to;
public String amount;
public String rate;
public String result;
/**
* Amount as double (parsed from string).
*/
public Double getAmountAsDouble() { try { return Double.parseDouble(amount); } catch (Exception e) { return null; } }
/**
* Rate as double (parsed from string).
*/
public Double getRateAsDouble() { try { return Double.parseDouble(rate); } catch (Exception e) { return null; } }
/**
* Result as double (parsed from string).
*/
public Double getResultAsDouble() { try { return Double.parseDouble(result); } catch (Exception e) { return null; } }
}
/**
* Currency object returned by /v1/currencies and /v1/currencies/{code}.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Currency {
public String code;
public String name;
public String type;
public int digits;
public String symbol;
public int iso_num;
public Map<String, Object> meta;
}
/**
* Response for /v1/currencies/{code} endpoint.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class GetCurrencyResponse {
public Currency currency;
}
}