use of org.infobip.mobile.messaging.api.support.ApiIOException 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
}
}
}
}
use of org.infobip.mobile.messaging.api.support.ApiIOException in project mobile-messaging-sdk-android by infobip.
the class MAsyncTaskTest method shouldMapErrorWithContentToAppropriateException.
@Test
public void shouldMapErrorWithContentToAppropriateException() {
// Given
String givenContent = "content";
ApiIOException givenError = new ApiBackendExceptionWithContent(ApiErrorCode.CONTACT_SERVICE_ERROR, "", givenContent);
Mockito.when(tester.run(any(Object[].class))).thenThrow(givenError);
// When
asyncTask.execute(executor);
// Then
Mockito.verify(tester, Mockito.after(100).times(1)).error(any(Object[].class), eqErrorWithContent(givenError, givenContent));
Mockito.verify(tester, Mockito.never()).after(Mockito.any());
}
use of org.infobip.mobile.messaging.api.support.ApiIOException in project mobile-messaging-sdk-android by infobip.
the class MAsyncTaskTest method shouldMapInvalidBirthdateToAppropriateException.
@Test
public void shouldMapInvalidBirthdateToAppropriateException() {
// Given
ApiIOException givenError = new ApiIOException(ApiErrorCode.INVALID_BIRTHDATE_FORMAT, "");
Mockito.when(tester.run(any(Object[].class))).thenThrow(givenError);
// When
asyncTask.execute(executor);
// Then
Mockito.verify(tester, Mockito.after(100).times(1)).error(any(Object[].class), eqInvalidParamErrorWith(givenError));
Mockito.verify(tester, Mockito.never()).after(Mockito.any());
}
use of org.infobip.mobile.messaging.api.support.ApiIOException in project mobile-messaging-sdk-android by infobip.
the class RetryableSynchronizersTest method setUp.
@SuppressLint("CommitPrefEdits")
@Override
public void setUp() throws Exception {
super.setUp();
MobileMessagingStats stats = mobileMessagingCore.getStats();
PreferenceHelper.saveBoolean(context, MobileMessagingProperty.REPORT_SYSTEM_INFO, true);
PreferenceHelper.saveInt(context, MobileMessagingProperty.DEFAULT_EXP_BACKOFF_MULTIPLIER, 0);
PreferenceHelper.remove(context, MobileMessagingProperty.REPORTED_SYSTEM_DATA_HASH);
mobileMessageHandler = mock(MobileMessageHandler.class);
mobileApiData = mock(MobileApiData.class);
mobileApiMessages = mock(MobileApiMessages.class);
mobileApiRegistration = mock(MobileApiRegistration.class);
given(mobileApiData.reportUserData(anyString(), any(UserDataReport.class))).willThrow(new BackendCommunicationException("Backend error", new ApiIOException("0", "Backend error")));
doThrow(new BackendCommunicationException("Backend error", new ApiIOException("0", "Backend error"))).when(mobileApiData).reportSystemData(any(SystemDataReport.class));
given(mobileApiMessages.sync(any(SyncMessagesBody.class))).willThrow(new BackendCommunicationException("Backend error", new ApiIOException("0", "Backend error")));
given(mobileApiRegistration.upsert(anyString(), anyBoolean())).willThrow(new BackendCommunicationException("Backend error", new ApiIOException("0", "Backend error")));
RetryPolicyProvider retryPolicyProvider = new RetryPolicyProvider(context);
retryPolicy = retryPolicyProvider.DEFAULT();
executor = Executors.newSingleThreadExecutor();
systemDataReporter = new SystemDataReporter(mobileMessagingCore, stats, retryPolicy, executor, broadcaster, mobileApiData);
messagesSynchronizer = new MessagesSynchronizer(mobileMessagingCore, stats, executor, broadcaster, retryPolicy, mobileMessageHandler, mobileApiMessages);
registrationSynchronizer = new RegistrationSynchronizer(context, mobileMessagingCore, stats, executor, broadcaster, retryPolicyProvider, mobileApiRegistration);
userDataReporter = new UserDataReporter(mobileMessagingCore, executor, broadcaster, retryPolicyProvider, stats, mobileApiData);
}
use of org.infobip.mobile.messaging.api.support.ApiIOException in project mobile-messaging-sdk-android by infobip.
the class RetryableSynchronizerTest method test_geo_report_retry.
@Test
public void test_geo_report_retry() {
// Given
createReport(context, "signalingMessageId1", "campaignId1", "messageId1", true, createArea("areaId1"));
createReport(context, "signalingMessageId2", "campaignId2", "messageId2", true, createArea("areaId2"));
createReport(context, "signalingMessageId2", "campaignId2", "messageId3", true, createArea("areaId3"));
given(mobileApiGeo.report(any(EventReportBody.class))).willThrow(new BackendCommunicationException("Backend error", new ApiIOException("0", "Backend error")));
// When
geoReporter.synchronize();
// Then
verify(geoBroadcaster, Mockito.after(8000).times(1)).error(any(MobileMessagingError.class));
verify(mobileApiGeo, times(4)).report(any(EventReportBody.class));
}
Aggregations