-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch.java
More file actions
280 lines (250 loc) · 10.6 KB
/
Search.java
File metadata and controls
280 lines (250 loc) · 10.6 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
273
274
275
276
277
278
279
280
// Java example for the TCG Price Lookup API.
//
// Uses the JDK 11+ java.net.http.HttpClient and a tiny inline JSON parser
// (the response shapes are stable, so we keep this dependency-free).
//
// Usage:
// TCGLOOKUP_API_KEY=tlk_live_... java Search.java
//
// Requires Java 11+ for HttpClient + the single-file launcher.
// Get a free API key at https://tcgpricelookup.com/tcg-api
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Search {
private static final String API_BASE = "https://api.tcgpricelookup.com/v1";
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("TCGLOOKUP_API_KEY");
if (apiKey == null || apiKey.isEmpty()) {
System.err.println("Set TCGLOOKUP_API_KEY in your environment.");
System.exit(1);
}
TcgLookupClient client = new TcgLookupClient(apiKey);
try {
// Search for cards by name + game.
Map<String, Object> results = client.get(
"/cards/search",
Map.of("q", "charizard", "game", "pokemon", "limit", "5")
);
int total = ((Number) results.get("total")).intValue();
List<Map<String, Object>> data = (List<Map<String, Object>>) results.get("data");
System.out.printf("Found %d matches. Showing first %d:%n%n", total, data.size());
for (Map<String, Object> card : data) {
String name = (String) card.get("name");
String setName = (String) ((Map<String, Object>) card.get("set")).get("name");
String price = formatNearMintPrice(card);
System.out.printf(" %-30s %-28s %s%n", name, setName, price);
}
// Fetch the top hit's full price block.
if (!data.isEmpty()) {
System.out.println("\nFull price block for the top hit:");
String topId = (String) data.get(0).get("id");
Map<String, Object> top = client.get("/cards/" + topId, Map.of());
Map<String, Object> raw = (Map<String, Object>) ((Map<String, Object>) top.get("prices")).get("raw");
for (Map.Entry<String, Object> entry : raw.entrySet()) {
Map<String, Object> sources = (Map<String, Object>) entry.getValue();
Map<String, Object> tcg = (Map<String, Object>) sources.get("tcgplayer");
String price = "—";
if (tcg != null && tcg.get("market") != null) {
price = String.format("$%.2f", ((Number) tcg.get("market")).doubleValue());
}
System.out.printf(" %-20s %s%n", entry.getKey(), price);
}
}
System.out.printf("%nRate limit: %s/%s%n", client.rateLimitRemaining, client.rateLimitTotal);
} catch (TcgLookupException e) {
switch (e.status) {
case 403:
System.err.println("This endpoint requires Trader plan — upgrade at tcgpricelookup.com/tcg-api");
break;
case 429:
System.err.println("Rate limit exceeded. Wait or upgrade plan.");
break;
default:
System.err.printf("API error (HTTP %d): %s%n", e.status, e.getMessage());
}
System.exit(1);
}
}
private static String formatNearMintPrice(Map<String, Object> card) {
Map<String, Object> raw = (Map<String, Object>) ((Map<String, Object>) card.get("prices")).get("raw");
if (raw == null) return "—";
Map<String, Object> nm = (Map<String, Object>) raw.get("near_mint");
if (nm == null) return "—";
Map<String, Object> tcg = (Map<String, Object>) nm.get("tcgplayer");
if (tcg == null || tcg.get("market") == null) return "—";
return String.format("$%.2f", ((Number) tcg.get("market")).doubleValue());
}
// ====================================================== client + parser
static class TcgLookupClient {
private final String apiKey;
private final HttpClient http;
Integer rateLimitTotal;
Integer rateLimitRemaining;
TcgLookupClient(String apiKey) {
this.apiKey = apiKey;
this.http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(30))
.build();
}
@SuppressWarnings("unchecked")
Map<String, Object> get(String path, Map<String, String> query) throws Exception {
String qs = query.entrySet().stream()
.filter(e -> e.getValue() != null && !e.getValue().isEmpty())
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8)
+ "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
URI uri = URI.create(API_BASE + path + (qs.isEmpty() ? "" : "?" + qs));
HttpRequest req = HttpRequest.newBuilder(uri)
.header("X-API-Key", apiKey)
.header("Accept", "application/json")
.header("User-Agent", "tcg-api-example-java/0.1")
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
res.headers().firstValue("x-ratelimit-limit").ifPresent(v -> rateLimitTotal = Integer.parseInt(v));
res.headers().firstValue("x-ratelimit-remaining").ifPresent(v -> rateLimitRemaining = Integer.parseInt(v));
Object body = res.body().isEmpty() ? null : MiniJson.parse(res.body());
if (res.statusCode() >= 400) {
String msg = "HTTP " + res.statusCode();
if (body instanceof Map && ((Map<String, Object>) body).get("error") instanceof String) {
msg = (String) ((Map<String, Object>) body).get("error");
}
throw new TcgLookupException(msg, res.statusCode());
}
return (Map<String, Object>) body;
}
}
static class TcgLookupException extends RuntimeException {
final int status;
TcgLookupException(String message, int status) {
super(message);
this.status = status;
}
}
/**
* Tiny zero-dependency JSON parser. Handles only the subset the API
* actually returns: objects, arrays, strings, numbers, booleans, null.
* For production code, use Jackson or Gson — this is just enough for
* a self-contained example.
*/
static class MiniJson {
private final String s;
private int pos;
private MiniJson(String s) {
this.s = s;
}
static Object parse(String json) {
MiniJson p = new MiniJson(json);
p.skipWs();
Object v = p.readValue();
p.skipWs();
return v;
}
private Object readValue() {
skipWs();
char c = s.charAt(pos);
if (c == '{') return readObject();
if (c == '[') return readArray();
if (c == '"') return readString();
if (c == 't' || c == 'f') return readBool();
if (c == 'n') {
pos += 4;
return null;
}
return readNumber();
}
private Map<String, Object> readObject() {
Map<String, Object> out = new LinkedHashMap<>();
pos++; // {
skipWs();
if (s.charAt(pos) == '}') {
pos++;
return out;
}
while (true) {
skipWs();
String key = readString();
skipWs();
pos++; // :
Object value = readValue();
out.put(key, value);
skipWs();
char c = s.charAt(pos++);
if (c == '}') return out;
}
}
private List<Object> readArray() {
List<Object> out = new java.util.ArrayList<>();
pos++; // [
skipWs();
if (s.charAt(pos) == ']') {
pos++;
return out;
}
while (true) {
out.add(readValue());
skipWs();
char c = s.charAt(pos++);
if (c == ']') return out;
}
}
private String readString() {
pos++; // "
StringBuilder sb = new StringBuilder();
while (true) {
char c = s.charAt(pos++);
if (c == '"') return sb.toString();
if (c == '\\') {
char esc = s.charAt(pos++);
switch (esc) {
case '"': sb.append('"'); break;
case '\\': sb.append('\\'); break;
case '/': sb.append('/'); break;
case 'n': sb.append('\n'); break;
case 't': sb.append('\t'); break;
case 'r': sb.append('\r'); break;
case 'b': sb.append('\b'); break;
case 'f': sb.append('\f'); break;
case 'u':
sb.append((char) Integer.parseInt(s.substring(pos, pos + 4), 16));
pos += 4;
break;
default: sb.append(esc);
}
} else {
sb.append(c);
}
}
}
private Object readNumber() {
int start = pos;
while (pos < s.length() && "-+0123456789.eE".indexOf(s.charAt(pos)) >= 0) pos++;
String num = s.substring(start, pos);
if (num.contains(".") || num.contains("e") || num.contains("E")) {
return Double.parseDouble(num);
}
return Long.parseLong(num);
}
private Boolean readBool() {
if (s.charAt(pos) == 't') {
pos += 4;
return true;
}
pos += 5;
return false;
}
private void skipWs() {
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) pos++;
}
}
}