-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathIPinfo.java
More file actions
535 lines (481 loc) · 18.6 KB
/
IPinfo.java
File metadata and controls
535 lines (481 loc) · 18.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
package io.ipinfo.api;
import com.google.common.net.InetAddresses;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.ipinfo.api.cache.Cache;
import io.ipinfo.api.cache.SimpleCache;
import io.ipinfo.api.context.Context;
import io.ipinfo.api.errors.RateLimitedException;
import io.ipinfo.api.model.ASNResponse;
import io.ipinfo.api.model.IPResponse;
import io.ipinfo.api.model.MapResponse;
import io.ipinfo.api.model.ResproxyResponse;
import io.ipinfo.api.request.ASNRequest;
import io.ipinfo.api.request.IPRequest;
import io.ipinfo.api.request.MapRequest;
import io.ipinfo.api.request.ResproxyRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import javax.annotation.ParametersAreNonnullByDefault;
import okhttp3.*;
public class IPinfo {
private static final int batchMaxSize = 1000;
private static final int batchReqTimeoutDefault = 5;
private static final BatchReqOpts defaultBatchReqOpts =
new BatchReqOpts.Builder()
.setBatchSize(batchMaxSize)
.setTimeoutPerBatch(batchReqTimeoutDefault)
.build();
private static final Gson gson = new Gson();
private final OkHttpClient client;
private final Context context;
private final String token;
private final Cache cache;
IPinfo(OkHttpClient client, Context context, String token, Cache cache) {
this.client = client;
this.context = context;
this.token = token;
this.cache = cache;
}
public static void main(String... args) {
System.out.println(
"This library is not meant to be run as a standalone jar."
);
System.exit(0);
}
/**
* Lookup IP information using the IP.
*
* @param ip the ip string to lookup - accepts both ipv4 and ipv6.
* @return IPResponse response from the api.
* @throws RateLimitedException an exception when your api key has been rate limited.
*/
public IPResponse lookupIP(String ip) throws RateLimitedException {
IPResponse response = (IPResponse) cache.get(cacheKey(ip));
if (response != null) {
return response;
}
response = new IPRequest(client, token, ip).handle();
response.setContext(context);
cache.set(cacheKey(ip), response);
return response;
}
/**
* Lookup ASN information using the AS number.
*
* @param asn the asn string to lookup.
* @return ASNResponse response from the api.
* @throws RateLimitedException an exception when your api key has been rate limited.
*/
public ASNResponse lookupASN(String asn) throws RateLimitedException {
ASNResponse response = (ASNResponse) cache.get(cacheKey(asn));
if (response != null) {
return response;
}
response = new ASNRequest(client, token, asn).handle();
response.setContext(context);
cache.set(cacheKey(asn), response);
return response;
}
/**
* Lookup residential proxy information using the IP.
*
* @param ip the ip string to lookup - accepts both ipv4 and ipv6.
* @return ResproxyResponse response from the api.
* @throws RateLimitedException an exception when your api key has been rate limited.
*/
public ResproxyResponse lookupResproxy(String ip)
throws RateLimitedException {
String cacheKeyStr = "resproxy:" + ip;
ResproxyResponse response = (ResproxyResponse) cache.get(
cacheKey(cacheKeyStr)
);
if (response != null) {
return response;
}
response = new ResproxyRequest(client, token, ip).handle();
cache.set(cacheKey(cacheKeyStr), response);
return response;
}
/**
* Get a map of a list of IPs.
*
* @param ips the list of IPs to map.
* @return String the URL to the map.
* @throws RateLimitedException an exception when your API key has been rate limited.
*/
public String getMap(List<String> ips) throws RateLimitedException {
MapResponse response = new MapRequest(client, token, ips).handle();
return response.getReportUrl();
}
/**
* Get the result of a list of URLs in bulk.
*
* @param urls the list of URLs.
* @return the result where each URL is the key and the value is the data for that URL.
* @throws RateLimitedException an exception when your API key has been rate limited.
*/
public ConcurrentHashMap<String, Object> getBatch(List<String> urls)
throws RateLimitedException {
return this.getBatchGeneric(urls, defaultBatchReqOpts);
}
/**
* Get the result of a list of URLs in bulk.
*
* @param urls the list of URLs.
* @param opts options to modify the behavior of the batch operation.
* @return the result where each URL is the key and the value is the data for that URL.
* @throws RateLimitedException an exception when your API key has been rate limited.
*/
public ConcurrentHashMap<String, Object> getBatch(
List<String> urls,
BatchReqOpts opts
) throws RateLimitedException {
return this.getBatchGeneric(urls, opts);
}
/**
* Get the result of a list of IPs in bulk.
*
* @param ips the list of IPs.
* @return the result where each IP is the key and the value is the data for that IP.
* @throws RateLimitedException an exception when your API key has been rate limited.
*/
public ConcurrentHashMap<String, IPResponse> getBatchIps(List<String> ips)
throws RateLimitedException {
return new ConcurrentHashMap(
this.getBatchGeneric(ips, defaultBatchReqOpts)
);
}
/**
* Get the result of a list of IPs in bulk.
*
* @param ips the list of IPs.
* @param opts options to modify the behavior of the batch operation.
* @return the result where each IP is the key and the value is the data for that IP.
* @throws RateLimitedException an exception when your API key has been rate limited.
*/
public ConcurrentHashMap<String, IPResponse> getBatchIps(
List<String> ips,
BatchReqOpts opts
) throws RateLimitedException {
return new ConcurrentHashMap(this.getBatchGeneric(ips, opts));
}
/**
* Get the result of a list of ASNs in bulk.
*
* @param asns the list of ASNs.
* @return the result where each ASN is the key and the value is the data for that ASN.
* @throws RateLimitedException an exception when your API key has been rate limited.
*/
public ConcurrentHashMap<String, ASNResponse> getBatchAsns(
List<String> asns
) throws RateLimitedException {
return new ConcurrentHashMap(
this.getBatchGeneric(asns, defaultBatchReqOpts)
);
}
/**
* Get the result of a list of ASNs in bulk.
*
* @param asns the list of ASNs.
* @param opts options to modify the behavior of the batch operation.
* @return the result where each ASN is the key and the value is the data for that ASN.
* @throws RateLimitedException an exception when your API key has been rate limited.
*/
public ConcurrentHashMap<String, ASNResponse> getBatchAsns(
List<String> asns,
BatchReqOpts opts
) throws RateLimitedException {
return new ConcurrentHashMap(this.getBatchGeneric(asns, opts));
}
private ConcurrentHashMap<String, Object> getBatchGeneric(
List<String> urls,
BatchReqOpts opts
) throws RateLimitedException {
int batchSize;
int timeoutPerBatch;
List<String> lookupUrls;
ConcurrentHashMap<String, Object> result;
// if the cache is available, filter out URLs already cached.
result = new ConcurrentHashMap<>(urls.size());
if (this.cache != null) {
lookupUrls = new ArrayList<>(urls.size() / 2);
for (String url : urls) {
Object val = cache.get(cacheKey(url));
if (val != null) {
result.put(url, val);
} else {
lookupUrls.add(url);
}
}
} else {
lookupUrls = urls;
}
// everything cached; exit early.
if (lookupUrls.size() == 0) {
return result;
}
// use correct batch size; default/clip to `batchMaxSize`.
if (opts.batchSize == 0 || opts.batchSize > batchMaxSize) {
batchSize = batchMaxSize;
} else {
batchSize = opts.batchSize;
}
// use correct timeout per batch; either default or user-provided.
if (opts.timeoutPerBatch == 0) {
timeoutPerBatch = batchReqTimeoutDefault;
} else {
timeoutPerBatch = opts.timeoutPerBatch;
}
// prep URL we'll target.
// add `filter=1` as qparam for filtering out empty results on server.
String postUrl;
if (opts.filter) {
postUrl = "https://ipinfo.io/batch?filter=1";
} else {
postUrl = "https://ipinfo.io/batch";
}
// prepare latch & common request.
// each request, when complete, will countdown the latch.
CountDownLatch latch = new CountDownLatch(
(int) Math.ceil(lookupUrls.size() / 1000.0)
);
Request.Builder reqCommon = new Request.Builder()
.url(postUrl)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", Credentials.basic(token, ""))
.addHeader("User-Agent", "IPinfoClient/Java/3.4.0");
for (int i = 0; i < lookupUrls.size(); i += batchSize) {
// create chunk.
int end = i + batchSize;
if (end > lookupUrls.size()) {
end = lookupUrls.size();
}
List<String> urlsChunk = lookupUrls.subList(i, end);
// prepare & queue up request.
String urlListJson = gson.toJson(urlsChunk);
RequestBody requestBody = RequestBody.create(null, urlListJson);
Request req = reqCommon.post(requestBody).build();
OkHttpClient chunkClient = client
.newBuilder()
.connectTimeout(timeoutPerBatch, TimeUnit.SECONDS)
.readTimeout(timeoutPerBatch, TimeUnit.SECONDS)
.build();
chunkClient
.newCall(req)
.enqueue(
new Callback() {
@Override
@ParametersAreNonnullByDefault
public void onFailure(Call call, IOException e) {
latch.countDown();
}
@Override
@ParametersAreNonnullByDefault
public void onResponse(Call call, Response response)
throws IOException {
if (
response.body() == null ||
response.code() == 429
) {
return;
}
Type respType = new TypeToken<
HashMap<String, Object>
>() {}.getType();
HashMap<String, Object> localResult = gson.fromJson(
response.body().string(),
respType
);
localResult.forEach(
new BiConsumer<String, Object>() {
@Override
public void accept(String k, Object v) {
if (k.startsWith("AS")) {
String vStr = gson.toJson(v);
ASNResponse vCasted = gson.fromJson(
vStr,
ASNResponse.class
);
vCasted.setContext(context);
result.put(k, vCasted);
} else if (
InetAddresses.isInetAddress(k)
) {
String vStr = gson.toJson(v);
IPResponse vCasted = gson.fromJson(
vStr,
IPResponse.class
);
vCasted.setContext(context);
result.put(k, vCasted);
} else {
result.put(k, v);
}
}
}
);
latch.countDown();
}
}
);
}
// wait for all requests to finish.
try {
if (opts.timeoutTotal == 0) {
latch.await();
} else {
boolean success = latch.await(
opts.timeoutTotal,
TimeUnit.SECONDS
);
if (!success) {
if (result.size() == 0) {
return null;
} else {
return result;
}
}
}
} catch (InterruptedException e) {
if (result.size() == 0) {
return null;
} else {
return result;
}
}
// insert any new lookups into the cache:
if (cache != null) {
for (String url : lookupUrls) {
Object v = result.get(url);
if (v != null) {
cache.set(cacheKey(url), v);
}
}
}
return result;
}
/**
* Converts a normal key into a versioned cache key.
*
* @param k the key to convert into a versioned cache key.
* @return the versioned cache key.
*/
public static String cacheKey(String k) {
return k + ":1";
}
public static class Builder {
private OkHttpClient client = new OkHttpClient.Builder().build();
private String token = "";
private Cache cache = new SimpleCache(Duration.ofDays(1));
public Builder setClient(OkHttpClient client) {
this.client = client;
return this;
}
public Builder setToken(String token) {
this.token = token;
return this;
}
public Builder setCache(Cache cache) {
this.cache = cache;
return this;
}
public IPinfo build() {
return new IPinfo(client, new Context(), token, cache);
}
}
public static class BatchReqOpts {
public final int batchSize;
public final int timeoutPerBatch;
public final int timeoutTotal;
public final boolean filter;
public BatchReqOpts(
int batchSize,
int timeoutPerBatch,
int timeoutTotal,
boolean filter
) {
this.batchSize = batchSize;
this.timeoutPerBatch = timeoutPerBatch;
this.timeoutTotal = timeoutTotal;
this.filter = filter;
}
public static class Builder {
private int batchSize = 1000;
private int timeoutPerBatch = 5;
private int timeoutTotal = 0;
private boolean filter = false;
/**
* batchSize is the internal batch size used per API request; the IPinfo
* API has a maximum batch size, but the batch request functions available
* in this library do not. Therefore the library chunks the input slices
* internally into chunks of size `batchSize`, clipping to the maximum
* allowed by the IPinfo API.
*
* 0 means to use the default batch size which is the max allowed by the
* IPinfo API.
*
* @param batchSize see description.
* @return the builder.
*/
public Builder setBatchSize(int batchSize) {
this.batchSize = batchSize;
return this;
}
/**
* timeoutPerBatch is the timeout in seconds that each batch of size
* `BatchSize` will have for its own request.
*
* 0 means to use a default of 5 seconds; any negative number will turn it
* off; turning it off does _not_ disable the effects of `timeoutTotal`.
*
* @param timeoutPerBatch see description.
* @return the builder.
*/
public Builder setTimeoutPerBatch(int timeoutPerBatch) {
this.timeoutPerBatch = timeoutPerBatch;
return this;
}
/**
* timeoutTotal is the total timeout in seconds for all batch requests in a
* batch request function to complete.
*
* 0 means no total timeout; `timeoutPerBatch` will still apply.
*
* @param timeoutTotal see description.
* @return the builder.
*/
public Builder setTimeoutTotal(int timeoutTotal) {
this.timeoutTotal = timeoutTotal;
return this;
}
/**
* filter, if turned on, will filter out a URL whose value was deemed empty
* on the server.
*
* @param filter see description.
* @return the builder.
*/
public Builder setFilter(boolean filter) {
this.filter = filter;
return this;
}
public IPinfo.BatchReqOpts build() {
return new IPinfo.BatchReqOpts(
batchSize,
timeoutPerBatch,
timeoutTotal,
filter
);
}
}
}
}