Search in sources :

Example 1 with ApiResponse

use of org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse 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
            }
        }
    }
}
Also used : OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) URL(java.net.URL) ApiResponse(org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse) HttpURLConnection(java.net.HttpURLConnection) BufferedOutputStream(java.io.BufferedOutputStream) ApiBackendException(org.infobip.mobile.messaging.api.support.ApiBackendException) InputStream(java.io.InputStream) ApiIOException(org.infobip.mobile.messaging.api.support.ApiIOException) ApiIOException(org.infobip.mobile.messaging.api.support.ApiIOException) ApiBackendException(org.infobip.mobile.messaging.api.support.ApiBackendException) ApiException(org.infobip.mobile.messaging.api.support.ApiException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ApiBackendExceptionWithContent(org.infobip.mobile.messaging.api.support.ApiBackendExceptionWithContent) Collection(java.util.Collection) Map(java.util.Map) ApiException(org.infobip.mobile.messaging.api.support.ApiException)

Example 2 with ApiResponse

use of org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse in project mobile-messaging-sdk-android by infobip.

the class DefaultApiClientTest method execute_withQueryParams_withHeaders_noBody_receivesError.

@Test(expected = ApiException.class)
public void execute_withQueryParams_withHeaders_noBody_receivesError() throws Exception {
    debugServer.respondWith(NanoHTTPD.Response.Status.UNAUTHORIZED, DefaultApiClient.JSON_SERIALIZER.serialize(new ApiResponse(new ApiError(new ApiServiceException("1", "Invalid Application ID")))));
    apiClient.execute(HttpMethod.GET, "http://127.0.0.1:" + debugServer.getListeningPort(), null, null, MapUtils.map("applicationId", "xyz", "currentRegistrationId", "1234"), MapUtils.map("X-Test-1", "test1", "X-Test-2", "test2"), null, ApiResponse.class);
}
Also used : ApiError(org.infobip.mobile.messaging.api.support.http.client.model.ApiError) ApiServiceException(org.infobip.mobile.messaging.api.support.http.client.model.ApiServiceException) ApiResponse(org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse) Test(org.junit.Test)

Example 3 with ApiResponse

use of org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse in project mobile-messaging-sdk-android by infobip.

the class DefaultApiClientTest method execute_withQueryParams_noHeaders_withBody_receivesError.

@Test(expected = ApiException.class)
public void execute_withQueryParams_noHeaders_withBody_receivesError() throws Exception {
    debugServer.respondWith(NanoHTTPD.Response.Status.UNAUTHORIZED, DefaultApiClient.JSON_SERIALIZER.serialize(new ApiResponse(new ApiError(new ApiServiceException("1", "Invalid Application ID")))));
    apiClient.execute(HttpMethod.POST, "http://127.0.0.1:" + debugServer.getListeningPort(), null, null, MapUtils.map("applicationId", "xyz", "currentRegistrationId", "1234"), null, new SomeApiRequest("Test"), ApiResponse.class);
}
Also used : ApiError(org.infobip.mobile.messaging.api.support.http.client.model.ApiError) ApiServiceException(org.infobip.mobile.messaging.api.support.http.client.model.ApiServiceException) ApiResponse(org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse) Test(org.junit.Test)

Example 4 with ApiResponse

use of org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse in project mobile-messaging-sdk-android by infobip.

the class DefaultApiClientTest method execute_withQueryParams_noHeaders_noBody_receivesError.

@Test(expected = ApiException.class)
public void execute_withQueryParams_noHeaders_noBody_receivesError() throws Exception {
    debugServer.respondWith(NanoHTTPD.Response.Status.UNAUTHORIZED, DefaultApiClient.JSON_SERIALIZER.serialize(new ApiResponse(new ApiError(new ApiServiceException("1", "Invalid Application ID")))));
    apiClient.execute(HttpMethod.GET, "http://127.0.0.1:" + debugServer.getListeningPort(), null, null, MapUtils.map("applicationId", "xyz", "currentRegistrationId", "1234"), null, null, ApiResponse.class);
}
Also used : ApiError(org.infobip.mobile.messaging.api.support.http.client.model.ApiError) ApiServiceException(org.infobip.mobile.messaging.api.support.http.client.model.ApiServiceException) ApiResponse(org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse) Test(org.junit.Test)

Example 5 with ApiResponse

use of org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse in project mobile-messaging-sdk-android by infobip.

the class DefaultApiClientTest method execute_withQueryParams_withHeaders_withBody_receivesError.

@Test(expected = ApiException.class)
public void execute_withQueryParams_withHeaders_withBody_receivesError() throws Exception {
    debugServer.respondWith(NanoHTTPD.Response.Status.UNAUTHORIZED, DefaultApiClient.JSON_SERIALIZER.serialize(new ApiResponse(new ApiError(new ApiServiceException("1", "Invalid Application ID")))));
    apiClient.execute(HttpMethod.POST, "http://127.0.0.1:" + debugServer.getListeningPort(), null, null, MapUtils.map("applicationId", "xyz", "currentRegistrationId", "1234"), MapUtils.map("X-Test-1", "test1", "X-Test-2", "test2"), new SomeApiRequest("Test"), ApiResponse.class);
}
Also used : ApiError(org.infobip.mobile.messaging.api.support.http.client.model.ApiError) ApiServiceException(org.infobip.mobile.messaging.api.support.http.client.model.ApiServiceException) ApiResponse(org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse) Test(org.junit.Test)

Aggregations

ApiResponse (org.infobip.mobile.messaging.api.support.http.client.model.ApiResponse)5 ApiError (org.infobip.mobile.messaging.api.support.http.client.model.ApiError)4 ApiServiceException (org.infobip.mobile.messaging.api.support.http.client.model.ApiServiceException)4 Test (org.junit.Test)4 BufferedOutputStream (java.io.BufferedOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 Collection (java.util.Collection)1 Map (java.util.Map)1 ApiBackendException (org.infobip.mobile.messaging.api.support.ApiBackendException)1 ApiBackendExceptionWithContent (org.infobip.mobile.messaging.api.support.ApiBackendExceptionWithContent)1 ApiException (org.infobip.mobile.messaging.api.support.ApiException)1 ApiIOException (org.infobip.mobile.messaging.api.support.ApiIOException)1