Search in sources :

Example 11 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class RealUserMeasurements method testUrl.

/**
 * Test urls one by one.
 */
private synchronized void testUrl(final HttpClient httpClient, final String rumKey, final Iterator<TestUrl> iterator) {
    /* Check if a disable happened while we were waiting for a call result. */
    if (httpClient != mHttpClient) {
        return;
    }
    /* Iterate over next test url. */
    if (iterator.hasNext()) {
        final long startTime = System.currentTimeMillis();
        final TestUrl testUrl = iterator.next();
        AppCenterLog.verbose(LOG_TAG, "Calling " + testUrl.url);
        mHttpClient.callAsync(testUrl.url, METHOD_GET, HEADERS, null, new ServiceCallback() {

            @Override
            public void onCallSucceeded(String payload) {
                testUrl.result = System.currentTimeMillis() - startTime;
                testUrl(httpClient, rumKey, iterator);
            }

            @Override
            public void onCallFailed(Exception e) {
                AppCenterLog.error(LOG_TAG, testUrl.url + " call failed", e);
                testUrl(httpClient, rumKey, iterator);
            }
        });
    } else /* Or report results after last one. */
    {
        try {
            /* Generate report. */
            String reportId = rumUniqueId();
            JSONArray results = new JSONArray();
            for (TestUrl testUrl : mTestUrls) {
                if (testUrl.result != null) {
                    JSONObject result = new JSONObject();
                    result.put("RequestID", testUrl.requestId);
                    result.put("Object", testUrl.object);
                    result.put("Conn", testUrl.conn);
                    result.put("Result", testUrl.result);
                    results.put(result);
                }
            }
            String reportJson = results.toString();
            if (AppCenter.getLogLevel() <= Log.VERBOSE) {
                AppCenterLog.verbose(LOG_TAG, "Report payload=" + results.toString(2));
            }
            /* There can be more than 1 report URL, parse them. */
            JSONArray reportUrls = mConfiguration.getJSONArray("r");
            /* Report. */
            report(httpClient, rumKey, reportUrls, reportJson, reportId, 0);
        } catch (JSONException e) {
            AppCenterLog.error(LOG_TAG, "Failed to generate report.", e);
        }
    }
}
Also used : ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONException(org.json.JSONException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 12 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class RealUserMeasurements method report.

/**
 * Report the results to 1 endpoint at a time, stopping at the first one that succeeds.
 */
private synchronized void report(final HttpClient httpClient, final String rumKey, final JSONArray reportUrls, final String reportJson, final String reportId, final int reportUrlIndex) {
    /* Check if a disable happened while we were waiting for a call result. */
    if (httpClient != mHttpClient) {
        return;
    }
    /* Check if we still have urls to report to. */
    if (reportUrlIndex < reportUrls.length()) {
        try {
            String reportUrl = reportUrls.getString(reportUrlIndex);
            String parameters = URLEncoder.encode(reportJson, "UTF-8");
            reportUrl = String.format(REPORT_URL_FORMAT, reportUrl, reportId, rumKey, parameters);
            final String finalReportUrl = reportUrl;
            AppCenterLog.verbose(LOG_TAG, "Calling " + finalReportUrl);
            mHttpClient.callAsync(finalReportUrl, METHOD_GET, HEADERS, null, new ServiceCallback() {

                @Override
                public void onCallSucceeded(String payload) {
                    AppCenterLog.info(LOG_TAG, "Measurements reported successfully.");
                }

                @Override
                public void onCallFailed(Exception e) {
                    AppCenterLog.error(LOG_TAG, "Failed to report measurements at " + finalReportUrl, e);
                    reportNextUrl();
                }

                private void reportNextUrl() {
                    report(httpClient, rumKey, reportUrls, reportJson, reportId, reportUrlIndex + 1);
                }
            });
        } catch (JSONException | UnsupportedEncodingException e) {
            AppCenterLog.error(LOG_TAG, "Failed to generate report.", e);
        }
    } else {
        AppCenterLog.error(LOG_TAG, "Measurements report failed on all report endpoints.");
    }
}
Also used : ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 13 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class DefaultChannel method sendLogs.

/**
 * Send logs.
 *
 * @param groupState   The group state.
 * @param currentState The current state.
 * @param batch        The log batch.
 * @param batchId      The batch ID.
 */
@MainThread
private synchronized void sendLogs(final GroupState groupState, final int currentState, List<Log> batch, final String batchId) {
    if (checkStateDidNotChange(groupState, currentState)) {
        /* Send logs. */
        LogContainer logContainer = new LogContainer();
        logContainer.setLogs(batch);
        mIngestion.sendAsync(mAppSecret, mInstallId, logContainer, new ServiceCallback() {

            @Override
            public void onCallSucceeded(String payload) {
                mAppCenterHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        handleSendingSuccess(groupState, currentState, batchId);
                    }
                });
            }

            @Override
            public void onCallFailed(final Exception e) {
                mAppCenterHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        handleSendingFailure(groupState, currentState, batchId, e);
                    }
                });
            }
        });
        /* Check for more pending logs. */
        mAppCenterHandler.post(new Runnable() {

            @Override
            public void run() {
                checkPendingLogsAfterPost(groupState, currentState);
            }
        });
    }
}
Also used : ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) LogContainer(com.microsoft.appcenter.ingestion.models.LogContainer) IOException(java.io.IOException) CancellationException(com.microsoft.appcenter.CancellationException) MainThread(android.support.annotation.MainThread)

Example 14 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class DefaultChannelRaceConditionTest method disabledWhileHandlingIngestionSuccess.

@Test
public void disabledWhileHandlingIngestionSuccess() throws Exception {
    /* Set up mocking. */
    final Semaphore beforeCallSemaphore = new Semaphore(0);
    final Semaphore afterCallSemaphore = new Semaphore(0);
    Persistence mockPersistence = mock(Persistence.class);
    when(mockPersistence.countLogs(anyString())).thenReturn(1);
    when(mockPersistence.getLogs(anyString(), eq(1), anyListOf(Log.class))).then(getGetLogsAnswer(1));
    when(mockPersistence.getLogs(anyString(), eq(CLEAR_BATCH_SIZE), anyListOf(Log.class))).then(getGetLogsAnswer(0));
    IngestionHttp mockIngestion = mock(IngestionHttp.class);
    when(mockIngestion.sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class))).then(new Answer<Object>() {

        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            new Thread() {

                @Override
                public void run() {
                    beforeCallSemaphore.acquireUninterruptibly();
                    ((ServiceCallback) invocation.getArguments()[3]).onCallSucceeded("");
                    afterCallSemaphore.release();
                }
            }.start();
            return mock(ServiceCall.class);
        }
    });
    /* Simulate enable module then disable. */
    DefaultChannel channel = new DefaultChannel(mock(Context.class), UUIDUtils.randomUUID().toString(), mockPersistence, mockIngestion, mCoreHandler);
    Channel.GroupListener listener = mock(Channel.GroupListener.class);
    channel.addGroup(TEST_GROUP, 1, BATCH_TIME_INTERVAL, MAX_PARALLEL_BATCHES, listener);
    channel.setEnabled(false);
    channel.setEnabled(true);
    /* Release call to mock ingestion. */
    beforeCallSemaphore.release();
    /* Wait for callback ingestion. */
    afterCallSemaphore.acquireUninterruptibly();
    /* Verify handling success was ignored. */
    verify(listener, never()).onSuccess(any(Log.class));
    verify(listener).onFailure(any(Log.class), argThat(new ArgumentMatcher<Exception>() {

        @Override
        public boolean matches(Object argument) {
            return argument instanceof CancellationException;
        }
    }));
}
Also used : Context(android.content.Context) ServiceCall(com.microsoft.appcenter.http.ServiceCall) Log(com.microsoft.appcenter.ingestion.models.Log) Semaphore(java.util.concurrent.Semaphore) Persistence(com.microsoft.appcenter.persistence.Persistence) IngestionHttp(com.microsoft.appcenter.ingestion.IngestionHttp) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) CancellationException(com.microsoft.appcenter.CancellationException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentMatcher(org.mockito.ArgumentMatcher) LogContainer(com.microsoft.appcenter.ingestion.models.LogContainer) UUID(java.util.UUID) Test(org.junit.Test)

Example 15 with ServiceCallback

use of com.microsoft.appcenter.http.ServiceCallback in project mobile-center-sdk-android by Microsoft.

the class DefaultChannelTest method maxRequests.

@Test
@SuppressWarnings("unchecked")
public void maxRequests() throws Persistence.PersistenceException {
    Persistence mockPersistence = mock(Persistence.class);
    IngestionHttp mockIngestion = mock(IngestionHttp.class);
    /* We make second request return less logs than expected to make sure counter is reset properly. */
    when(mockPersistence.getLogs(any(String.class), anyInt(), any(ArrayList.class))).then(getGetLogsAnswer()).then(getGetLogsAnswer(49)).then(getGetLogsAnswer());
    final List<ServiceCallback> callbacks = new ArrayList<>();
    when(mockIngestion.sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class))).then(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            if (args[3] instanceof ServiceCallback) {
                callbacks.add((ServiceCallback) invocation.getArguments()[3]);
            }
            return null;
        }
    });
    /* Init channel with mocks. */
    DefaultChannel channel = new DefaultChannel(mock(Context.class), UUIDUtils.randomUUID().toString(), mockPersistence, mockIngestion, mCoreHandler);
    channel.addGroup(TEST_GROUP, 50, BATCH_TIME_INTERVAL, MAX_PARALLEL_BATCHES, null);
    /* Enqueue enough logs to be split in N + 1 maximum requests. */
    for (int i = 0; i < 200; i++) {
        channel.enqueue(mock(Log.class), TEST_GROUP);
    }
    verify(mHandler, times(4)).postDelayed(any(Runnable.class), eq(BATCH_TIME_INTERVAL));
    verify(mHandler, times(4)).removeCallbacks(any(Runnable.class));
    /* Verify all logs stored, N requests sent, not log deleted yet. */
    verify(mockPersistence, times(200)).putLog(eq(TEST_GROUP), any(Log.class));
    verify(mockIngestion, times(3)).sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class));
    verify(mockPersistence, never()).deleteLogs(any(String.class), any(String.class));
    /* Make 1 of the call succeed. Verify log deleted. */
    callbacks.get(0).onCallSucceeded("");
    verify(mockPersistence).deleteLogs(any(String.class), any(String.class));
    /* The request N+1 is now unlocked. */
    verify(mockIngestion, times(4)).sendAsync(anyString(), any(UUID.class), any(LogContainer.class), any(ServiceCallback.class));
    /* Unlock all requests and check logs deleted. */
    for (int i = 1; i < 4; i++) callbacks.get(i).onCallSucceeded("");
    verify(mockPersistence, times(4)).deleteLogs(any(String.class), any(String.class));
    /* The counter should be 0 now as we sent data. */
    assertEquals(0, channel.getCounter(TEST_GROUP));
}
Also used : Context(android.content.Context) Log(com.microsoft.appcenter.ingestion.models.Log) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) Persistence(com.microsoft.appcenter.persistence.Persistence) IngestionHttp(com.microsoft.appcenter.ingestion.IngestionHttp) ServiceCallback(com.microsoft.appcenter.http.ServiceCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) LogContainer(com.microsoft.appcenter.ingestion.models.LogContainer) UUID(java.util.UUID) Test(org.junit.Test)

Aggregations

ServiceCallback (com.microsoft.appcenter.http.ServiceCallback)33 InvocationOnMock (org.mockito.invocation.InvocationOnMock)28 ServiceCall (com.microsoft.appcenter.http.ServiceCall)25 Matchers.anyString (org.mockito.Matchers.anyString)25 HttpClientNetworkStateHandler (com.microsoft.appcenter.http.HttpClientNetworkStateHandler)24 Test (org.junit.Test)24 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)19 Activity (android.app.Activity)18 HashMap (java.util.HashMap)13 Context (android.content.Context)10 UUID (java.util.UUID)9 DialogInterface (android.content.DialogInterface)8 LogContainer (com.microsoft.appcenter.ingestion.models.LogContainer)8 Log (com.microsoft.appcenter.ingestion.models.Log)7 Semaphore (java.util.concurrent.Semaphore)6 JSONException (org.json.JSONException)6 Persistence (com.microsoft.appcenter.persistence.Persistence)5 IOException (java.io.IOException)5 IngestionHttp (com.microsoft.appcenter.ingestion.IngestionHttp)4 ArrayList (java.util.ArrayList)4