This repository has been archived by the owner on Nov 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 206
/
OCRRequestHelper.java
83 lines (67 loc) · 2.86 KB
/
OCRRequestHelper.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
package io;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import javax.net.ssl.SSLContext;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.concurrent.ExecutionException;
/**
* IO.OCRRequestHelper.java
* handles the OCR request with HTTP post.
* Parsing the result as a IO.Response object.
*/
public class OCRRequestHelper {
/**
* Send the request with Json parameters to Mathpix API.
* Parsing the result as a IO.Response object.
*
* @param parameters JsonObject to send as the request parameters.
* @return a IO.Response object.
*/
public static Response getResult(JsonObject parameters) throws NoSuchAlgorithmException {
String appId;
String appKey;
var APICredentialConfig = PreferenceHelper.getAPICredentialConfig();
if (APICredentialConfig.isValid()) {
appId = APICredentialConfig.getAppId();
appKey = APICredentialConfig.getAppKey();
} else {
// early return
return new Response(IOUtils.INVALID_CREDENTIALS_ERROR);
}
// TLSv1.2 only
var sslParameters = SSLContext.getDefault().getDefaultSSLParameters();
sslParameters.setProtocols(new String[]{"TLSv1.2"});
var httpClientBuilder = HttpClient.newBuilder().sslParameters(sslParameters);
if (PreferenceHelper.getProxyEnableOption()) {
// proxy enabled
var proxyConfig = PreferenceHelper.getProxyConfig();
if (proxyConfig.isValid()) {
var inetSocketAddress = new InetSocketAddress(proxyConfig.getHostname(), proxyConfig.getPort());
httpClientBuilder.proxy(ProxySelector.of(inetSocketAddress));
} else {
return new Response(IOUtils.INVALID_PROXY_CONFIG_ERROR);
}
}
var httpClient = httpClientBuilder.build();
// request body
var requestBody = HttpRequest.BodyPublishers.ofString(parameters.toString());
// wait up to 30 seconds
var httpRequest = HttpRequest.newBuilder().uri(URI.create(IOUtils.API_URL)).
headers("app_id", appId, "app_key", appKey, "Content-type", "application/json").
POST(requestBody).timeout(Duration.ofSeconds(30)).build();
var completableFuture = httpClient.
sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::body);
try {
return new Gson().fromJson(completableFuture.get(), Response.class);
} catch (RuntimeException | InterruptedException | ExecutionException e) {
return new Response(e.getMessage());
}
}
}