use of com.microsoft.appcenter.ingestion.models.one.CommonSchemaLog in project mobile-center-sdk-android by Microsoft.
the class DatabasePersistenceAndroidTest method generateCsLogsWithIKey.
/**
* Utility for getLogsFilteringOutPausedTargetKeys test.
*/
private void generateCsLogsWithIKey(DatabasePersistence persistence, String iKey, int numberOfLogsPerKey) throws PersistenceException {
for (int i = 0; i < numberOfLogsPerKey; i++) {
CommonSchemaLog log = new MockCommonSchemaLog();
log.setVer("3.0");
log.setName("test");
log.setTimestamp(new Date());
log.setIKey(iKey);
log.addTransmissionTarget(iKey + "-token");
persistence.putLog(log, "test", NORMAL);
}
}
use of com.microsoft.appcenter.ingestion.models.one.CommonSchemaLog in project mobile-center-sdk-android by Microsoft.
the class OneCollectorIngestion method sendAsync.
@Override
public ServiceCall sendAsync(String appSecret, UUID installId, LogContainer logContainer, ServiceCallback serviceCallback) throws IllegalArgumentException {
super.sendAsync(appSecret, installId, logContainer, serviceCallback);
/* Gather API keys from logs. */
Map<String, String> headers = new HashMap<>();
Set<String> apiKeys = new LinkedHashSet<>();
for (Log log : logContainer.getLogs()) {
apiKeys.addAll(log.getTransmissionTargetTokens());
}
/* Build the header. String.join with iterable is only API level 26+. */
StringBuilder apiKey = new StringBuilder();
for (String targetToken : apiKeys) {
apiKey.append(targetToken).append(",");
}
if (!apiKeys.isEmpty()) {
apiKey.deleteCharAt(apiKey.length() - 1);
}
headers.put(API_KEY, apiKey.toString());
/* Gather tokens from logs. */
JSONObject tickets = new JSONObject();
for (Log log : logContainer.getLogs()) {
List<String> ticketKeys = ((CommonSchemaLog) log).getExt().getProtocol().getTicketKeys();
if (ticketKeys != null) {
for (String ticketKey : ticketKeys) {
String token = TicketCache.getTicket(ticketKey);
if (token != null) {
try {
tickets.put(ticketKey, token);
} catch (JSONException e) {
AppCenterLog.error(LOG_TAG, "Cannot serialize tickets, sending log anonymously", e);
break;
}
}
}
}
}
/* Pass ticket header if we have at least 1 token. */
if (tickets.length() > 0) {
headers.put(TICKETS, tickets.toString());
/* Enable 400 errors on invalid tickets on debug builds. */
if (Constants.APPLICATION_DEBUGGABLE) {
headers.put(STRICT, Boolean.TRUE.toString());
}
}
/* Content type. */
headers.put(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE);
/* Client version (no import to avoid Javadoc issue). */
String sdkVersion = com.microsoft.appcenter.BuildConfig.VERSION_NAME;
headers.put(CLIENT_VERSION_KEY, String.format(CLIENT_VERSION_FORMAT, sdkVersion));
/* Upload time */
headers.put(UPLOAD_TIME_KEY, String.valueOf(System.currentTimeMillis()));
/* Make the call. */
HttpClient.CallTemplate callTemplate = new IngestionCallTemplate(mLogSerializer, logContainer);
return getServiceCall(getLogUrl(), METHOD_POST, headers, callTemplate, serviceCallback);
}
use of com.microsoft.appcenter.ingestion.models.one.CommonSchemaLog in project mobile-center-sdk-android by Microsoft.
the class DatabasePersistence method putLog.
@Override
public long putLog(@NonNull Log log, @NonNull String group, @IntRange(from = Flags.NORMAL, to = Flags.CRITICAL) int flags) throws PersistenceException {
/* Convert log to JSON string and put in the database. */
try {
AppCenterLog.debug(LOG_TAG, "Storing a log to the Persistence database for log type " + log.getType() + " with flags=" + flags);
String payload = getLogSerializer().serializeLog(log);
ContentValues contentValues;
// noinspection CharsetObjectCanBeUsed min API level 19 required to fix this warning.
int payloadSize = payload.getBytes("UTF-8").length;
boolean isLargePayload = payloadSize >= PAYLOAD_MAX_SIZE;
String targetKey;
String targetToken;
if (log instanceof CommonSchemaLog) {
if (isLargePayload) {
throw new PersistenceException("Log is larger than " + PAYLOAD_MAX_SIZE + " bytes, cannot send to OneCollector.");
}
targetToken = log.getTransmissionTargetTokens().iterator().next();
targetKey = PartAUtils.getTargetKey(targetToken);
targetToken = CryptoUtils.getInstance(mContext).encrypt(targetToken);
} else {
targetKey = null;
targetToken = null;
}
long maxSize = mDatabaseManager.getMaxSize();
if (maxSize == -1) {
throw new PersistenceException("Failed to store a log to the Persistence database.");
}
if (!isLargePayload && maxSize <= payloadSize) {
throw new PersistenceException("Log is too large (" + payloadSize + " bytes) to store in database. " + "Current maximum database size is " + maxSize + " bytes.");
}
contentValues = getContentValues(group, isLargePayload ? null : payload, targetToken, log.getType(), targetKey, Flags.getPersistenceFlag(flags, false));
long databaseId = mDatabaseManager.put(contentValues, COLUMN_PRIORITY);
if (databaseId == -1) {
throw new PersistenceException("Failed to store a log to the Persistence database for log type " + log.getType() + ".");
}
AppCenterLog.debug(LOG_TAG, "Stored a log to the Persistence database for log type " + log.getType() + " with databaseId=" + databaseId);
if (isLargePayload) {
AppCenterLog.debug(LOG_TAG, "Payload is larger than what SQLite supports, storing payload in a separate file.");
File directory = getLargePayloadGroupDirectory(group);
// noinspection ResultOfMethodCallIgnored we'll get an error anyway at write time.
directory.mkdir();
File payloadFile = getLargePayloadFile(directory, databaseId);
try {
FileManager.write(payloadFile, payload);
} catch (IOException e) {
/* Remove database entry if we cannot save payload as a file. */
mDatabaseManager.delete(databaseId);
throw e;
}
AppCenterLog.debug(LOG_TAG, "Payload written to " + payloadFile);
}
return databaseId;
} catch (JSONException e) {
throw new PersistenceException("Cannot convert to JSON string.", e);
} catch (IOException e) {
throw new PersistenceException("Cannot save large payload in a file.", e);
}
}
use of com.microsoft.appcenter.ingestion.models.one.CommonSchemaLog in project mobile-center-sdk-android by Microsoft.
the class OneCollectorIngestionTest method passTickets.
private Map<String, String> passTickets() {
/* Build some payload. */
final CommonSchemaLog log1 = mock(CommonSchemaLog.class);
final CommonSchemaLog log2 = mock(CommonSchemaLog.class);
final List<String> ticketKeys = new ArrayList<String>() {
{
add("key1");
add("key2");
add(null);
}
};
TicketCache.putTicket("key2", "value2");
Extensions ext1 = new Extensions() {
{
setProtocol(new ProtocolExtension() {
{
setTicketKeys(ticketKeys);
}
});
}
};
Extensions ext2 = new Extensions() {
{
setProtocol(new ProtocolExtension());
}
};
when(log1.getExt()).thenReturn(ext1);
when(log2.getExt()).thenReturn(ext2);
LogContainer container = new LogContainer() {
{
setLogs(new ArrayList<Log>() {
{
add(log1);
add(log2);
}
});
}
};
/* Configure mock HTTP. */
ServiceCall call = mock(ServiceCall.class);
when(mHttpClient.callAsync(anyString(), anyString(), mHeadersCaptor.capture(), any(HttpClient.CallTemplate.class), any(ServiceCallback.class))).thenReturn(call);
/* Verify call to http client. */
LogSerializer serializer = mock(LogSerializer.class);
OneCollectorIngestion ingestion = new OneCollectorIngestion(mHttpClient, serializer);
ingestion.setLogUrl("http://mock");
ServiceCallback serviceCallback = mock(ServiceCallback.class);
assertEquals(call, ingestion.sendAsync(null, null, container, serviceCallback));
/* Verify call to http client. */
Map<String, String> headers = mHeadersCaptor.getValue();
assertTrue(headers.containsKey(TICKETS));
assertEquals("{\"key2\":\"value2\"}", headers.get(TICKETS));
return headers;
}
use of com.microsoft.appcenter.ingestion.models.one.CommonSchemaLog in project mobile-center-sdk-android by Microsoft.
the class OneCollectorIngestionTest method sendAsync.
@Test
public void sendAsync() throws Exception {
/* Mock time. */
mockStatic(System.class);
when(System.currentTimeMillis()).thenReturn(1234L);
/* Build some payload. */
Extensions ext = new Extensions() {
{
setProtocol(new ProtocolExtension());
}
};
final CommonSchemaLog log1 = mock(CommonSchemaLog.class);
when(log1.getExt()).thenReturn(ext);
when(log1.getTransmissionTargetTokens()).thenReturn(Collections.singleton("token1"));
final CommonSchemaLog log2 = mock(CommonSchemaLog.class);
when(log2.getExt()).thenReturn(ext);
when(log2.getTransmissionTargetTokens()).thenReturn(new HashSet<>(Arrays.asList("token2", "token3")));
LogContainer container = new LogContainer() {
{
setLogs(new ArrayList<Log>() {
{
add(log1);
add(log2);
}
});
}
};
LogSerializer serializer = mock(LogSerializer.class);
when(serializer.serializeLog(log1)).thenReturn("mockPayload1");
when(serializer.serializeLog(log2)).thenReturn("mockPayload2");
/* Configure mock HTTP. */
ServiceCall call = mock(ServiceCall.class);
ArgumentCaptor<HttpClient.CallTemplate> callTemplate = ArgumentCaptor.forClass(HttpClient.CallTemplate.class);
when(mHttpClient.callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), callTemplate.capture(), any(ServiceCallback.class))).thenReturn(call);
/* Test calling code. */
OneCollectorIngestion ingestion = new OneCollectorIngestion(mHttpClient, serializer);
ingestion.setLogUrl("http://mock");
ServiceCallback serviceCallback = mock(ServiceCallback.class);
assertEquals(call, ingestion.sendAsync(null, null, container, serviceCallback));
/* Verify call to http client. */
HashMap<String, String> expectedHeaders = new HashMap<>();
expectedHeaders.put(OneCollectorIngestion.API_KEY, "token1,token2,token3");
expectedHeaders.put(OneCollectorIngestion.CLIENT_VERSION_KEY, String.format("ACS-Android-Java-no-%s-no", VERSION_NAME));
expectedHeaders.put(OneCollectorIngestion.UPLOAD_TIME_KEY, "1234");
expectedHeaders.put(DefaultHttpClient.CONTENT_TYPE_KEY, "application/x-json-stream; charset=utf-8");
verify(mHttpClient).callAsync(eq("http://mock"), eq(METHOD_POST), eq(expectedHeaders), notNull(HttpClient.CallTemplate.class), eq(serviceCallback));
assertNotNull(callTemplate.getValue());
assertEquals("mockPayload1\nmockPayload2\n", callTemplate.getValue().buildRequestBody());
/* Verify close. */
ingestion.close();
verify(mHttpClient).close();
/* Verify reopen. */
ingestion.reopen();
verify(mHttpClient).reopen();
}
Aggregations