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);
}
}
}
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.");
}
}
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);
}
});
}
}
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;
}
}));
}
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));
}
Aggregations