Search in sources :

Example 1 with NetworkStateHelper

use of com.microsoft.appcenter.utils.NetworkStateHelper in project mobile-center-sdk-android by Microsoft.

the class Distribute method getLatestReleaseDetails.

/**
 * Get latest release details from server.
 *
 * @param distributionGroupId distribution group id.
 * @param updateToken         token to secure API call.
 */
@VisibleForTesting
synchronized void getLatestReleaseDetails(String distributionGroupId, String updateToken) {
    AppCenterLog.debug(LOG_TAG, "Get latest release details...");
    HttpClientRetryer retryer = new HttpClientRetryer(new DefaultHttpClient());
    NetworkStateHelper networkStateHelper = NetworkStateHelper.getSharedInstance(mContext);
    HttpClient httpClient = new HttpClientNetworkStateHandler(retryer, networkStateHelper);
    String releaseHash = computeReleaseHash(mPackageInfo);
    String url = mApiUrl;
    if (updateToken == null) {
        url += String.format(GET_LATEST_PUBLIC_RELEASE_PATH_FORMAT, mAppSecret, distributionGroupId, releaseHash, getReportingParametersForUpdatedRelease(true, ""));
    } else {
        url += String.format(GET_LATEST_PRIVATE_RELEASE_PATH_FORMAT, mAppSecret, releaseHash, getReportingParametersForUpdatedRelease(false, distributionGroupId));
    }
    Map<String, String> headers = new HashMap<>();
    if (updateToken != null) {
        headers.put(HEADER_API_TOKEN, updateToken);
    }
    final Object releaseCallId = mCheckReleaseCallId = new Object();
    mCheckReleaseApiCall = httpClient.callAsync(url, METHOD_GET, headers, new HttpClient.CallTemplate() {

        @Override
        public String buildRequestBody() throws JSONException {
            /* Only GET is used by Distribute service. This method is never getting called. */
            return null;
        }

        @Override
        public void onBeforeCalling(URL url, Map<String, String> headers) {
            if (AppCenterLog.getLogLevel() <= VERBOSE) {
                /* Log url. */
                String urlString = url.toString().replaceAll(mAppSecret, HttpUtils.hideSecret(mAppSecret));
                AppCenterLog.verbose(LOG_TAG, "Calling " + urlString + "...");
                /* Log headers. */
                Map<String, String> logHeaders = new HashMap<>(headers);
                String apiToken = logHeaders.get(HEADER_API_TOKEN);
                if (apiToken != null) {
                    logHeaders.put(HEADER_API_TOKEN, HttpUtils.hideSecret(apiToken));
                }
                AppCenterLog.verbose(LOG_TAG, "Headers: " + logHeaders);
            }
        }
    }, new ServiceCallback() {

        @Override
        public void onCallSucceeded(final String payload) {
            /* onPostExecute is not always called on UI thread due to an old Android bug. */
            HandlerUtils.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        handleApiCallSuccess(releaseCallId, payload, ReleaseDetails.parse(payload));
                    } catch (JSONException e) {
                        onCallFailed(e);
                    }
                }
            });
        }

        @Override
        public void onCallFailed(Exception e) {
            handleApiCallFailure(releaseCallId, e);
        }
    });
}
Also used : HashMap(java.util.HashMap) JSONException(org.json.JSONException) DefaultHttpClient(com.microsoft.appcenter.http.DefaultHttpClient) DEFAULT_INSTALL_URL(com.microsoft.appcenter.distribute.DistributeConstants.DEFAULT_INSTALL_URL) DEFAULT_API_URL(com.microsoft.appcenter.distribute.DistributeConstants.DEFAULT_API_URL) URL(java.net.URL) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) HttpException(com.microsoft.appcenter.http.HttpException) ActivityNotFoundException(android.content.ActivityNotFoundException) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) HttpClientRetryer(com.microsoft.appcenter.http.HttpClientRetryer) DefaultHttpClient(com.microsoft.appcenter.http.DefaultHttpClient) HttpClient(com.microsoft.appcenter.http.HttpClient) NetworkStateHelper(com.microsoft.appcenter.utils.NetworkStateHelper) HttpClientNetworkStateHandler(com.microsoft.appcenter.http.HttpClientNetworkStateHandler) Map(java.util.Map) HashMap(java.util.HashMap) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 2 with NetworkStateHelper

use of com.microsoft.appcenter.utils.NetworkStateHelper in project mobile-center-sdk-android by Microsoft.

the class HttpClientNetworkStateHandlerTest method networkDownBecomesUp.

@Test
public void networkDownBecomesUp() throws IOException {
    /* Configure mock wrapped API. */
    String url = "http://mock/call";
    Map<String, String> headers = new HashMap<>();
    final HttpClient.CallTemplate callTemplate = mock(HttpClient.CallTemplate.class);
    final ServiceCallback callback = mock(ServiceCallback.class);
    final ServiceCall call = mock(ServiceCall.class);
    HttpClient httpClient = mock(HttpClient.class);
    doAnswer(new Answer<ServiceCall>() {

        @Override
        public ServiceCall answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((ServiceCallback) invocationOnMock.getArguments()[4]).onCallSucceeded("");
            return call;
        }
    }).when(httpClient).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    /* Simulate network down then becomes up. */
    NetworkStateHelper networkStateHelper = mock(NetworkStateHelper.class);
    when(networkStateHelper.isNetworkConnected()).thenReturn(false).thenReturn(true);
    /* Test call. */
    HttpClientNetworkStateHandler decorator = new HttpClientNetworkStateHandler(httpClient, networkStateHelper);
    decorator.callAsync(url, METHOD_GET, headers, callTemplate, callback);
    /* Network is down: no call to target API must be done. */
    verify(httpClient, times(0)).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    verify(callback, times(0)).onCallSucceeded("");
    /* Network now up: call must be done and succeed. */
    decorator.onNetworkStateUpdated(true);
    verify(httpClient).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    verify(callback).onCallSucceeded("");
    /* Close. */
    decorator.close();
    verify(httpClient).close();
}
Also used : HashMap(java.util.HashMap) InvocationOnMock(org.mockito.invocation.InvocationOnMock) NetworkStateHelper(com.microsoft.appcenter.utils.NetworkStateHelper) Test(org.junit.Test)

Example 3 with NetworkStateHelper

use of com.microsoft.appcenter.utils.NetworkStateHelper in project mobile-center-sdk-android by Microsoft.

the class HttpClientNetworkStateHandlerTest method networkLossDuringCall.

@Test
public void networkLossDuringCall() throws InterruptedException, IOException {
    /* Configure mock wrapped API. */
    String url = "http://mock/call";
    Map<String, String> headers = new HashMap<>();
    final HttpClient.CallTemplate callTemplate = mock(HttpClient.CallTemplate.class);
    final ServiceCallback callback = mock(ServiceCallback.class);
    final ServiceCall call = mock(ServiceCall.class);
    HttpClient httpClient = mock(HttpClient.class);
    final AtomicReference<Thread> threadRef = new AtomicReference<>();
    doAnswer(new Answer<ServiceCall>() {

        @Override
        public ServiceCall answer(final InvocationOnMock invocationOnMock) throws Throwable {
            Thread thread = new Thread() {

                @Override
                public void run() {
                    try {
                        sleep(200);
                        ((ServiceCallback) invocationOnMock.getArguments()[4]).onCallSucceeded("mockPayload");
                    } catch (InterruptedException ignore) {
                    }
                }
            };
            thread.start();
            threadRef.set(thread);
            return call;
        }
    }).when(httpClient).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            threadRef.get().interrupt();
            return null;
        }
    }).when(call).cancel();
    /* Simulate network up then down then up again. */
    NetworkStateHelper networkStateHelper = mock(NetworkStateHelper.class);
    when(networkStateHelper.isNetworkConnected()).thenReturn(true).thenReturn(false).thenReturn(true);
    /* Test call. */
    HttpClientNetworkStateHandler decorator = new HttpClientNetworkStateHandler(httpClient, networkStateHelper);
    decorator.callAsync(url, METHOD_GET, headers, callTemplate, callback);
    /* Wait some time. */
    Thread.sleep(100);
    /* Lose network. */
    decorator.onNetworkStateUpdated(false);
    /* Verify that the call was attempted then canceled. */
    verify(httpClient).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    verify(call).cancel();
    verifyNoMoreInteractions(callback);
    /* Then up again. */
    decorator.onNetworkStateUpdated(true);
    verify(httpClient, times(2)).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    Thread.sleep(300);
    verify(callback).onCallSucceeded("mockPayload");
    verifyNoMoreInteractions(callback);
    /* Close. */
    decorator.close();
    verify(httpClient).close();
}
Also used : HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) NetworkStateHelper(com.microsoft.appcenter.utils.NetworkStateHelper) Test(org.junit.Test)

Example 4 with NetworkStateHelper

use of com.microsoft.appcenter.utils.NetworkStateHelper in project mobile-center-sdk-android by Microsoft.

the class HttpClientNetworkStateHandlerTest method cancelRunningCall.

@Test
public void cancelRunningCall() throws InterruptedException, IOException {
    /* Configure mock wrapped API. */
    String url = "http://mock/call";
    Map<String, String> headers = new HashMap<>();
    final HttpClient.CallTemplate callTemplate = mock(HttpClient.CallTemplate.class);
    final ServiceCallback callback = mock(ServiceCallback.class);
    final ServiceCall call = mock(ServiceCall.class);
    HttpClient httpClient = mock(HttpClient.class);
    final AtomicReference<Thread> threadRef = new AtomicReference<>();
    doAnswer(new Answer<ServiceCall>() {

        @Override
        public ServiceCall answer(final InvocationOnMock invocationOnMock) throws Throwable {
            Thread thread = new Thread() {

                @Override
                public void run() {
                    try {
                        sleep(200);
                        ((ServiceCallback) invocationOnMock.getArguments()[4]).onCallSucceeded("mockPayload");
                    } catch (InterruptedException ignored) {
                    }
                }
            };
            thread.start();
            threadRef.set(thread);
            return call;
        }
    }).when(httpClient).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            threadRef.get().interrupt();
            return null;
        }
    }).when(call).cancel();
    /* Simulate network down then becomes up. */
    NetworkStateHelper networkStateHelper = mock(NetworkStateHelper.class);
    when(networkStateHelper.isNetworkConnected()).thenReturn(true);
    /* Test call. */
    HttpClientNetworkStateHandler decorator = new HttpClientNetworkStateHandler(httpClient, networkStateHelper);
    ServiceCall decoratorCall = decorator.callAsync(url, METHOD_GET, headers, callTemplate, callback);
    /* Wait some time. */
    Thread.sleep(100);
    /* Cancel. */
    decoratorCall.cancel();
    /* Verify that the call was attempted then canceled. */
    verify(httpClient).callAsync(eq(url), eq(METHOD_GET), eq(headers), eq(callTemplate), any(ServiceCallback.class));
    verify(call).cancel();
    verifyNoMoreInteractions(callback);
    /* Close. */
    decorator.close();
    verify(httpClient).close();
}
Also used : HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) NetworkStateHelper(com.microsoft.appcenter.utils.NetworkStateHelper) Test(org.junit.Test)

Example 5 with NetworkStateHelper

use of com.microsoft.appcenter.utils.NetworkStateHelper in project mobile-center-sdk-android by Microsoft.

the class RealUserMeasurements method applyEnabledState.

/**
 * React to enable state change.
 *
 * @param enabled current state.
 */
@Override
protected synchronized void applyEnabledState(boolean enabled) {
    if (enabled) {
        /* Snapshot run key for the run to avoid race conditions, we ignore updates. */
        final String rumKey = mRumKey;
        /* Check rum key. */
        if (rumKey == null) {
            AppCenterLog.error(LOG_TAG, "Rum key must be configured before start.");
            return;
        }
        /* Configure HTTP client with no retries but handling network state. */
        NetworkStateHelper networkStateHelper = NetworkStateHelper.getSharedInstance(mContext);
        mHttpClient = new HttpClientNetworkStateHandler(new DefaultHttpClient(), networkStateHelper);
        /* Get configuration. */
        getConfiguration(0, rumKey, mHttpClient);
    } else /* On disabling, cancel everything. */
    if (mHttpClient != null) {
        try {
            mHttpClient.close();
        } catch (IOException e) {
            AppCenterLog.error(LOG_TAG, "Failed to close http client.", e);
        }
        mHttpClient = null;
        mConfiguration = null;
        mTestUrls = null;
    }
}
Also used : NetworkStateHelper(com.microsoft.appcenter.utils.NetworkStateHelper) IOException(java.io.IOException) HttpClientNetworkStateHandler(com.microsoft.appcenter.http.HttpClientNetworkStateHandler) DefaultHttpClient(com.microsoft.appcenter.http.DefaultHttpClient)

Aggregations

NetworkStateHelper (com.microsoft.appcenter.utils.NetworkStateHelper)9 HashMap (java.util.HashMap)8 Test (org.junit.Test)7 InvocationOnMock (org.mockito.invocation.InvocationOnMock)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 Mockito.doAnswer (org.mockito.Mockito.doAnswer)3 Answer (org.mockito.stubbing.Answer)3 DefaultHttpClient (com.microsoft.appcenter.http.DefaultHttpClient)2 HttpClientNetworkStateHandler (com.microsoft.appcenter.http.HttpClientNetworkStateHandler)2 ActivityNotFoundException (android.content.ActivityNotFoundException)1 VisibleForTesting (android.support.annotation.VisibleForTesting)1 DEFAULT_API_URL (com.microsoft.appcenter.distribute.DistributeConstants.DEFAULT_API_URL)1 DEFAULT_INSTALL_URL (com.microsoft.appcenter.distribute.DistributeConstants.DEFAULT_INSTALL_URL)1 HttpClient (com.microsoft.appcenter.http.HttpClient)1 HttpClientRetryer (com.microsoft.appcenter.http.HttpClientRetryer)1 HttpException (com.microsoft.appcenter.http.HttpException)1 ServiceCallback (com.microsoft.appcenter.http.ServiceCallback)1 IOException (java.io.IOException)1 SocketException (java.net.SocketException)1 URISyntaxException (java.net.URISyntaxException)1