-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBaseService.java
More file actions
192 lines (167 loc) · 6.62 KB
/
BaseService.java
File metadata and controls
192 lines (167 loc) · 6.62 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
// This file was generated by liblab | https://liblab.com/
package com.asaas.apisdk.services;
import com.asaas.apisdk.config.AsaasSdkConfig;
import com.asaas.apisdk.exceptions.ApiError;
import com.asaas.apisdk.http.Environment;
import com.asaas.apisdk.http.ModelConverter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
public class BaseService {
private static final Logger logger = Logger.getLogger(BaseService.class.getName());
protected OkHttpClient httpClient;
protected AsaasSdkConfig config;
protected Map<Integer, ErrorMapping<?>> errorMappings;
private static class ErrorMapping<T> {
private final Class<T> modelClass;
private final Class<? extends ApiError> exceptionClass;
public ErrorMapping(Class<T> modelClass, Class<? extends ApiError> exceptionClass) {
this.modelClass = modelClass;
this.exceptionClass = exceptionClass;
}
}
public BaseService(OkHttpClient httpClient, AsaasSdkConfig config) {
this.httpClient = httpClient;
this.config = config;
this.errorMappings = new HashMap<>();
}
public void setBaseUrl(String baseUrl) {
this.config.setBaseUrl(baseUrl);
}
public void setEnvironment(Environment environment) {
this.config.setEnvironment(environment);
}
protected <T> void addErrorMapping(int status, Class<T> modelClass, Class<? extends ApiError> exceptionClass) {
this.errorMappings.put(status, new ErrorMapping<>(modelClass, exceptionClass));
}
private String extractErrorMessage(Response response, Object errorModel) {
String message = null;
if (errorModel != null) {
try {
message = (String) errorModel.getClass().getMethod("getMessage").invoke(errorModel);
} catch (Exception e) {
// Ignore if getMessage doesn't exist or fails
}
}
if (Objects.isNull(message) || message.trim().isEmpty()) {
message = response.message();
}
if (Objects.isNull(message) || message.trim().isEmpty()) {
message = String.format("%d error in request to: %s", response.code(), response.request().url());
}
return message;
}
protected Response execute(Request request) throws ApiError {
Response response;
try {
response = this.httpClient.newCall(request).execute();
} catch (IOException e) {
if (e instanceof SocketTimeoutException) {
throw new ApiError("Request timed out", 408, null);
}
throw new ApiError(e.getMessage(), 0, null);
}
if (response.isSuccessful()) {
return response;
}
// Handle error response
ErrorMapping<?> errorMapping = this.errorMappings.get(response.code());
if (errorMapping != null) {
Object errorModel = null;
try {
errorModel = ModelConverter.convert(response, errorMapping.modelClass);
} catch (Exception e) {
logger.log(Level.WARNING, "Failed to deserialize error response to " + errorMapping.modelClass.getName(), e);
}
if (errorModel != null) {
try {
Constructor<? extends ApiError> constructor = errorMapping.exceptionClass.getConstructor(
errorMapping.modelClass,
String.class,
int.class,
Response.class
);
String message = extractErrorMessage(response, errorModel);
throw constructor.newInstance(errorModel, message, response.code(), response);
} catch (ReflectiveOperationException e) {
logger.log(
Level.WARNING,
"Failed to create exception instance for " + errorMapping.exceptionClass.getName(),
e
);
}
}
}
// If no specific error model is mapped or conversion failed, throw generic ApiError
throw new ApiError(extractErrorMessage(response, null), response.code(), response);
}
protected CompletableFuture<Response> executeAsync(Request request) {
CompletableFuture<Response> future = new CompletableFuture<>();
this.httpClient.newCall(request).enqueue(
new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) {
if (!response.isSuccessful()) {
// Handle error response
ErrorMapping<?> errorMapping = errorMappings.get(response.code());
if (errorMapping != null) {
try {
Object errorModel = ModelConverter.convert(response, errorMapping.modelClass);
if (errorModel != null) {
// Use reflection to create the exception
Constructor<? extends ApiError> constructor = errorMapping.exceptionClass.getConstructor(
errorMapping.modelClass,
String.class,
int.class,
Response.class
);
String message = extractErrorMessage(response, errorModel);
future.completeExceptionally(
constructor.newInstance(errorModel, message, response.code(), response)
);
return;
}
} catch (Exception e) {
logger.log(
Level.WARNING,
"Failed to deserialize error response to " + errorMapping.modelClass.getName(),
e
);
}
}
// If no specific error model is mapped or conversion failed, throw generic ApiError
ApiError error = new ApiError(extractErrorMessage(response, null), response.code(), response);
future.completeExceptionally(error);
return;
}
future.complete(response);
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
if (e instanceof SocketTimeoutException) {
ApiError error = new ApiError("Request timed out", 408, null);
future.completeExceptionally(error);
} else {
ApiError error = new ApiError(e.getMessage(), 0, null);
future.completeExceptionally(error);
}
}
}
);
return future;
}
}