-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLettermintClient.java
More file actions
257 lines (211 loc) · 9.37 KB
/
Copy pathLettermintClient.java
File metadata and controls
257 lines (211 loc) · 9.37 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
package co.lettermint.client;
import co.lettermint.BuildInfo;
import co.lettermint.exceptions.HttpRequestException;
import co.lettermint.exceptions.LettermintException;
import co.lettermint.exceptions.ValidationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* HTTP client for Lettermint API requests.
*/
public class LettermintClient {
private static final String DEFAULT_BASE_URL = "https://api.lettermint.co/v1";
private static final int DEFAULT_TIMEOUT_SECONDS = 30;
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private final String apiToken;
private final String baseUrl;
private final AuthMode authMode;
private final OkHttpClient httpClient;
private final ObjectMapper objectMapper;
public LettermintClient(String apiToken) {
this(apiToken, DEFAULT_BASE_URL);
}
public LettermintClient(String apiToken, String baseUrl) {
this(apiToken, baseUrl, AuthMode.SENDING);
}
public LettermintClient(String apiToken, String baseUrl, AuthMode authMode) {
if (apiToken == null || apiToken.isEmpty()) {
throw new IllegalArgumentException("API token is required");
}
this.apiToken = apiToken;
this.baseUrl = baseUrl != null ? baseUrl : DEFAULT_BASE_URL;
this.authMode = authMode;
this.objectMapper = new ObjectMapper();
this.httpClient = buildHttpClient();
}
private OkHttpClient buildHttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.addInterceptor(this::addDefaultHeaders)
.build();
}
private Response addDefaultHeaders(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("User-Agent", buildUserAgent());
if (authMode == AuthMode.BEARER) {
builder.header("Authorization", "Bearer " + apiToken);
builder.removeHeader("x-lettermint-token");
} else {
builder.header("x-lettermint-token", apiToken);
builder.removeHeader("Authorization");
}
return chain.proceed(builder.build());
}
private String buildUserAgent() {
String javaVersion = System.getProperty("java.version", "unknown");
return String.format("Lettermint/%s (Java; Java %s)", BuildInfo.VERSION, javaVersion);
}
public <T> T post(String path, Object payload, Class<T> responseClass) {
return post(path, payload, responseClass, null);
}
public <T> T post(String path, Object payload, Class<T> responseClass, Map<String, String> headers) {
return request("POST", url(path, null), payload, responseClass, null, headers);
}
public <T> T post(String path, Object payload, TypeReference<T> responseType) {
return post(path, payload, responseType, null);
}
public <T> T post(String path, Object payload, TypeReference<T> responseType, Map<String, String> headers) {
return request("POST", url(path, null), payload, null, responseType, headers);
}
public <T> T get(String path, Class<T> responseClass) {
return get(path, responseClass, null);
}
public <T> T get(String path, Class<T> responseClass, Map<String, String> query) {
return request("GET", url(path, query), null, responseClass, null, null);
}
public <T> T put(String path, Object payload, Class<T> responseClass) {
return request("PUT", url(path, null), payload, responseClass, null, null);
}
public <T> T patch(String path, Object payload, Class<T> responseClass) {
return request("PATCH", url(path, null), payload, responseClass, null, null);
}
public <T> T delete(String path, Class<T> responseClass) {
return request("DELETE", url(path, null), null, responseClass, null, null);
}
public String getRaw(String path) {
Request request = new Request.Builder().url(url(path, null)).get().build();
try (Response response = httpClient.newCall(request).execute()) {
String responseBody = response.body() != null ? response.body().string() : "";
if (!response.isSuccessful()) {
handleErrorResponse(response.code(), responseBody);
}
return responseBody;
} catch (SocketTimeoutException e) {
throw new LettermintException("Request timed out", e);
} catch (IOException e) {
throw new LettermintException("Request failed: " + e.getMessage(), e);
}
}
private <T> T request(String method, String requestUrl, Object payload, Class<T> responseClass, TypeReference<T> responseType, Map<String, String> headers) {
Request.Builder requestBuilder = new Request.Builder().url(requestUrl);
RequestBody body = null;
if (payload != null) {
try {
body = RequestBody.create(objectMapper.writeValueAsString(payload), JSON);
} catch (JsonProcessingException e) {
throw new LettermintException("Failed to serialize request body", e);
}
}
if ("POST".equals(method)) {
requestBuilder.post(body != null ? body : RequestBody.create(new byte[0], JSON));
} else if ("PUT".equals(method)) {
requestBuilder.put(body != null ? body : RequestBody.create(new byte[0], JSON));
} else if ("PATCH".equals(method)) {
requestBuilder.patch(body != null ? body : RequestBody.create(new byte[0], JSON));
} else if ("DELETE".equals(method)) {
requestBuilder.delete();
} else {
requestBuilder.get();
}
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.header(entry.getKey(), entry.getValue());
}
}
Request request = requestBuilder.build();
try (Response response = httpClient.newCall(request).execute()) {
String responseBody = response.body() != null ? response.body().string() : "";
if (!response.isSuccessful()) {
handleErrorResponse(response.code(), responseBody);
}
if (responseClass != null) {
return objectMapper.readValue(responseBody, responseClass);
}
return objectMapper.readValue(responseBody, responseType);
} catch (SocketTimeoutException e) {
throw new LettermintException("Request timed out", e);
} catch (IOException e) {
throw new LettermintException("Request failed: " + e.getMessage(), e);
}
}
private String url(String path) {
return url(path, null);
}
private String url(String path, Map<String, String> query) {
if (isAbsolutePath(path)) {
throw new IllegalArgumentException("Request path must be relative");
}
StringBuilder result = new StringBuilder(baseUrl.replaceAll("/+$", "") + path);
if (query != null && !query.isEmpty()) {
result.append("?");
boolean first = true;
for (Map.Entry<String, String> entry : query.entrySet()) {
if (!first) {
result.append("&");
}
first = false;
result.append(encode(entry.getKey())).append("=").append(encode(entry.getValue()));
}
}
return result.toString();
}
private boolean isAbsolutePath(String path) {
return path.matches("^[a-zA-Z][a-zA-Z0-9+.-]*:.*") || path.startsWith("//");
}
private String encode(String value) {
try {
return URLEncoder.encode(value, "UTF-8");
} catch (IOException e) {
throw new LettermintException("Failed to encode query parameter", e);
}
}
private void handleErrorResponse(int statusCode, String responseBody) {
String message = extractErrorMessage(responseBody, statusCode);
if (statusCode == 422) {
throw new ValidationException(message, responseBody);
}
throw new HttpRequestException(message, statusCode, responseBody);
}
private String extractErrorMessage(String responseBody, int statusCode) {
try {
Map<?, ?> errorMap = objectMapper.readValue(responseBody, Map.class);
if (errorMap.containsKey("message")) {
return (String) errorMap.get("message");
}
if (errorMap.containsKey("error")) {
return (String) errorMap.get("error");
}
} catch (Exception ignored) {
}
return "HTTP " + statusCode + " error";
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public enum AuthMode {
SENDING,
BEARER
}
}