use of org.infobip.mobile.messaging.api.support.ApiException in project mobile-messaging-sdk-android by infobip.
the class DefaultApiClient method execute.
@Override
public <B, R> R execute(HttpMethod method, String uri, String apiKey, Tuple<String, String> credentials, Map<String, Collection<Object>> queryParams, Map<String, Collection<Object>> headers, B body, Class<R> responseType) {
Request request = new Request(method, uri, apiKey, credentials, headers, queryParams, body);
for (RequestInterceptor interceptor : requestInterceptors) {
try {
request = interceptor.intercept(request);
} catch (Exception e) {
logger.e("Request interceptor " + interceptor + " thrown an exception " + e);
}
}
HttpURLConnection urlConnection = null;
try {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Collection<Object>> entry : request.queryParams.entrySet()) {
appendValue(sb, entry);
}
urlConnection = (HttpURLConnection) new URL(request.uri + sb.toString()).openConnection();
urlConnection.setRequestMethod(request.httpMethod.name());
urlConnection.setUseCaches(false);
if (request.httpMethod != HttpMethod.GET) {
urlConnection.setDoOutput(true);
}
urlConnection.setDoInput(true);
urlConnection.setConnectTimeout(connectTimeout);
urlConnection.setReadTimeout(readTimeout);
if (null != request.headers) {
for (Map.Entry<String, Collection<Object>> entry : request.headers.entrySet()) {
Collection<Object> value = entry.getValue();
if (null == value || value.isEmpty()) {
continue;
}
String key = entry.getKey().trim();
if (key.equalsIgnoreCase("Content-Length")) {
continue;
}
for (Object v : value) {
if (v == null)
continue;
urlConnection.setRequestProperty(key, v.toString());
}
}
}
if (StringUtils.isNotBlank(request.apiKey)) {
urlConnection.setRequestProperty("Authorization", "App " + request.apiKey);
} else if (request.credentials != null && StringUtils.isNotBlank(request.credentials.getLeft()) && StringUtils.isNotBlank(request.credentials.getRight())) {
String basicApiKey = new String(Base64.encodeBase64((request.credentials.getLeft() + ":" + request.credentials.getRight()).getBytes()));
urlConnection.setRequestProperty("Authorization", "Basic " + basicApiKey);
}
urlConnection.setRequestProperty("Accept", "application/json");
String userAgent = urlConnection.getRequestProperty("User-Agent");
if (null == userAgent) {
urlConnection.setRequestProperty("User-Agent", getUserAgent());
}
if (null != request.body) {
byte[] bytes = JSON_SERIALIZER.serialize(request.body).getBytes("UTF-8");
urlConnection.setRequestProperty("Content-Length", "" + Long.toString(bytes.length));
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
outputStream.write(bytes);
outputStream.flush();
} finally {
StreamUtils.closeSafely(outputStream);
}
}
int responseCode = urlConnection.getResponseCode();
interceptResponse(responseCode, urlConnection.getHeaderFields());
if (responseCode >= 400) {
ApiResponse apiResponse = new ApiResponse("-1", "Unknown error");
if (urlConnection.getContentLength() > 0) {
InputStream inputStream = urlConnection.getErrorStream();
String s = StreamUtils.readToString(inputStream, "UTF-8", Long.parseLong(urlConnection.getHeaderField("Content-Length")));
apiResponse = JSON_SERIALIZER.deserialize(s, ApiResponse.class);
}
if (responseCode >= 500) {
Tuple<String, String> tuple = safeGetErrorInfo(apiResponse, "-2", "Unknown API backend error");
throw new ApiBackendException(tuple.getLeft(), tuple.getRight());
}
Tuple<String, String> tuple = safeGetErrorInfo(apiResponse, "-3", "Unknown API error");
throw new ApiException(tuple.getLeft(), tuple.getRight());
}
if (urlConnection.getContentLength() <= 0) {
return null;
}
if (Void.class.equals(responseType) || void.class.equals(responseType)) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
String s = StreamUtils.readToString(inputStream, "UTF-8", Long.parseLong(urlConnection.getHeaderField("Content-Length")));
R response = JSON_SERIALIZER.deserialize(s, responseType);
ApiResponse apiResponse = null;
try {
apiResponse = JSON_SERIALIZER.deserialize(s, ApiResponse.class);
} catch (Exception ignored) {
}
if (apiResponse != null && apiResponse.getRequestError() != null) {
Tuple<String, String> tuple = safeGetErrorInfo(apiResponse, "-2", "Unknown API backend error");
throw new ApiBackendExceptionWithContent(tuple.getLeft(), tuple.getRight(), response);
}
return response;
} catch (Exception e) {
interceptErrorResponse(e);
if (e instanceof ApiIOException) {
throw (ApiIOException) e;
}
throw new ApiIOException("-4", "Can't access URI: " + request.uri, e);
} finally {
if (null != urlConnection) {
try {
urlConnection.disconnect();
} catch (Exception e) {
// ignore
}
}
}
}
Aggregations